Skip to contentSkip to conversation

x86/percpu: Share decrypted storage before guest setup

PATCH In review Zack Rusin 4 participants 20 messages Sep 29 – Oct 2

Subsystems (13)
lore
Share & tools
lore

Zack Rusin

author
#0 lore raw

v2 cover x86/percpu: Share decrypted storage before guest setup

VMware publishes its per-CPU steal-time GPA without first sharing the storage in encrypted guests. Following Kiryl's review, this series moves sharing into early per-CPU initialization for both KVM and VMware. This replaces the VMware fix from Bo Gan and Alexey Makhalov:
https://lore.kernel.org/r/[email protected]

The common helper uses boot-time page-table allocation and preserves initial contents on AMD and TDX. Conversion precedes buffer registration on SMP and UP; failures stop boot. Encrypted guests use the embedded allocator, warn on percpu_alloc=page, and never fall back to page mode. There is no driver conversion loop or readiness flag. .bss..decrypted remains outside this series.

I interpreted the allocator requirement as guest-specific, so both it and per-CPU conversion use CC_ATTR_GUEST_MEM_ENCRYPT and leave bare-metal SME behavior unchanged.

Two corrections to v1: its isolation claim missed UP, where ordinary data could share the decrypted objects' page; patch 1 fixes that separately. TDX's vmalloc constraint concerns private aliases and adjacent accesses through load_unaligned_zeropad(), not just GPA lookup. This series removes the unused declaration macro and adds explicit SMP/UP section boundaries. I have not carried the v1 Ack onto the revised patches; renewed review would be appreciated.

Tested on VMware ESXi with SEV-SNP and TDX guests, and on KVM with SEV and SEV-SNP guests, using SMP and UP kernels.

v1: https://lore.kernel.org/r/[email protected]

Zack Rusin (6):
percpu: Page-align decrypted data in UP kernels
percpu: Bound decrypted storage for all x86 encrypted guests x86/percpu: Require embedded allocation in encrypted guests x86/mm: Provide common early memory decryption x86/tdx: Support early sharing of kernel data x86/percpu: Share decrypted storage before guest CPU setup

 .../admin-guide/kernel-parameters.txt         |   3 +
 arch/x86/coco/sev/core.c                      |  16 ++
 arch/x86/coco/tdx/tdx.c                       |  32 ++++
 arch/x86/hyperv/ivm.c                         |   4 +
 arch/x86/include/asm/mem_encrypt.h            |   9 +-
 arch/x86/include/asm/x86_init.h               |   4 +
 arch/x86/kernel/cpu/vmware.c                  |   2 +-
 arch/x86/kernel/kvm.c                         |  35 -----
 arch/x86/kernel/setup.c                       |   2 +
 arch/x86/kernel/setup_percpu.c                |  14 +-
 arch/x86/mm/mem_encrypt.c                     | 139 ++++++++++++++++++
 arch/x86/mm/mem_encrypt_amd.c                 |  12 +-
 include/asm-generic/vmlinux.lds.h             |  19 ++-
 include/linux/percpu-defs.h                   |   7 +-
 14 files changed, 247 insertions(+), 51 deletions(-)

base-commit: 93f51579e7df248780214094418f205253383cc5

Signature · 1 line
2.53.0
author
#1 lore raw

PATCH v2 1/6 percpu: Page-align decrypted data in UP kernels

Without SMP, DEFINE_PER_CPU_DECRYPTED() places variables in .data..decrypted. Align both ends of that section so that changing a variable's encryption attribute cannot expose unrelated kernel data. Keep the section in permanent data, where UP variables are instantiated.

Fixes 000f8870a47b ("vmlinux.lds.h: Fix placement of '.data..decrypted' section")
---
 include/asm-generic/vmlinux.lds.h | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
include/asm-generic/vmlinux.lds.h +10 -1
index b2988aa12f66..64bc2bfdd2ec 100644
@@ -368,10 +368,19 @@
 /*
  * .data section
  */
+#if defined(CONFIG_AMD_MEM_ENCRYPT) && !defined(CONFIG_SMP)
+#define DATA_DECRYPTED							\
+	. = ALIGN(PAGE_SIZE);						\
+	*(.data..decrypted)						\
+	. = ALIGN(PAGE_SIZE);
+#else
+#define DATA_DECRYPTED	*(.data..decrypted)
+#endif
+
 #define DATA_DATA							\
 	*(.xiptext)							\
 	*(DATA_MAIN)							\
-	*(.data..decrypted)						\
+	DATA_DECRYPTED							\
 	*(.ref.data)							\
 	*(.data..shared_aligned) /* percpu related */			\
 	*(.data..unlikely)						\
Signature · 1 line
2.53.0
#2 lore raw

Re: [PATCH v2 1/6] percpu: Page-align decrypted data in UP kernels

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 7 lines

Without SMP, DEFINE_PER_CPU_DECRYPTED() places variables in .data..decrypted. Align both ends of that section so that changing a variable's encryption attribute cannot expose unrelated kernel data. Keep the section in permanent data, where UP variables are instantiated.

Fixes 000f8870a47b ("vmlinux.lds.h: Fix placement of '.data..decrypted' section")

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author
#3 lore raw

PATCH v2 2/6 percpu: Bound decrypted storage for all x86 encrypted guests

In reply to Zack Rusin

TDX also needs shared per-CPU buffers. Use X86_MEM_ENCRYPT for their definition and placement, and provide page-aligned boundaries so the architecture can convert each CPU's whole section before registration.

Define the boundaries in the SMP template or UP data as appropriate. Drop the unused DECLARE_PER_CPU_DECRYPTED() macro.

---
 include/asm-generic/vmlinux.lds.h | 12 ++++++++----
 include/linux/percpu-defs.h       |  7 ++-----
 2 files changed, 10 insertions(+), 9 deletions(-)
include/asm-generic/vmlinux.lds.h +8 -4
index 64bc2bfdd2ec..145fcdbbe9db 100644
@@ -368,11 +368,13 @@
 /*
  * .data section
  */
-#if defined(CONFIG_AMD_MEM_ENCRYPT) && !defined(CONFIG_SMP)
+#if defined(CONFIG_X86_MEM_ENCRYPT) && !defined(CONFIG_SMP)
 #define DATA_DECRYPTED							\
 	. = ALIGN(PAGE_SIZE);						\
+	__start_percpu_decrypted = .;					\
 	*(.data..decrypted)						\
-	. = ALIGN(PAGE_SIZE);
+	. = ALIGN(PAGE_SIZE);						\
+	__end_percpu_decrypted = .;
 #else
 #define DATA_DECRYPTED	*(.data..decrypted)
 #endif
@@ -1022,11 +1024,13 @@
  * Note: We use a separate section so that only this section gets
  * decrypted to avoid exposing more than we wish.
  */
-#ifdef CONFIG_AMD_MEM_ENCRYPT
+#if defined(CONFIG_X86_MEM_ENCRYPT) && defined(CONFIG_SMP)
 #define PERCPU_DECRYPTED_SECTION					\
 	. = ALIGN(PAGE_SIZE);						\
+	__start_percpu_decrypted = .;					\
 	*(.data..percpu..decrypted)					\
-	. = ALIGN(PAGE_SIZE);
+	. = ALIGN(PAGE_SIZE);						\
+	__end_percpu_decrypted = .;
 #else
 #define PERCPU_DECRYPTED_SECTION
 #endif
include/linux/percpu-defs.h +2 -5
index dbe3267a0a13..fdb666a1b4de 100644
@@ -169,13 +169,10 @@
 	DEFINE_PER_CPU_SECTION(type, name, "..read_mostly")
 
 /*
- * Declaration/definition used for per-CPU variables that should be accessed
+ * Definition used for built-in per-CPU variables that should be accessed
  * as decrypted when memory encryption is enabled in the guest.
  */
-#ifdef CONFIG_AMD_MEM_ENCRYPT
-#define DECLARE_PER_CPU_DECRYPTED(type, name)				\
-	DECLARE_PER_CPU_SECTION(type, name, "..decrypted")
-
+#ifdef CONFIG_X86_MEM_ENCRYPT
 #define DEFINE_PER_CPU_DECRYPTED(type, name)				\
 	DEFINE_PER_CPU_SECTION(type, name, "..decrypted")
 #else
Signature · 1 line
2.53.0
#4 lore raw

Re: [PATCH v2 2/6] percpu: Bound decrypted storage for all x86 encrypted guests

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 10 lines

TDX also needs shared per-CPU buffers. Use X86_MEM_ENCRYPT for their definition and placement, and provide page-aligned boundaries so the architecture can convert each CPU's whole section before registration.

Define the boundaries in the SMP template or UP data as appropriate. Drop the unused DECLARE_PER_CPU_DECRYPTED() macro.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
maintainer
#5 lore raw

Re: [PATCH v2 2/6] percpu: Bound decrypted storage for all x86 encrypted guests

In reply to Zack Rusin
Quoted 26 lines · Zack Rusin

TDX also needs shared per-CPU buffers. Use X86_MEM_ENCRYPT for their definition and placement, and provide page-aligned boundaries so the architecture can convert each CPU's whole section before registration.

Define the boundaries in the SMP template or UP data as appropriate. Drop the unused DECLARE_PER_CPU_DECRYPTED() macro.

---
 include/asm-generic/vmlinux.lds.h | 12 ++++++++----
 include/linux/percpu-defs.h       |  7 ++-----
 2 files changed, 10 insertions(+), 9 deletions(-)
include/asm-generic/vmlinux.lds.h +1 -1
index 64bc2bfdd2ec..145fcdbbe9db 100644
@@ -1022,11 +1024,13 @@
  * Note: We use a separate section so that only this section gets
  * decrypted to avoid exposing more than we wish.
  */
-#ifdef CONFIG_AMD_MEM_ENCRYPT
+#if defined(CONFIG_X86_MEM_ENCRYPT) && defined(CONFIG_SMP)

include/asm-generic/vmlinux.lds.h line 1036

Quoted 10 lines
include/asm-generic/vmlinux.lds.h +3 -1
 #define PERCPU_DECRYPTED_SECTION					\
 	. = ALIGN(PAGE_SIZE);						\
+	__start_percpu_decrypted = .;					\
 	*(.data..percpu..decrypted)					\
-	. = ALIGN(PAGE_SIZE);
+	. = ALIGN(PAGE_SIZE);						\
+	__end_percpu_decrypted = .;
 #else
 #define PERCPU_DECRYPTED_SECTION
 #endif

So you're page aligning something that will get different protection and will thus shatter large pages?

That is somewhat uncool. We like large pages, large pages are good.

author
#6 lore raw

Re: [PATCH v2 2/6] percpu: Bound decrypted storage for all x86 encrypted guests

Quoted 21 lines · Peter Zijlstra
Quoted 6 lines · Zack Rusin
include/asm-generic/vmlinux.lds.h +1 -1
@@ -1022,11 +1024,13 @@
  * Note: We use a separate section so that only this section gets
  * decrypted to avoid exposing more than we wish.
  */
-#ifdef CONFIG_AMD_MEM_ENCRYPT
+#if defined(CONFIG_X86_MEM_ENCRYPT) && defined(CONFIG_SMP)

include/asm-generic/vmlinux.lds.h line 1036

Quoted 10 lines
include/asm-generic/vmlinux.lds.h +3 -1
 #define PERCPU_DECRYPTED_SECTION                                     \
      . = ALIGN(PAGE_SIZE);                                           \
+     __start_percpu_decrypted = .;                                   \
      *(.data..percpu..decrypted)                                     \
-     . = ALIGN(PAGE_SIZE);
+     . = ALIGN(PAGE_SIZE);                                           \
+     __end_percpu_decrypted = .;
 #else
 #define PERCPU_DECRYPTED_SECTION
 #endif

So you're page aligning something that will get different protection and will thus shatter large pages?

Quoted 1 line

That is somewhat uncool. We like large pages, large pages are good.

I'm a huge large pages fan too. I have a poster in my office and everything... And I never do things that are uncool. I have a wwcdd (what would cool dude do) bracelet and I look at it every time I make a decision, which given that I'm old gets on my wife's nerves a lot. That is to say I'm handsome and innocent.

The alignment isn't new. It has been there since ac26963a1175 ("percpu: Introduce DEFINE_PER_CPU_DECRYPTED") under AMD_MEM_ENCRYPT, which common distro kernels enable. This patch extends it to TDX-only builds and adds the boundary symbols. On bare metal and in ordinary guests nothing changes protection, so no large pages are split.

In confidential guests, yes, converting each CPU's page splits the direct map around it. The alignment doesn't cause that: a large mapping can't be part private and part shared, so a converted page can't stay inside one. The alignment only keeps unrelated per-CPU data out of the shared page. Because that page sits in every CPU's per-CPU unit, each 2M mapping that holds one of them becomes 4K mappings, including the ordinary per-CPU data around it. In the layouts we've tested that's most of the first per-CPU chunk.

SMP KVM SEV guests already pay this today. sev_map_percpu_data() converts the same pages for every possible CPU, at the same granularity. What v2 adds is TDX guests and guests on other hypervisors.

Where you're right is that v2 converts in every encrypted guest apart from Hyper-V vTOM, even when nothing uses the pages. VMware only needs them when the steal clock is enabled.

If this is a deal breaker for you for v3 I could convert only when the hypervisor's platform setup says it will use them: VMware when the steal clock is available, KVM when async page faults, steal time or PV EOI are enabled. That decision would be made before the conversion (for KVM that means making it in kvm_init_platform() instead of kvm_guest_init()), so there's still no readiness state, and other confidential guests don't lose large pages to this.

If you'd also like to keep large pages while the steal clock is in use, the alternative is to move these buffers out of the per-CPU area into one tightly packed allocation. That concentrates the splits in that one allocation, so the rest of the per-CPU area keeps its large pages. Kiryl preferred the per-CPU section when we discussed v1, so I'd like to hear from both of you before going that way. fwiw, I'd vastly prefer to first fix the steal-time bug for VMware before trying to do this though (whether it's with this series or a smaller VMware-only fix). x86 kernel team is notoriously opinionated, which isn't a bad thing, but it means that a rewrite of core x86 bits like that will take a long time and it's starting to feel a little like I stepped into something and you're all behind blast doors yelling "cut all the wires you coward!!!" and I'm just confused going "I just came here to get some blueberries".

z

maintainer
#7 lore raw

Re: [PATCH v2 2/6] percpu: Bound decrypted storage for all x86 encrypted guests

Quoted 22 lines · Zack Rusin
Quoted 21 lines · Peter Zijlstra
Quoted 6 lines · Zack Rusin
include/asm-generic/vmlinux.lds.h +1 -1
@@ -1022,11 +1024,13 @@
  * Note: We use a separate section so that only this section gets
  * decrypted to avoid exposing more than we wish.
  */
-#ifdef CONFIG_AMD_MEM_ENCRYPT
+#if defined(CONFIG_X86_MEM_ENCRYPT) && defined(CONFIG_SMP)

include/asm-generic/vmlinux.lds.h line 1036

Quoted 10 lines
include/asm-generic/vmlinux.lds.h +3 -1
 #define PERCPU_DECRYPTED_SECTION                                     \
      . = ALIGN(PAGE_SIZE);                                           \
+     __start_percpu_decrypted = .;                                   \
      *(.data..percpu..decrypted)                                     \
-     . = ALIGN(PAGE_SIZE);
+     . = ALIGN(PAGE_SIZE);                                           \
+     __end_percpu_decrypted = .;
 #else
 #define PERCPU_DECRYPTED_SECTION
 #endif

So you're page aligning something that will get different protection and will thus shatter large pages?

Quoted 7 lines
Quoted 1 line

That is somewhat uncool. We like large pages, large pages are good.

I'm a huge large pages fan too. I have a poster in my office and everything... And I never do things that are uncool. I have a wwcdd (what would cool dude do) bracelet and I look at it every time I make a decision, which given that I'm old gets on my wife's nerves a lot. That is to say I'm handsome and innocent.

:-)

Quoted 5 lines

The alignment isn't new. It has been there since ac26963a1175 ("percpu: Introduce DEFINE_PER_CPU_DECRYPTED") under AMD_MEM_ENCRYPT, which common distro kernels enable. This patch extends it to TDX-only builds and adds the boundary symbols. On bare metal and in ordinary guests nothing changes protection, so no large pages are split.

Right, I saw it is pre-existing, but you made me notice ;-)

Anyway, the thing that wasn't immediately obvious was that we only really change the protection for (sekjoer) guests. This means I mostly don't care.

Quoted 2 lines

In confidential guests, yes, converting each CPU's page splits the direct map around it. The alignment doesn't cause that: a large

Nit you could 2M align, so alignment is somewhat related.

Quoted 6 lines

mapping can't be part private and part shared, so a converted page can't stay inside one. The alignment only keeps unrelated per-CPU data out of the shared page. Because that page sits in every CPU's per-CPU unit, each 2M mapping that holds one of them becomes 4K mappings, including the ordinary per-CPU data around it. In the layouts we've tested that's most of the first per-CPU chunk.

So perhaps a little more invasive would be poking at the per-cpu allocator and having a whole 'decrypted' pcpu_chunk which is 2M aligned or something.

Anyway, as long as this is sekjoer guests only, I really could not be bothered much. Proceed, but perhaps put on a comment in the vmlinux.lds.h to clarify this, for those of us who do not live in coconut land?

author
#8 lore raw

PATCH v2 3/6 x86/percpu: Require embedded allocation in encrypted guests

In reply to Zack Rusin

Early sharing needs direct-mapped per-CPU storage. In TDX, a private direct-map alias of a shared page can terminate the guest, including through load_unaligned_zeropad(). Require embed rather than adding early vmalloc conversion and alias synchronization.

Warn when overriding percpu_alloc=page and let embed failures reach the existing panic. Restrict this policy to encrypted guests, leaving host SME allocation unchanged.

---
 Documentation/admin-guide/kernel-parameters.txt |  3 +++
 arch/x86/kernel/setup_percpu.c                  | 12 ++++++++++--
 2 files changed, 13 insertions(+), 2 deletions(-)
Documentation/admin-guide/kernel-parameters.txt +3 -0
index 33cd30996e47..8ba881af3520 100644
@@ -5347,6 +5347,9 @@ Kernel parameters
 			See comments in mm/percpu.c for details on each
 			allocator.  This parameter is primarily	for debugging
 			and performance comparison.
+			On x86 encrypted guests, only "embed" is supported;
+			"page" is ignored with a warning. An embed allocation
+			failure is fatal instead of falling back to "page".
 
 	pirq=		[SMP,APIC] Manual mp-table setup
 			See Documentation/arch/x86/i386/IO-APIC.rst.
arch/x86/kernel/setup_percpu.c +10 -2
index bfa48e7a32a2..c83c61e0b20a 100644
@@ -8,6 +8,7 @@
 #include <linux/percpu.h>
 #include <linux/kexec.h>
 #include <linux/crash_dump.h>
+#include <linux/cc_platform.h>
 #include <linux/smp.h>
 #include <linux/topology.h>
 #include <linux/pfn.h>
@@ -112,6 +113,7 @@ void __init setup_per_cpu_areas(void)
 {
 	unsigned int cpu;
 	unsigned long delta;
+	bool encrypted = cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT);
 	int rc;
 
 	pr_info("NR_CPUS:%d nr_cpumask_bits:%d nr_cpu_ids:%u nr_node_ids:%u\n",
@@ -127,6 +129,12 @@ void __init setup_per_cpu_areas(void)
 	if (pcpu_chosen_fc == PCPU_FC_AUTO && pcpu_need_numa())
 		pcpu_chosen_fc = PCPU_FC_PAGE;
 #endif
+	if (encrypted) {
+		if (pcpu_chosen_fc == PCPU_FC_PAGE)
+			pr_warn("Ignoring percpu_alloc=page in an encrypted guest\n");
+		pcpu_chosen_fc = PCPU_FC_EMBED;
+	}
+
 	rc = -EINVAL;
 	if (pcpu_chosen_fc != PCPU_FC_PAGE) {
 		const size_t dyn_size = PERCPU_MODULE_RESERVE +
@@ -149,11 +157,11 @@ void __init setup_per_cpu_areas(void)
 					    dyn_size, atom_size,
 					    pcpu_cpu_distance,
 					    pcpu_cpu_to_node);
-		if (rc < 0)
+		if (rc < 0 && !encrypted)
 			pr_warn("%s allocator failed (%d), falling back to page size\n",
 				pcpu_fc_names[pcpu_chosen_fc], rc);
 	}
-	if (rc < 0)
+	if (rc < 0 && !encrypted)
 		rc = pcpu_page_first_chunk(PERCPU_FIRST_CHUNK_RESERVE,
 					   pcpu_cpu_to_node);
 	if (rc < 0)
Signature · 1 line
2.53.0
#9 lore raw

Re: [PATCH v2 3/6] x86/percpu: Require embedded allocation in encrypted guests

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 5 lines

Early sharing needs direct-mapped per-CPU storage. In TDX, a private direct-map alias of a shared page can terminate the guest, including through load_unaligned_zeropad(). Require embed rather than adding early vmalloc conversion and alias synchronization.

Quoted 7 lines

Warn when overriding percpu_alloc=page and let embed failures reach the existing panic. Restrict this policy to encrypted guests, leaving host SME allocation unchanged.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author
#10 lore raw

PATCH v2 4/6 x86/mm: Provide common early memory decryption

In reply to Zack Rusin

Static per-CPU buffers must be shared before the page allocator is ready. Provide a page conversion callback with common early page-table splitting, including the kernel-image alias used by UP data. Flush large translations before changing attributes and retain the AMD content and SNP transitions. Drop UP image aliases before SNP kexec makes the backing pages private.

---
 arch/x86/coco/sev/core.c           |  16 +++++
 arch/x86/include/asm/mem_encrypt.h |   7 ++-
 arch/x86/include/asm/x86_init.h    |   2 +
 arch/x86/mm/mem_encrypt.c          | 117 +++++++++++++++++++++++++++++++++++++
 arch/x86/mm/mem_encrypt_amd.c      |  12 +++-
 5 files changed, 149 insertions(+), 5 deletions(-)
arch/x86/coco/sev/core.c +16 -0
index cc292d7c6fd1..bc1afa366c33 100644
@@ -541,6 +541,10 @@ static void set_pte_enc(pte_t *kpte, int level, void *va)
 	set_pte_enc_mask(kpte, d.pfn, d.new_pgprot);
 }
 
+#ifndef CONFIG_SMP
+extern char __start_percpu_decrypted[], __end_percpu_decrypted[];
+#endif
+
 static void unshare_all_memory(void)
 {
 	unsigned long addr, end, size, ghcb;
@@ -550,6 +554,18 @@ static void unshare_all_memory(void)
 	pte_t *pte;
 	int cpu;
 
+#ifndef CONFIG_SMP
+	/* Drop image aliases before the direct-map walk makes pages private. */
+	addr = (unsigned long)__start_percpu_decrypted;
+	end = (unsigned long)__end_percpu_decrypted;
+	for (; addr < end; addr += PAGE_SIZE) {
+		pte = lookup_address(addr, &level);
+		if (pte && pte_decrypted(*pte))
+			set_pte(pte, __pte(0));
+	}
+	__flush_tlb_all();
+#endif
+
 	/* Unshare the direct mapping. */
 	addr = PAGE_OFFSET;
 	end  = PAGE_OFFSET + get_max_mapped();
arch/x86/include/asm/mem_encrypt.h +4 -3
index ea6494628cb0..4d81f693b1d3 100644
@@ -21,9 +21,13 @@ struct boot_params;
 #ifdef CONFIG_X86_MEM_ENCRYPT
 void __init mem_encrypt_init(void);
 void __init mem_encrypt_setup_arch(void);
+int __init early_set_memory_decrypted(unsigned long vaddr, unsigned long size);
+void __init early_set_page_decrypted(unsigned long addr, unsigned long alias);
 #else
 static inline void mem_encrypt_init(void) { }
 static inline void __init mem_encrypt_setup_arch(void) { }
+static inline int __init
+early_set_memory_decrypted(unsigned long vaddr, unsigned long size) { return 0; }
 #endif
 
 #ifdef CONFIG_AMD_MEM_ENCRYPT
@@ -50,7 +54,6 @@ void __init sme_early_init(void);
 void sme_encrypt_kernel(struct boot_params *bp);
 void sme_enable(struct boot_params *bp);
 
-int __init early_set_memory_decrypted(unsigned long vaddr, unsigned long size);
 int __init early_set_memory_encrypted(unsigned long vaddr, unsigned long size);
 void __init early_set_mem_enc_dec_hypercall(unsigned long vaddr,
 					    unsigned long size, bool enc);
@@ -86,8 +89,6 @@ static inline void sme_enable(struct boot_params *bp) { }
 
 static inline void sev_es_init_vc_handling(void) { }
 
-static inline int __init
-early_set_memory_decrypted(unsigned long vaddr, unsigned long size) { return 0; }
 static inline int __init
 early_set_memory_encrypted(unsigned long vaddr, unsigned long size) { return 0; }
 static inline void __init
arch/x86/include/asm/x86_init.h +2 -0
index 953d3199408a..e4131402c783 100644
@@ -75,9 +75,11 @@ struct x86_init_oem {
  *			the kernel pagetables and prepare accessors functions.
  *			Callback must call paging_init(). Called once after the
  *			direct mapping for phys memory is available.
+ * @early_decrypt_page:	Share a direct-mapped page and its optional image alias
  */
 struct x86_init_paging {
 	void (*pagetable_init)(void);
+	int (*early_decrypt_page)(unsigned long addr, unsigned long alias);
 };
 
 /**
arch/x86/mm/mem_encrypt.c +117 -0

127 lines not on this page · raw message

arch/x86/mm/mem_encrypt_amd.c +10 -2
index 2f8c32173972..e854f3a039f7 100644
@@ -459,9 +459,15 @@ static int __init early_set_memory_enc_dec(unsigned long vaddr,
 	return ret;
 }
 
-int __init early_set_memory_decrypted(unsigned long vaddr, unsigned long size)
+static int __init amd_early_decrypt_page(unsigned long addr, unsigned long alias)
 {
-	return early_set_memory_enc_dec(vaddr, size, false);
+	unsigned int level;
+	pte_t *pte = lookup_address(addr, &level);
+
+	__set_clr_pte_enc(pte, PG_LEVEL_4K, false);
+	early_set_page_decrypted(addr, alias);
+	early_set_mem_enc_dec_hypercall(addr, PAGE_SIZE, false);
+	return 0;
 }
 
 int __init early_set_memory_encrypted(unsigned long vaddr, unsigned long size)
@@ -479,6 +485,8 @@ void __init sme_early_init(void)
 	if (!sme_me_mask)
 		return;
 
+	x86_init.paging.early_decrypt_page = amd_early_decrypt_page;
+
 	early_pmd_flags = __sme_set(early_pmd_flags);
 
 	__supported_pte_mask = __sme_set(__supported_pte_mask);
Signature · 1 line
2.53.0
#11 lore raw

Re: [PATCH v2 4/6] x86/mm: Provide common early memory decryption

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 9 lines

Static per-CPU buffers must be shared before the page allocator is ready. Provide a page conversion callback with common early page-table splitting, including the kernel-image alias used by UP data. Flush large translations before changing attributes and retain the AMD content and SNP transitions. Drop UP image aliases before SNP kexec makes the backing pages private.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author
#12 lore raw

PATCH v2 5/6 x86/tdx: Support early sharing of kernel data

In reply to Zack Rusin

Share pages before the page allocator is available, after both their direct-map and kernel-image mappings have been made shared. Preserve initial contents in a private scratch page, matching the AMD early helper, and use the existing MapGPA path and shared-page accounting.

UP per-CPU data has an image alias. Drop shared image mappings before kexec converts their backing pages to private through the direct map.

---
 arch/x86/coco/tdx/tdx.c | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
arch/x86/coco/tdx/tdx.c +32 -0
index f904a636d449..4a683e9eafc3 100644
@@ -4,6 +4,7 @@
 #undef pr_fmt
 #define pr_fmt(fmt)     "tdx: " fmt
 
+#include <linux/cacheflush.h>
 #include <linux/cpufeature.h>
 #include <linux/export.h>
 #include <linux/io.h>
@@ -18,6 +19,7 @@
 #include <asm/paravirt_types.h>
 #include <asm/pgtable.h>
+#include <asm/sections.h>
 #include <asm/set_memory.h>
 #include <asm/traps.h>
 
 /* MMIO direction */
@@ -1006,6 +1008,23 @@ static int tdx_enc_status_change_finish(unsigned long vaddr, int numpages,
 	return 0;
 }
 
+static char tdx_early_buffer[PAGE_SIZE] __initdata __aligned(PAGE_SIZE);
+
+static int __init tdx_early_decrypt_page(unsigned long addr, unsigned long alias)
+{
+	void *buffer = __va(__pa_symbol(tdx_early_buffer));
+	int ret;
+
+	memcpy(buffer, (void *)addr, PAGE_SIZE);
+	clflush_cache_range((void *)addr, PAGE_SIZE);
+	early_set_page_decrypted(addr, alias);
+	ret = tdx_enc_status_change_finish(addr, 1, false);
+	if (ret)
+		return ret;
+	memcpy((void *)addr, buffer, PAGE_SIZE);
+	return 0;
+}
+
 /* Stop new private<->shared conversions */
 static void tdx_kexec_begin(void)
 {
@@ -1033,6 +1052,18 @@ static void tdx_kexec_finish(void)
 
 	lockdep_assert_irqs_disabled();
 
+	/* Drop image aliases before the direct-map walk makes pages private. */
+	addr = (unsigned long)_text;
+	while (addr < _brk_end) {
+		unsigned int level;
+		pte_t *pte = lookup_address(addr, &level);
+
+		if (pte && pte_decrypted(*pte))
+			set_pte(pte, __pte(0));
+		addr = (addr & page_level_mask(level)) + page_level_size(level);
+	}
+	__flush_tlb_all();
+
 	addr = PAGE_OFFSET;
 	end  = PAGE_OFFSET + get_max_mapped();
 
@@ -1160,6 +1191,7 @@ void __init tdx_early_init(void)
 	 */
 	x86_platform.guest.enc_status_change_prepare = tdx_enc_status_change_prepare;
 	x86_platform.guest.enc_status_change_finish  = tdx_enc_status_change_finish;
+	x86_init.paging.early_decrypt_page = tdx_early_decrypt_page;
 
 	x86_platform.guest.enc_cache_flush_required  = tdx_cache_flush_required;
 	x86_platform.guest.enc_tlb_flush_required    = tdx_tlb_flush_required;
Signature · 1 line
2.53.0
#13 lore raw

Re: [PATCH v2 5/6] x86/tdx: Support early sharing of kernel data

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 11 lines

Share pages before the page allocator is available, after both their direct-map and kernel-image mappings have been made shared. Preserve initial contents in a private scratch page, matching the AMD early helper, and use the existing MapGPA path and shared-page accounting.

UP per-CPU data has an image alias. Drop shared image mappings before kexec converts their backing pages to private through the direct map.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
author
#14 lore raw

PATCH v2 6/6 x86/percpu: Share decrypted storage before guest CPU setup

In reply to Zack Rusin

Convert every possible CPU's decrypted section after per-CPU setup and before the boot CPU registers its buffers. This replaces KVM's object loop and shares VMware steal-time storage without a driver conversion path or readiness state.

UP KVM registers inside setup_arch(), so convert before guest_late_init() there and move VMware's UP registration to that hook. Stop boot on a conversion failure: inconsistent page state must not be published to the hypervisor. Host SME keeps its existing mappings. Skip Hyper-V vTOM per-CPU storage: its visibility callbacks require later Hyper-V initialization.

---
 arch/x86/hyperv/ivm.c              |  4 ++++
 arch/x86/include/asm/mem_encrypt.h |  2 ++
 arch/x86/include/asm/x86_init.h    |  2 ++
 arch/x86/kernel/cpu/vmware.c       |  2 +-
 arch/x86/kernel/kvm.c              | 35 -----------------------------------
 arch/x86/kernel/setup.c            |  2 ++
 arch/x86/kernel/setup_percpu.c     |  2 ++
 arch/x86/mm/mem_encrypt.c          | 22 ++++++++++++++++++++++
 8 files changed, 35 insertions(+), 36 deletions(-)
arch/x86/hyperv/ivm.c +4 -0
index 2ce4dfe53472..4a5c735c9c52 100644
@@ -887,6 +887,10 @@ void __init hv_vtom_init(void)
 	cc_set_mask(ms_hyperv.shared_gpa_boundary);
 	physical_mask &= ms_hyperv.shared_gpa_boundary - 1;
 
+	/* vTOM has no early per-CPU consumers and needs the Hyper-V setup. */
+	x86_init.paging.skip_percpu_decryption = true;
+	x86_init.paging.early_decrypt_page = NULL;
+
 	x86_platform.hyper.is_private_mmio = hv_is_private_mmio;
 	x86_platform.guest.enc_cache_flush_required = hv_vtom_cache_flush_required;
 	x86_platform.guest.enc_tlb_flush_required = hv_vtom_tlb_flush_required;
arch/x86/include/asm/mem_encrypt.h +2 -0
index 4d81f693b1d3..05cf395407ef 100644
@@ -21,11 +21,13 @@ struct boot_params;
 #ifdef CONFIG_X86_MEM_ENCRYPT
 void __init mem_encrypt_init(void);
 void __init mem_encrypt_setup_arch(void);
+void __init mem_encrypt_init_percpu(void);
 int __init early_set_memory_decrypted(unsigned long vaddr, unsigned long size);
 void __init early_set_page_decrypted(unsigned long addr, unsigned long alias);
 #else
 static inline void mem_encrypt_init(void) { }
 static inline void __init mem_encrypt_setup_arch(void) { }
+static inline void __init mem_encrypt_init_percpu(void) { }
 static inline int __init
 early_set_memory_decrypted(unsigned long vaddr, unsigned long size) { return 0; }
 #endif
arch/x86/include/asm/x86_init.h +2 -0
index e4131402c783..8d1597372eb6 100644
@@ -76,10 +76,12 @@ struct x86_init_oem {
  *			Callback must call paging_init(). Called once after the
  *			direct mapping for phys memory is available.
  * @early_decrypt_page:	Share a direct-mapped page and its optional image alias
+ * @skip_percpu_decryption: Platform does not use early shared per-CPU data
  */
 struct x86_init_paging {
 	void (*pagetable_init)(void);
 	int (*early_decrypt_page)(unsigned long addr, unsigned long alias);
+	bool skip_percpu_decryption;
 };
 
 /**
arch/x86/kernel/cpu/vmware.c +1 -1
index 34b73573b108..b477cc027b18 100644
@@ -366,7 +366,7 @@ static void __init vmware_paravirt_ops_setup(void)
 					      vmware_cpu_down_prepare) < 0)
 			pr_err("vmware_guest: Failed to install cpu hotplug callbacks\n");
 #else
-		vmware_guest_cpu_init();
+		x86_init.hyper.guest_late_init = vmware_guest_cpu_init;
 #endif
 	}
 }
arch/x86/kernel/kvm.c +0 -35
index 6b0a5861ccb8..acb3b7b18ebe 100644
@@ -429,34 +429,6 @@ static u64 kvm_steal_clock(int cpu)
 	return steal;
 }
 
-static inline __init void __set_percpu_decrypted(void *ptr, unsigned long size)
-{
-	early_set_memory_decrypted((unsigned long) ptr, size);
-}
-
-/*
- * Iterate through all possible CPUs and map the memory region pointed
- * by apf_reason, steal_time and kvm_apic_eoi as decrypted at once.
- *
- * Note: we iterate through all possible CPUs to ensure that CPUs
- * hotplugged will have their per-cpu variable already mapped as
- * decrypted.
- */
-static void __init sev_map_percpu_data(void)
-{
-	int cpu;
-
-	if (cc_vendor != CC_VENDOR_AMD ||
-	    !cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
-		return;
-
-	for_each_possible_cpu(cpu) {
-		__set_percpu_decrypted(&per_cpu(apf_reason, cpu), sizeof(apf_reason));
-		__set_percpu_decrypted(&per_cpu(steal_time, cpu), sizeof(steal_time));
-		__set_percpu_decrypted(&per_cpu(kvm_apic_eoi, cpu), sizeof(kvm_apic_eoi));
-	}
-}
-
 static void kvm_guest_cpu_offline(bool shutdown)
 {
 	kvm_disable_steal_time();
@@ -709,12 +681,6 @@ arch_initcall(kvm_alloc_cpumask);
 
 static void __init kvm_smp_prepare_boot_cpu(void)
 {
-	/*
-	 * Map the per-cpu variables as decrypted before kvm_guest_cpu_init()
-	 * shares the guest physical address with the hypervisor.
-	 */
-	sev_map_percpu_data();
-
 	kvm_guest_cpu_init();
 	native_smp_prepare_boot_cpu();
 	kvm_spinlock_init();
@@ -868,7 +834,6 @@ static void __init kvm_guest_init(void)
 				      kvm_cpu_online, kvm_cpu_down_prepare) < 0)
 		pr_err("failed to install cpu hotplug callbacks\n");
 #else
-	sev_map_percpu_data();
 	kvm_guest_cpu_init();
 #endif
 
arch/x86/kernel/setup.c +2 -0
index cda6adb9f69c..8eebd85e59af 100644
@@ -1251,6 +1251,8 @@ void __init setup_arch(char **cmdline_p)
 
 	io_apic_init_mappings();
 
+	if (!IS_ENABLED(CONFIG_SMP))
+		mem_encrypt_init_percpu();
 	x86_init.hyper.guest_late_init();
 
 	e820__reserve_resources();
arch/x86/kernel/setup_percpu.c +2 -0
index c83c61e0b20a..8526ad37a81b 100644
@@ -5,6 +5,7 @@
 #include <linux/export.h>
 #include <linux/init.h>
 #include <linux/memblock.h>
+#include <linux/mem_encrypt.h>
 #include <linux/percpu.h>
 #include <linux/kexec.h>
 #include <linux/crash_dump.h>
@@ -234,4 +235,5 @@ void __init setup_per_cpu_areas(void)
 	 * this call?
 	 */
 	sync_initial_page_table();
+	mem_encrypt_init_percpu();
 }
arch/x86/mm/mem_encrypt.c +22 -0
index c3e239a47b66..d3224607170d 100644
@@ -13,6 +13,7 @@
 #include <linux/cc_platform.h>
 #include <linux/mem_encrypt.h>
 #include <linux/pgalloc.h>
+#include <linux/percpu.h>
 #include <linux/virtio_anchor.h>
 #include <linux/iommu-dma.h>
 
@@ -24,6 +25,8 @@
 
 #include "mm_internal.h"
 
+extern char __percpu __start_percpu_decrypted[], __end_percpu_decrypted[];
+
 static pte_t * __init early_lookup_pte(unsigned long addr)
 {
 	unsigned long pfn, step;
@@ -134,6 +137,25 @@ int __init early_set_memory_decrypted(unsigned long vaddr, unsigned long size)
 	return 0;
 }
 
+void __init mem_encrypt_init_percpu(void)
+{
+	unsigned long size = __end_percpu_decrypted - __start_percpu_decrypted;
+	int cpu, ret;
+
+	if (!cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) ||
+	    x86_init.paging.skip_percpu_decryption)
+		return;
+
+	for_each_possible_cpu(cpu) {
+		unsigned long addr = (unsigned long)
+			per_cpu_ptr(__start_percpu_decrypted, cpu);
+
+		ret = early_set_memory_decrypted(addr, size);
+		if (ret)
+			panic("Cannot share CPU %d per-CPU data (err=%d)", cpu, ret);
+	}
+}
+
 /* Override for DMA direct allocation check - ARCH_HAS_FORCE_DMA_UNENCRYPTED */
 bool force_dma_unencrypted(struct device *dev)
 {
Signature · 1 line
2.53.0
#15 lore raw

Re: [PATCH v2 6/6] x86/percpu: Share decrypted storage before guest CPU setup

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 12 lines

Convert every possible CPU's decrypted section after per-CPU setup and before the boot CPU registers its buffers. This replaces KVM's object loop and shares VMware steal-time storage without a driver conversion path or readiness state.

UP KVM registers inside setup_arch(), so convert before guest_late_init() there and move VMware's UP registration to that hook. Stop boot on a conversion failure: inconsistent page state must not be published to the hypervisor. Host SME keeps its existing mappings. Skip Hyper-V vTOM per-CPU storage: its visibility callbacks require later Hyper-V initialization.

Quoted 4 lines

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
maintainer
#16 lore raw
In reply to Zack Rusin
Quoted 2 lines · Zack Rusin

VMware publishes its per-CPU steal-time GPA without first sharing the storage in encrypted guests.

So this one liner is the only explanation why this patchset exists, AFAICT. So I asked AI. I'm pasting what it said below, at the end.

Is any of it true?

If so, how much and is that the reason this patchset exists?

I.e., you want for vmware monitoring tools to work with CoCo guests.

Yes, no? Anything else?

And looking at your commit messages, they don't really talk about why the patches exist.

And I don't think you know your audience - you're sending a bunch of patches touching arch/x86/ and you throw all that virt gibberish around like it ain't no tomorrow and you're thinking that tip people can follow. And I think we can follow only bits and pieces but all of us will be mostly head-scratching here and probably ignore the whole set.

So perhaps you should lay off your virt hat for a minute and try to explain in an approachable way what you're trying to do so that even non-virt people can follow.

Right now concepts are flying around left and right in that text and I have no clue what's going on here.

Thx.

P.S., here's the AI gunk:

"In this context, “VMware per‑CPU steal‑time GPA” is referring to **Guest Physical Address (GPA)**–based accounting of **CPU steal time per vCPU** inside a VMware virtual machine.

Let’s break the components down:

- **Steal time**

In virtualization, “steal time” is the amount of time a guest CPU *wanted* to run but **was not scheduled by the hypervisor** because the physical CPU was busy running other VMs or host tasks.

Per‑CPU steal time means this is measured **for each vCPU** separately.

- **GPA (Guest Physical Address)**
GPA is the CPU’s view of “physical” memory inside the guest. It’s:
- The address space the guest OS uses for RAM, MMIO, etc.
- Translated by the hypervisor to real host physical memory (or nested translations with EPT/NPT).

- **Why GPA for steal time?**
VMware (and other hypervisors) can expose performance statistics (like steal time, idle time, run time) via:
- Per‑vCPU counters/timers
- Memory‑mapped (GPA‑mapped) structures that the guest can read
- Paravirtual interfaces (e.g., hypercalls, PV drivers) which are often described or backed by GPA regions

So when someone says “VMware per‑CPU steal-time GPA,” they usually mean:

A VMware mechanism where **per‑vCPU steal‑time metrics** are exposed to the guest via data structures located in **guest physical address space**, so the guest OS or monitoring tools can read those counters and attribute lost CPU time per vCPU."

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
author
#17 lore raw

Hi, Boris.

Quoted 8 lines · Borislav Petkov
Quoted 2 lines · Zack Rusin

VMware publishes its per-CPU steal-time GPA without first sharing the storage in encrypted guests.

So this one liner is the only explanation why this patchset exists, AFAICT. So I asked AI. I'm pasting what it said below, at the end.

Is any of it true?

Partly. So steal time tells Linux how much time a virtual CPU spent ready to run but waiting for the hypervisor to schedule it.

For example, during a 100 ms interval, the vCPU might execute for 70 ms and wait for a physical CPU for 30 ms. Reporting those 30 ms helps kernel:
- account for CPU usage accurately: avoid charging applications for time when the hypervisor wasn't running their vCPU.
- make fairer scheduling decisions: base task execution accounting on the CPU time tasks actually received.
- expose host contention: the st field in top and counters in /proc/stat help explain why a VM is slow even though its applications don't appear to consume all available CPU time.

The benefit is greatest on busy or overcommitted hosts. On a host where vCPUs rarely wait, steal time stays near zero.

To make this work the hypervisor writes a running total into a small per-CPU buffer in guest memory, and the guest kernel reads it. More below...

Quoted 5 lines

If so, how much and is that the reason this patchset exists?

I.e., you want for vmware monitoring tools to work with CoCo guests.

Yes, no? Anything else?

If options are binary then "no" :) It's not for monitoring tools, it's for the kernel's own steal-time accounting above, which currently doesn't work in confidential VMware guests. So the issue is that in a confidential guest (AMD SEV SNP, Intel TDX) memory is private by default, so the hypervisor can't read or write it. Any page the hypervisor has to write must first be converted to shared by the guest. Linux gives us the address of the steal-time buffer without converting it. The hypervisor then tries to write into a private page, which doesn't work. Currently ESXi deliberately powers off the VM when that happens. That only affects VMs with the steal clock enabled, which ESXi leaves off by default except for Photon guests. I'll probably change ESXi to just disable steal time when a guest gives us a private page, but that only avoids the power-off; steal time still won't work in these guests without this series.

KVM has the same need for three of its per-CPU buffers (steal time, async page faults and PV EOI). It already converts them, but only on AMD and in its own loop. Kiryl asked on v1 for one common place that converts all such per CPU buffers early, on both AMD and Intel, instead of each hypervisor driver doing it. That's patches 2-6.

Patch 1 fixes an old layout bug in uniprocessor kernels, where these buffers can share a page with unrelated data. The series also fixes SEV and SEV-SNP guests on KVM running kernels built with CONFIG_SMP=n, which currently hang at boot (we reproduced the hang).

Quoted 9 lines

And looking at your commit messages, they don't really talk about why the patches exist.

And I don't think you know your audience - you're sending a bunch of patches touching arch/x86/ and you throw all that virt gibberish around like it ain't no tomorrow and you're thinking that tip people can follow. And I think we can follow only bits and pieces but all of us will be mostly head-scratching here and probably ignore the whole set.

Quoted 3 lines

So perhaps you should lay off your virt hat for a minute and try to explain in an approachable way what you're trying to do so that even non-virt people can follow.

Fair enough. I'll rework the cover letter and the commit messages so each one starts with the problem. The series originally wasn't really touching x86 core parts and I haven't updated it for a larger crowd. Would you like an explanation of steal time, like the above, in the cover as well?

z

maintainer
#18 lore raw
Quoted 13 lines · Zack Rusin

Partly. So steal time tells Linux how much time a virtual CPU spent ready to run but waiting for the hypervisor to schedule it.

For example, during a 100 ms interval, the vCPU might execute for 70 ms and wait for a physical CPU for 30 ms. Reporting those 30 ms helps kernel:
- account for CPU usage accurately: avoid charging applications for time when the hypervisor wasn't running their vCPU.
- make fairer scheduling decisions: base task execution accounting on the CPU time tasks actually received.
- expose host contention: the st field in top and counters in /proc/stat help explain why a VM is slow even though its applications don't appear to consume all available CPU time.

Aaaha, IOW, that's the "st" column here:

$ vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st gu
 1  0      0 1714852   9748  85300    0    0  3793    51 1445    0  0  1 99  0  0  0

In any case, you could keep that helpful explanation in yout 0th message. :)

Quoted 15 lines

If options are binary then "no" :) It's not for monitoring tools, it's for the kernel's own steal-time accounting above, which currently doesn't work in confidential VMware guests. So the issue is that in a confidential guest (AMD SEV SNP, Intel TDX) memory is private by default, so the hypervisor can't read or write it. Any page the hypervisor has to write must first be converted to shared by the guest. Linux gives us the address of the steal-time buffer without converting it. The hypervisor then tries to write into a private page, which doesn't work. Currently ESXi deliberately powers off the VM when that happens. That only affects VMs with the steal clock enabled, which ESXi leaves off by default except for Photon guests. I'll probably change ESXi to just disable steal time when a guest gives us a private page, but that only avoids the power-off; steal time still won't work in these guests without this series.

Quoted 4 lines

KVM has the same need for three of its per-CPU buffers (steal time, async page faults and PV EOI). It already converts them, but only on AMD and in its own loop. Kiryl asked on v1 for one common place that converts all such per CPU buffers early, on both AMD and Intel,

Right, why early?

I mean, I am still trying to see the justification for this diffstat

 14 files changed, 247 insertions(+), 51 deletions(-)

and whether it is really worth it.

Quoted 6 lines

instead of each hypervisor driver doing it. That's patches 2-6.

Patch 1 fixes an old layout bug in uniprocessor kernels, where these buffers can share a page with unrelated data. The series also fixes SEV and SEV-SNP guests on KVM running kernels built with CONFIG_SMP=n, which currently hang at boot (we reproduced the hang).

That should tell you how much we care about UP. We would even love to make SMP the default.

Quoted 5 lines

Fair enough. I'll rework the cover letter and the commit messages so each one starts with the problem. The series originally wasn't really touching x86 core parts and I haven't updated it for a larger crowd. Would you like an explanation of steal time, like the above, in the cover as well?

Yes please.

Also, we have some blurb about how to write those:

https://docs.kernel.org/process/maintainer-tip.html#patch-subject

and

https://docs.kernel.org/process/submitting-patches.html

In talking to Peter about it, we were wondering whether this can be made simpler. Like do not touch perCPU but do a normal page for each CPU's steal time gunk and thus do not split the large page and then that early enc/decrypting of memory I don't like either.

Perhaps we should start with the simplest approach first.

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
author
#19 lore raw
Quoted 16 lines · Borislav Petkov
Quoted 13 lines · Zack Rusin

Partly. So steal time tells Linux how much time a virtual CPU spent ready to run but waiting for the hypervisor to schedule it.

For example, during a 100 ms interval, the vCPU might execute for 70 ms and wait for a physical CPU for 30 ms. Reporting those 30 ms helps kernel:
- account for CPU usage accurately: avoid charging applications for time when the hypervisor wasn't running their vCPU.
- make fairer scheduling decisions: base task execution accounting on the CPU time tasks actually received.
- expose host contention: the st field in top and counters in /proc/stat help explain why a VM is slow even though its applications don't appear to consume all available CPU time.

Quoted 8 lines

Aaaha, IOW, that's the "st" column here:

$ vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st gu
 1  0      0 1714852   9748  85300    0    0  3793    51 1445    0  0  1 99  0  0  0

In any case, you could keep that helpful explanation in yout 0th message. :)

Yeah, that's the one. Sounds good, and thanks for the links to the tip and submitting-patches docs, I'll follow them for v3.

Quoted 15 lines
Quoted 15 lines

If options are binary then "no" :) It's not for monitoring tools, it's for the kernel's own steal-time accounting above, which currently doesn't work in confidential VMware guests. So the issue is that in a confidential guest (AMD SEV SNP, Intel TDX) memory is private by default, so the hypervisor can't read or write it. Any page the hypervisor has to write must first be converted to shared by the guest. Linux gives us the address of the steal-time buffer without converting it. The hypervisor then tries to write into a private page, which doesn't work. Currently ESXi deliberately powers off the VM when that happens. That only affects VMs with the steal clock enabled, which ESXi leaves off by default except for Photon guests. I'll probably change ESXi to just disable steal time when a guest gives us a private page, but that only avoids the power-off; steal time still won't work in these guests without this series.

Quoted 6 lines
Quoted 4 lines

KVM has the same need for three of its per-CPU buffers (steal time, async page faults and PV EOI). It already converts them, but only on AMD and in its own loop. Kiryl asked on v1 for one common place that converts all such per CPU buffers early, on both AMD and Intel,

Right, why early?

Because on SMP kernels both KVM and VMware hand the boot CPU's buffer address to the hypervisor in smp_prepare_boot_cpu(), right after setup_per_cpu_areas() and well before mm_core_init(). Sharing a page usually means splitting the direct map around it, and set_memory_decrypted() needs the page allocator for the new page table. To keep that existing registration point, the common code needed its own early sharing path, which is most of what patches 4 and 5 are.

Quoted 5 lines

I mean, I am still trying to see the justification for this diffstat

 14 files changed, 247 insertions(+), 51 deletions(-)

and whether it is really worth it.

For VMware alone it isn't. But you guys have to decide based on what your long-term plan here is.

I'd be happiest if we stayed within the confines of the VMware code. That's what v1 of this did (besides the small guard fix outside) and I'll only stray from this if I'm explicitly told that a patch/series won't be accepted without some cleanups/re-architecture somewhere else.

I'm here because internally we've had multiple teams needing various bugs/features in the kernel and looking at some parts of our Linux kernel code was making me sad so I decided to collect the changes and use this opportunity to also cleanup some of our code. (I have three other series in my tree, they all touch arch/x86/kernel/cpu/vmware.c so I'm trying to push them out in a semi-coherent order.) But this is very much a spare time thing. I can guarantee I'll find enough time to always review the VMware bits, maintain them and answer questions about them, but I can't do the same for other parts of the kernel. So the more focused we can keep those patches the easier this is for me.

Quoted 9 lines
Quoted 6 lines

instead of each hypervisor driver doing it. That's patches 2-6.

Patch 1 fixes an old layout bug in uniprocessor kernels, where these buffers can share a page with unrelated data. The series also fixes SEV and SEV-SNP guests on KVM running kernels built with CONFIG_SMP=n, which currently hang at boot (we reproduced the hang).

That should tell you how much we care about UP. We would even love to make SMP the default.

hah :) The UP handling was a good chunk of the complexity (patch 1, the kernel-image aliases and their kexec teardown), and the simpler approach below doesn't need any of it.

Quoted 6 lines

In talking to Peter about it, we were wondering whether this can be made simpler. Like do not touch perCPU but do a normal page for each CPU's steal time gunk and thus do not split the large page and then that early enc/decrypting of memory I don't like either.

Perhaps we should start with the simplest approach first.

Sounds good to me, that's pretty much the smaller fix I'd offered on v1. v3 would then be VMware only: if the steal clock is available, allocate the steal-time structs for all possible CPUs once the page allocator is up, share them with set_memory_decrypted(), and register the boot CPU from an early initcall. The existing hotplug callback registers the other CPUs as they come up. The memory comes from the page allocator, so it's in the direct map and TDX's vmalloc problem doesn't come up. No percpu, linker-script or early-conversion changes, and KVM stays as it is. This would also move registration for unencrypted guests to the initcall.

One small tweak: I'd pack all CPUs into one allocation (64 bytes each) rather than use a page per CPU. Sharing a page can still split the large direct map mapping around it, so a page per CPU could split one large mapping per CPU, while a single allocation concentrates those splits in that one allocation. And that only happens in confidential guests with the steal clock enabled.

Kiryl, I know this is the opposite of what you asked for on v1, but it sounds like Boris and Peter would rather start with the VMware-only fix. Shout if you object.

z