Skip to contentSkip to conversation

KVM: Allow alternative providers of guest_memfd backed by PFNMAP memory

RFC PATCH Superseded David Woodhouse 3 participants 24 messages Jul 16 – Jul 17

Subsystems (8)
Media (V4L/DVB) x86 KVM Kselftest +4 more subsystems

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover KVM: Allow alternative providers of guest_memfd backed by PFNMAP memory

For dedicated hosting environments, there are a few reasons to prefer using external PFNMAP memory for guests, rather than kernel-managed memory:

• No struct page overheads

• Easily managed in 1GiB pages (or larger chunks); no fragmentation/THP

• Faster kexec/KHO live update (every millisecond spend faffing around with memory management is an extra millisecond of steal time taken from guests)

Today, there is only one implementation of guest_memfd: the internal shmem-based page cache in virt/kvm/guest_memfd.c. This series allows for other code to provide "a guest_memfd". This is an early path- finding proof of concept tested with AMD SEV-SNP as well as non-CoCo guests on x86 and arm64. I'm planning to build a memory-based file system which gives files for both guest_memfd as well as memory-based storage to allow things like userspace VM and orchestrator stateallows to be passed over KHO/kexec.

This series lifts guest_memfd's operations into a small ops struct and converts KVM's own gmem to use it, so it becomes one implementation among peers rather than the only game in town. It also adapts the SEV-SNP fast paths to page-less operation, plumbs iommufd to map a guest_memfd-backing dma-buf as CPU RAM (not MMIO), and adds the provider->KVM revocation primitive that makes overcommit-style reclaim possible.

It's largely AI-built at the moment. My main design concerns are around that we tell that a given file is "a guest_memfd", and how we plug into IOMMUFD. Presenting a dma-buf was the less intrusive choice because that path already has support for taking pages away, but I'm less convinced that it's the cleaner choice in the long term.

I'll continue to bikeshed it myself, but this is at least functional enough to show the direction and solicit further opinions...

https://git.infradead.org/?p=users/dwmw2/linux.git;a=shortlog;h=gmem-provider

Connor Williamson (1):
KVM: SEV: Remove struct page dependency from SNP gmem paths

David Woodhouse (10):
KVM: selftests: sev_smoke_test: Only run VM types the host offers
KVM: selftests: sev_init2_tests: Derive SEV availability from KVM
KVM: guest_memfd: Introduce guest memory ops and route native gmem through them
iommufd: Look up private-interconnect phys via exporter symbols
iommufd: Plumb dma-buf memory-type (RAM vs MMIO) through the phys map
KVM: guest_memfd: Add ops-driven page revocation
samples/kvm: Add guest_memfd backing sample
selftests/kvm: gmem_provider KVM-only tests
selftests/kvm: gmem_provider iommufd tests
samples/kvm, selftests/kvm: Allow the gmem_provider NVMe DMA test on arm64

 arch/x86/kvm/Makefile                              |   4 +-
 arch/x86/kvm/svm/sev.c                             |  83 ++-
 arch/x86/virt/svm/sev.c                            |  27 +-
 drivers/iommu/iommufd/io_pagetable.h               |   7 +
 drivers/iommu/iommufd/pages.c                      |  49 +-
 include/linux/kvm_host.h                           |  91 +++
 samples/Kconfig                                    |  18 +
 samples/Makefile                                   |   1 +
 samples/kvm/Makefile                               |   2 +
 samples/kvm/gmem_provider.c                        | 651 +++++++++++++++++++++
 samples/kvm/gmem_provider.h                        |  53 ++
 tools/testing/selftests/kvm/Makefile.kvm           |   6 +
 .../selftests/kvm/gmem_provider_nvme_dma_test.c    | 365 ++++++++++++
 .../kvm/x86/gmem_provider_hugepage_test.c          | 130 ++++
 .../selftests/kvm/x86/gmem_provider_iommufd_test.c | 150 +++++
 .../selftests/kvm/x86/gmem_provider_revoke_test.c  | 134 +++++
 .../testing/selftests/kvm/x86/gmem_provider_test.c | 195 ++++++
 .../selftests/kvm/x86/gmem_provider_vfio_test.c    | 134 +++++
 tools/testing/selftests/kvm/x86/sev_init2_tests.c  |  16 +-
 tools/testing/selftests/kvm/x86/sev_smoke_test.c   |   9 +-
 virt/kvm/guest_memfd.c                             | 377 +++++++++---
 virt/kvm/kvm_main.c                                |   6 +-
 virt/kvm/kvm_mm.h                                  |   4 +-
 23 files changed, 2410 insertions(+), 102 deletions(-)
#1 lore raw

RFC PATCH 1/11 KVM: selftests: sev_smoke_test: Only run VM types the host offers

From: David Woodhouse <[email protected]>

sev_smoke_test ran the plain SEV subtest unconditionally, gated only on the X86_FEATURE_SEV CPUID bit, while gating SEV-ES and SNP on the KVM_CAP_VM_TYPES bits. CPUID reporting SEV does not mean KVM offers the SEV VM type: when all SEV ASIDs are assigned to SEV-SNP, KVM_X86_SEV_VM is unavailable even though X86_FEATURE_SEV is set. On such a host the test aborts in KVM_CREATE_VM instead of exercising the available modes.

Gate the SEV subtest on KVM_CAP_VM_TYPES like the others, so the test runs the VM types the host actually offers.

---
 tools/testing/selftests/kvm/x86/sev_smoke_test.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
tools/testing/selftests/kvm/x86/sev_smoke_test.c +8 -1
index 6b2cbe2a90b7..bf27b6187afa 100644
@@ -247,7 +247,14 @@ int main(int argc, char *argv[])
 {
 	TEST_REQUIRE(kvm_cpu_has(X86_FEATURE_SEV));
 
-	test_sev_smoke(guest_sev_code, KVM_X86_SEV_VM, 0);
+	/*
+	 * Only exercise VM types the host actually offers.  CPUID reporting
+	 * SEV does not guarantee KVM offers the SEV VM type: when all SEV
+	 * ASIDs are assigned to SEV-SNP, KVM_X86_SEV_VM is unavailable even
+	 * though X86_FEATURE_SEV is set.  Gate every type on KVM_CAP_VM_TYPES.
+	 */
+	if (kvm_check_cap(KVM_CAP_VM_TYPES) & BIT(KVM_X86_SEV_VM))
+		test_sev_smoke(guest_sev_code, KVM_X86_SEV_VM, 0);
 
 	if (kvm_check_cap(KVM_CAP_VM_TYPES) & BIT(KVM_X86_SEV_ES_VM))
 		test_sev_smoke(guest_sev_es_code, KVM_X86_SEV_ES_VM, SEV_POLICY_ES);

base-commit: 0e35b9b6ec0ffcc5e23cbdec09f5c622ad532b53

Signature · 1 line
2.54.0
#2 lore raw

RFC PATCH 2/11 KVM: selftests: sev_init2_tests: Derive SEV availability from KVM

From: David Woodhouse <[email protected]>

The test asserted that the X86_FEATURE_SEV CPUID bit exactly matches whether KVM offers KVM_X86_SEV_VM. That is not an invariant: when all SEV ASIDs are assigned to SEV-SNP, KVM does not offer the SEV VM type even though CPUID reports SEV, so the test aborts on an SNP-only host.

Derive SEV availability from KVM_CAP_VM_TYPES (as already done for SEV-ES and SNP), assert only the one-way implication that a type offered by KVM is also reported in CPUID, and TEST_REQUIRE() the SEV VM type so the test skips cleanly when it is unavailable.

---
 .../testing/selftests/kvm/x86/sev_init2_tests.c  | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)
tools/testing/selftests/kvm/x86/sev_init2_tests.c +11 -5
index 8db88c355f16..689390c10f7c 100644
@@ -130,12 +130,18 @@ int main(int argc, char *argv[])
 			    KVM_X86_SEV_VMSA_FEATURES,
 			    &supported_vmsa_features);
 
-	have_sev = kvm_cpu_has(X86_FEATURE_SEV);
-	TEST_ASSERT(have_sev == !!(kvm_check_cap(KVM_CAP_VM_TYPES) & BIT(KVM_X86_SEV_VM)),
-		    "sev: KVM_CAP_VM_TYPES (%x) does not match cpuid (checking %x)",
-		    kvm_check_cap(KVM_CAP_VM_TYPES), 1 << KVM_X86_SEV_VM);
+	/*
+	 * Whether a VM type is available depends on KVM, not just CPUID: e.g.
+	 * when all SEV ASIDs are assigned to SEV-SNP, KVM does not offer the
+	 * SEV VM type even though X86_FEATURE_SEV is set.  Derive availability
+	 * from KVM_CAP_VM_TYPES and only assert the one-way implication that a
+	 * type offered by KVM must also be reported in CPUID.
+	 */
+	have_sev = kvm_check_cap(KVM_CAP_VM_TYPES) & BIT(KVM_X86_SEV_VM);
+	TEST_ASSERT(!have_sev || kvm_cpu_has(X86_FEATURE_SEV),
+		    "sev: SEV_VM supported without SEV in CPUID");
 
-	TEST_REQUIRE(kvm_check_cap(KVM_CAP_VM_TYPES) & BIT(KVM_X86_SEV_VM));
+	TEST_REQUIRE(have_sev);
 	have_sev_es = kvm_check_cap(KVM_CAP_VM_TYPES) & BIT(KVM_X86_SEV_ES_VM);
 
 	TEST_ASSERT(!have_sev_es || kvm_cpu_has(X86_FEATURE_SEV_ES),
Signature · 1 line
2.54.0
Reviewed-by on v1 2/11
#3 lore raw

Re: [RFC PATCH 02/11] KVM: selftests: sev_init2_tests: Derive SEV availability from KVM

Quoted 7 lines · David Woodhouse

From: David Woodhouse <[email protected]>

The test asserted that the X86_FEATURE_SEV CPUID bit exactly matches whether KVM offers KVM_X86_SEV_VM. That is not an invariant: when all SEV ASIDs are assigned to SEV-SNP, KVM does not offer the SEV VM type even though CPUID reports SEV, so the test aborts on an SNP-only host.

Quoted 6 lines

Derive SEV availability from KVM_CAP_VM_TYPES (as already done for SEV-ES and SNP), assert only the one-way implication that a type offered by KVM is also reported in CPUID, and TEST_REQUIRE() the SEV VM type so the test skips cleanly when it is unavailable.

#4 lore raw

RFC PATCH 3/11 KVM: SEV: Remove struct page dependency from SNP gmem paths

In reply to David Woodhouse

From: Connor Williamson <[email protected]>

The SNP paths assume every guest_memfd PFN has a struct page and a direct map alias. That is not true for memory handed out by an external guest_memfd provider that backs guest RAM with device or carved-out physical memory (e.g. via mem=), which has no struct page.

Relax the RMP helpers in arch/x86/virt/svm/sev.c:

- psmash(): drop the pfn_valid() gate. PSMASH operates on the RMP entry for a physical address and touches neither the direct map nor struct page.

- adjust_direct_map(): return 0 instead of -EINVAL for a page-less PFN, which has no direct map alias to split. Checked before the 2M range test, which would otherwise reject the span.

- __snp_leak_pages(): compute the struct page per iteration and skip list insertion when it is NULL; a page-less PFN cannot be chained onto the leaked pages list.

And the KVM SNP gmem paths in arch/x86/kvm/svm/sev.c:

- sev_gmem_map_pfn()/sev_gmem_unmap_pfn() fall back to memremap() for the launch-update copy and the CPUID error read-back in sev_gmem_post_populate(). The destination PFN is mapped before the atomic kmap_local_page() of the source, since memremap() may sleep.

- sev_clflush_pfn() falls back to memremap() for the cache flush in sev_gmem_invalidate().

No functional change for page-backed PFNs.

---
 arch/x86/kvm/svm/sev.c  | 83 +++++++++++++++++++++++++++++++++++------
 arch/x86/virt/svm/sev.c | 27 ++++++++++----
 2 files changed, 90 insertions(+), 20 deletions(-)
arch/x86/kvm/svm/sev.c +71 -12
index 427229347876..2be9e3b80d85 100644
@@ -12,6 +12,7 @@
 #include <linux/kvm_host.h>
 #include <linux/kernel.h>
 #include <linux/highmem.h>
+#include <linux/io.h>
 #include <linux/psp.h>
 #include <linux/psp-sev.h>
 #include <linux/pagemap.h>
@@ -2321,6 +2322,30 @@ struct sev_gmem_populate_args {
 	int fw_error;
 };
 
+/*
+ * Map a guest_memfd PFN for CPU access.  A PFN provided by an external
+ * guest_memfd provider may have no struct page, so fall back to memremap()
+ * for those.  Pair each call with sev_gmem_unmap_pfn().
+ */
+static void *sev_gmem_map_pfn(kvm_pfn_t pfn)
+{
+	if (pfn_valid(pfn))
+		return kmap_local_pfn(pfn);
+
+	return memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
+}
+
+static void sev_gmem_unmap_pfn(kvm_pfn_t pfn, void *vaddr)
+{
+	if (!vaddr)
+		return;
+
+	if (pfn_valid(pfn))
+		kunmap_local(vaddr);
+	else
+		memunmap(vaddr);
+}
+
 static int sev_gmem_post_populate(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
 				  struct page *src_page, void *opaque)
 {
@@ -2343,13 +2368,23 @@ static int sev_gmem_post_populate(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
 	}
 
 	if (src_page) {
-		void *src_vaddr = kmap_local_page(src_page);
-		void *dst_vaddr = kmap_local_pfn(pfn);
+		void *dst_vaddr = sev_gmem_map_pfn(pfn);
+		void *src_vaddr;
 
-		memcpy(dst_vaddr, src_vaddr, PAGE_SIZE);
+		if (!dst_vaddr) {
+			ret = -ENOMEM;
+			goto out;
+		}
 
-		kunmap_local(dst_vaddr);
+		/*
+		 * Map the destination (which may be page-less and thus sleep in
+		 * memremap()) before the atomic kmap_local_page() of the source.
+		 */
+		src_vaddr = kmap_local_page(src_page);
+		memcpy(dst_vaddr, src_vaddr, PAGE_SIZE);
 		kunmap_local(src_vaddr);
+
+		sev_gmem_unmap_pfn(pfn, dst_vaddr);
 	}
 
 	ret = rmp_make_private(pfn, gfn << PAGE_SHIFT, PG_LEVEL_4K,
@@ -2379,14 +2414,17 @@ static int sev_gmem_post_populate(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
 	if (ret && !snp_page_reclaim(kvm, pfn) &&
 	    sev_populate_args->type == KVM_SEV_SNP_PAGE_TYPE_CPUID &&
 	    sev_populate_args->fw_error == SEV_RET_INVALID_PARAM) {
-		void *src_vaddr = kmap_local_page(src_page);
-		void *dst_vaddr = kmap_local_pfn(pfn);
+		void *dst_vaddr = sev_gmem_map_pfn(pfn);
+		void *src_vaddr;
 
-		memcpy(src_vaddr, dst_vaddr, PAGE_SIZE);
-		set_page_dirty(src_page);
+		if (dst_vaddr) {
+			src_vaddr = kmap_local_page(src_page);
+			memcpy(src_vaddr, dst_vaddr, PAGE_SIZE);
+			set_page_dirty(src_page);
+			kunmap_local(src_vaddr);
 
-		kunmap_local(dst_vaddr);
-		kunmap_local(src_vaddr);
+			sev_gmem_unmap_pfn(pfn, dst_vaddr);
+		}
 	}
 
 out:
@@ -5117,6 +5155,28 @@ int sev_gmem_prepare(struct kvm *kvm, kvm_pfn_t pfn, gfn_t gfn, int max_order)
 	return 0;
 }
 
+/*
+ * Flush the CPU caches for a guest_memfd PFN.  A PFN from an external
+ * guest_memfd provider may have no direct map alias, so fall back to a
+ * temporary memremap() mapping for the cache flush.
+ */
+static void sev_clflush_pfn(kvm_pfn_t pfn, size_t size)
+{
+	void *va;
+
+	if (pfn_valid(pfn)) {
+		clflush_cache_range(__va(pfn_to_hpa(pfn)), size);
+		return;
+	}
+
+	va = memremap(pfn_to_hpa(pfn), size, MEMREMAP_WB);
+	if (WARN_ON_ONCE(!va))
+		return;
+
+	clflush_cache_range(va, size);
+	memunmap(va);
+}
+
 void sev_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
 {
 	kvm_pfn_t pfn;
@@ -5172,8 +5232,7 @@ void sev_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
 		 * cache entries for these pages before free'ing them back to
 		 * the host.
 		 */
-		clflush_cache_range(__va(pfn_to_hpa(pfn)),
-				    use_2m_update ? PMD_SIZE : PAGE_SIZE);
+		sev_clflush_pfn(pfn, use_2m_update ? PMD_SIZE : PAGE_SIZE);
 next_pfn:
 		pfn += use_2m_update ? PTRS_PER_PMD : 1;
 		cond_resched();
arch/x86/virt/svm/sev.c +19 -8
index 8bcdce98f6dc..3623b52fbb11 100644
@@ -897,8 +897,11 @@ int psmash(u64 pfn)
 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
 		return -ENODEV;
 
-	if (!pfn_valid(pfn))
-		return -EINVAL;
+	/*
+	 * Do not require a struct page.  PSMASH operates on the RMP entry for
+	 * a physical address; a valid PFN with no struct page backing (e.g.
+	 * memory handed out by an external guest_memfd provider) is fine.
+	 */
 
 	/* Binutils version 2.36 supports the PSMASH mnemonic. */
 	asm volatile(".byte 0xF3, 0x0F, 0x01, 0xFF"
@@ -953,8 +956,13 @@ static int adjust_direct_map(u64 pfn, int rmp_level)
 	if (WARN_ON_ONCE(rmp_level > PG_LEVEL_2M))
 		return -EINVAL;
 
+	/*
+	 * A PFN with no struct page has no direct map alias to split, so
+	 * there is nothing to do.  This is checked before the 2M range test
+	 * below, which would otherwise reject the whole span.
+	 */
 	if (!pfn_valid(pfn))
-		return -EINVAL;
+		return 0;
 
 	if (rmp_level == PG_LEVEL_2M &&
 	    (!IS_ALIGNED(pfn, PTRS_PER_PMD) || !pfn_valid(pfn + PTRS_PER_PMD - 1)))
@@ -1060,32 +1068,35 @@ EXPORT_SYMBOL_GPL(rmp_make_shared);
 
 void __snp_leak_pages(u64 pfn, unsigned int npages, bool dump_rmp)
 {
-	struct page *page = pfn_to_page(pfn);
-
 	pr_warn("Leaking PFN range 0x%llx-0x%llx\n", pfn, pfn + npages);
 
 	spin_lock(&snp_leaked_pages_list_lock);
 	while (npages--) {
+		struct page *page = pfn_valid(pfn) ? pfn_to_page(pfn) : NULL;
 
 		/*
 		 * Reuse the page's buddy list for chaining into the leaked
 		 * pages list. This page should not be on a free list currently
 		 * and is also unsafe to be added to a free list.
+		 *
+		 * A page-less PFN (e.g. memory backed by an external
+		 * guest_memfd provider) has no struct page to chain, so it is
+		 * only accounted and, optionally, its RMP entry dumped.
 		 */
-		if (likely(!PageCompound(page)) ||
+		if (page &&
+		    (likely(!PageCompound(page)) ||
 
 			/*
 			 * Skip inserting tail pages of compound page as
 			 * page->buddy_list of tail pages is not usable.
 			 */
-		    (PageHead(page) && compound_nr(page) <= npages))
+		     (PageHead(page) && compound_nr(page) <= npages)))
 			list_add_tail(&page->buddy_list, &snp_leaked_pages_list);
 
 		if (dump_rmp)
 			dump_rmpentry(pfn);
 		snp_nr_leaked_pages++;
 		pfn++;
-		page++;
 	}
 	spin_unlock(&snp_leaked_pages_list_lock);
 }
Signature · 1 line
2.54.0
#5 lore raw

Re: [RFC PATCH 03/11] KVM: SEV: Remove struct page dependency from SNP gmem paths

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] An unprivileged userspace process can trigger a host kernel warning in sev_clflush_pfn()…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] An unprivileged userspace process can trigger a host kernel warning in sev_clflush_pfn(), violating KVM subsystem rules. --

--- Patch [3]: [RFC PATCH 03/11] KVM: SEV: Remove struct page dependency from SNP gmem paths --- commit 23550409886d9ce92ccb0c443cb1bc2d231b31b3
Author: Connor Williamson <[email protected]>

KVM: SEV: Remove struct page dependency from SNP gmem paths

This commit updates KVM SEV-SNP paths to support memory without a struct page by falling back to memremap() instead of relying on kmap_local_page(). It relaxes RMP helpers and updates cache flush paths to handle page-less PFNs.

Quoted 4 lines
arch/x86/kvm/svm/sev.c +0 -0
index 4272293478766..2be9e3b80d85e 100644

[ ... ]

Quoted 10 lines
arch/x86/kvm/svm/sev.c +6 -0
@@ -5117,6 +5155,28 @@ int sev_gmem_prepare(struct kvm *kvm, kvm_pfn_t pfn, gfn_t gfn, int max_order)
 	return 0;
 }
 
+/*
+ * Flush the CPU caches for a guest_memfd PFN.  A PFN from an external
+ * guest_memfd provider may have no direct map alias, so fall back to a
+ * temporary memremap() mapping for the cache flush.
+ */
+static void sev_clflush_pfn(kvm_pfn_t pfn, size_t size)

arch/x86/kvm/svm/sev.c int sev_gmem_prepare(struct kvm *kvm, kvm_pfn_t pfn, gfn_t gfn, int max_order) · line 5173

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+{
+	void *va;
+
+	if (pfn_valid(pfn)) {
+		clflush_cache_range(__va(pfn_to_hpa(pfn)), size);
+		return;
+	}
+
+	va = memremap(pfn_to_hpa(pfn), size, MEMREMAP_WB);
+	if (WARN_ON_ONCE(!va))

[Severity: High]
Is it safe to use WARN_ON_ONCE(!va) here when memremap() fails?

Since userspace can trigger sev_clflush_pfn() during guest_memfd hole-punching (via sev_gmem_invalidate()), an unprivileged process might be able to trigger this warning by inducing memory pressure or vmalloc space exhaustion.

This could result in a host denial of service if panic_on_warn is set.

Should we drop the assertion here to prevent unprivileged userspace from intentionally triggering host warnings?

Quoted 5 lines
arch/x86/kvm/svm/sev.c +5 -0
+		return;
+
+	clflush_cache_range(va, size);
+	memunmap(va);
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/f09647f427565c1789a6979470045aab78661563.1784194290.git.dwmw@amazon.co.uk?part=3
#6 lore raw

RFC PATCH 4/11 KVM: guest_memfd: Introduce guest memory ops and route native gmem through them

In reply to David Woodhouse

From: David Woodhouse <[email protected]>

Guest_memfd today has exactly one backing implementation, hard-wired into virt/kvm/guest_memfd.c. To let other subsystems supply guest memory from an alternate source -- for example a physically contiguous range without struct page, or memory shared with a peer device -- lift the operations into a small vtable and route the built-in gmem through it.

Introduce struct kvm_gmem_ops in <linux/kvm_host.h>: bind / unbind / get_pfn / populate / invalidate for the memory-side operations, plus release / mmap / fallocate for the file-level ones. Every file that can back guest memory is created with one shared struct file_operations, kvm_gmem_fops, and file->private_data points at a struct kvm_gmem_backing whose ->ops field is the per-instance vtable. This mirrors the dma-buf / socket / iommufd pattern: a canonical fops identifies the file (is_kvm_gmem_file() is a plain fops-equality check), and per-instance behaviour is reached via private_data.

Every callback on kvm_gmem_fops -- release, mmap, fallocate, and the memory-side dispatchers already present -- reaches through the ops table, so foreign implementations get a private hook for each and KVM code never has to distinguish "native vs foreign". Native gmem becomes one implementation of the ops (kvm_gmem_native_ops), with the current release/mmap/fallocate bodies moved into kvm_gmem_native_release/_mmap/_fallocate. struct gmem_file gains a struct kvm_gmem_backing as its first member so file->private_data can be reinterpreted uniformly across implementations.

.populate is deliberately left NULL for the built-in path; kvm_gmem_populate() keeps an inline fast path because the current folio-locked + attribute-checked shape of post_populate() does not fit the ops signature cleanly. Wiring that flow through ops is a separate cleanup. .invalidate is likewise NULL for the built-in path, because its invalidations run through inode->i_mapping (truncate, hwpoison, free_folio) rather than an out-of-band notification.

kvm_gmem_unbind() gains a struct kvm * parameter so the dispatcher can pass it to ops->unbind() without keeping a duplicate copy anywhere. The three existing callers in kvm_main.c already have @kvm in scope.

Based on a proof-of-concept by Connor Williamson <[email protected]>.

---
 include/linux/kvm_host.h |  82 ++++++++++
 virt/kvm/guest_memfd.c   | 338 +++++++++++++++++++++++++++++++--------
 virt/kvm/kvm_main.c      |   6 +-
 virt/kvm/kvm_mm.h        |   4 +-
 4 files changed, 359 insertions(+), 71 deletions(-)
include/linux/kvm_host.h +82 -0
index ab8cfaec82d3..b33d2f475042 100644
@@ -621,6 +621,88 @@ static inline bool kvm_slot_has_gmem(const struct kvm_memory_slot *slot)
 	return slot && (slot->flags & KVM_MEM_GUEST_MEMFD);
 }
 
+#ifdef CONFIG_KVM_GUEST_MEMFD
+/*
+ * struct kvm_gmem_ops - vtable a guest_memfd backing implementation exposes.
+ *
+ * Every file that can back KVM guest memory -- KVM's own guest_memfd (see
+ * kvm_gmem_create()) and any other subsystem opting in -- is created with
+ * the shared kvm_gmem_fops (see is_kvm_gmem_file()).  file->private_data on
+ * such a file points at a struct kvm_gmem_backing whose ->ops field is the
+ * per-instance vtable below.  KVM never looks any further; the rest of the
+ * per-file state (allocator, refcount, private xarray, ...) is up to the
+ * implementation and is reached via container_of() from the backing.
+ *
+ * The memory-side callbacks (bind, unbind, get_pfn, populate, invalidate)
+ * are the reason the interface exists.  The file-level callbacks (release,
+ * mmap, fallocate, ...) are dispatched by kvm_gmem_fops so that every
+ * implementation gets a private hook -- see the dispatchers in
+ * virt/kvm/guest_memfd.c.
+ *
+ * get_pfn() contract:
+ *  - *pfn is the host PFN backing @gfn.  It need not have a struct page.
+ *  - *max_order is the largest order KVM may use to map starting at @gfn.
+ *    The implementation MUST clamp it to the physical contiguity and the
+ *    HPA/GPA alignment of the backing, so KVM never builds a huge SPTE that
+ *    spans discontiguous physical memory.
+ *  - If *page is non-NULL on return the caller owns that page reference and
+ *    is responsible for put_page() after use.  If *page is left NULL the PFN
+ *    is treated as non-refcounted, and its lifetime is owned by the
+ *    implementation across bind()/unbind().
+ *
+ * Memory intended to back guest RAM MUST be reported as E820_TYPE_RAM by the
+ * host so KVM maps it write-back (and applies the memory-encryption bit on
+ * encrypted hosts) rather than treating it as MMIO.
+ */
+struct kvm_gmem_ops {
+	/* Memory operations. */
+	int (*bind)(struct file *file, struct kvm *kvm,
+		    struct kvm_memory_slot *slot, loff_t offset);
+	void (*unbind)(struct file *file, struct kvm *kvm,
+		       struct kvm_memory_slot *slot);
+	int (*get_pfn)(struct file *file, struct kvm *kvm,
+		       struct kvm_memory_slot *slot, gfn_t gfn,
+		       kvm_pfn_t *pfn, struct page **page, int *max_order);
+	int (*populate)(struct file *file, struct kvm *kvm,
+			struct kvm_memory_slot *slot, gfn_t gfn,
+			kvm_pfn_t *pfn, struct page *src_page, int order);
+	void (*invalidate)(struct file *file, struct kvm *kvm,
+			   struct kvm_memory_slot *slot,
+			   gfn_t start, gfn_t end);
+
+	/*
+	 * File-level operations, dispatched by kvm_gmem_fops.  These are
+	 * per-instance analogues of the like-named file_operations members,
+	 * with the same semantics.  A NULL entry causes the dispatcher to
+	 * fail the file-level operation with an appropriate errno.
+	 */
+	void (*release)(struct file *file);
+	int (*mmap)(struct file *file, struct vm_area_struct *vma);
+	long (*fallocate)(struct file *file, int mode, loff_t offset,
+			  loff_t len);
+	long (*ioctl)(struct file *file, unsigned int cmd, unsigned long arg);
+};
+
+/*
+ * Anchor placed at file->private_data of every guest_memfd-backing file.
+ * KVM's own gmem embeds it as the first member of struct gmem_file; other
+ * implementations do the same in their own per-fd state.  is_kvm_gmem_file()
+ * (fops-identity check) proves the reinterpretation is safe.
+ */
+struct kvm_gmem_backing {
+	const struct kvm_gmem_ops *ops;
+};
+
+/* Defined in guest_memfd.c; single canonical fops for every gmem file. */
+extern struct file_operations kvm_gmem_fops;
+
+static inline bool is_kvm_gmem_file(struct file *file)
+{
+	return file && file->f_op == &kvm_gmem_fops;
+}
+
+#endif /* CONFIG_KVM_GUEST_MEMFD */
+
 static inline bool kvm_slot_dirty_track_enabled(const struct kvm_memory_slot *slot)
 {
 	return slot->flags & KVM_MEM_LOG_DIRTY_PAGES;
virt/kvm/guest_memfd.c +272 -66

499 lines not on this page · raw message

virt/kvm/kvm_main.c +3 -3
index e44c20c04961..1b670201fafd 100644
@@ -935,7 +935,7 @@ static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
 {
 	if (slot->flags & KVM_MEM_GUEST_MEMFD)
-		kvm_gmem_unbind(slot);
+		kvm_gmem_unbind(kvm, slot);
 
 	kvm_destroy_dirty_bitmap(slot);
 
@@ -1747,7 +1747,7 @@ static void kvm_commit_memory_region(struct kvm *kvm,
 		 * flags-only changes on guest_memfd slots should be impossible.
 		 */
 		if (WARN_ON_ONCE(old->flags & KVM_MEM_GUEST_MEMFD))
-			kvm_gmem_unbind(old);
+			kvm_gmem_unbind(kvm, old);
 
 		/*
 		 * The final quirk.  Free the detached, old slot, but only its
@@ -2118,7 +2118,7 @@ static int kvm_set_memory_region(struct kvm *kvm,
 
 out_unbind:
 	if (mem->flags & KVM_MEM_GUEST_MEMFD)
-		kvm_gmem_unbind(new);
+		kvm_gmem_unbind(kvm, new);
 out:
 	kfree(new);
 	return r;
virt/kvm/kvm_mm.h +2 -2
index 7510ca915dd1..ea0fe74e89d4 100644
@@ -76,7 +76,7 @@ void kvm_gmem_exit(void);
 int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args);
 int kvm_gmem_bind(struct kvm *kvm, struct kvm_memory_slot *slot,
 		  unsigned int fd, uoff_t offset);
-void kvm_gmem_unbind(struct kvm_memory_slot *slot);
+void kvm_gmem_unbind(struct kvm *kvm, struct kvm_memory_slot *slot);
 #else
 static inline int kvm_gmem_init(struct module *module)
 {
@@ -91,7 +91,7 @@ static inline int kvm_gmem_bind(struct kvm *kvm,
 	return -EIO;
 }
 
-static inline void kvm_gmem_unbind(struct kvm_memory_slot *slot)
+static inline void kvm_gmem_unbind(struct kvm *kvm, struct kvm_memory_slot *slot)
 {
 	WARN_ON_ONCE(1);
 }
Signature · 1 line
2.54.0
#7 lore raw

Re: [RFC PATCH 04/11] KVM: guest_memfd: Introduce guest memory ops and route native gmem through them

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Critical] Dropped page reference in `kvm_gmem_populate_one` causes a TOCTOU Use-After-Free on physical…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Critical] Dropped page reference in kvm_gmem_populate_one causes a TOCTOU Use-After-Free on physical pages.
- [High] Use-After-Free (UAF) in kvm_gmem_unbind due to lockless dereference of unrefcounted slot->gmem.file.
- [High] Missing module reference count in kvm_gmem_ops allows foreign backend unload, causing kernel panic.
- [High] kvm_gmem_bind API contract fails to initialize slot->gmem.file, breaking KVM core state tracking. --

--- Patch [4]: [RFC PATCH 04/11] KVM: guest_memfd: Introduce guest memory ops and route native gmem through them --- commit 4ae3212093e20a291a948708162e27b1bb7009da
Author: David Woodhouse <[email protected]>

KVM: guest_memfd: Introduce guest memory ops and route native gmem through them

This commit introduces a kvm_gmem_ops vtable to allow other subsystems to supply guest memory backing. It routes the built-in guest_memfd operations through this vtable and refactors the generic bind, unbind, and populate flows.

Quoted 4 lines
include/linux/kvm_host.h +0 -0
index ab8cfaec82d31..b33d2f4750426 100644

[ ... ]

Quoted 29 lines
include/linux/kvm_host.h +25 -0
@@ -621,6 +621,88 @@ static inline bool kvm_slot_has_gmem(const struct kvm_memory_slot *slot)
 	return slot && (slot->flags & KVM_MEM_GUEST_MEMFD);
 }
 
+#ifdef CONFIG_KVM_GUEST_MEMFD
+/*
+ * struct kvm_gmem_ops - vtable a guest_memfd backing implementation exposes.
+ *
+ * Every file that can back KVM guest memory -- KVM's own guest_memfd (see
+ * kvm_gmem_create()) and any other subsystem opting in -- is created with
+ * the shared kvm_gmem_fops (see is_kvm_gmem_file()).  file->private_data on
+ * such a file points at a struct kvm_gmem_backing whose ->ops field is the
+ * per-instance vtable below.  KVM never looks any further; the rest of the
+ * per-file state (allocator, refcount, private xarray, ...) is up to the
+ * implementation and is reached via container_of() from the backing.
+ *
+ * The memory-side callbacks (bind, unbind, get_pfn, populate, invalidate)
+ * are the reason the interface exists.  The file-level callbacks (release,
+ * mmap, fallocate, ...) are dispatched by kvm_gmem_fops so that every
+ * implementation gets a private hook -- see the dispatchers in
+ * virt/kvm/guest_memfd.c.
+ *
+ * get_pfn() contract:
+ *  - *pfn is the host PFN backing @gfn.  It need not have a struct page.
+ *  - *max_order is the largest order KVM may use to map starting at @gfn.
+ *    The implementation MUST clamp it to the physical contiguity and the
+ *    HPA/GPA alignment of the backing, so KVM never builds a huge SPTE that
+ *    spans discontiguous physical memory.
+ *  - If *page is non-NULL on return the caller owns that page reference and

include/linux/kvm_host.h static inline bool kvm_slot_has_gmem(const struct kvm_memory_slot *slot) · line 658

Quoted 10 lines
include/linux/kvm_host.h +10 -0
+ *    is responsible for put_page() after use.  If *page is left NULL the PFN
+ *    is treated as non-refcounted, and its lifetime is owned by the
+ *    implementation across bind()/unbind().
+ *
+ * Memory intended to back guest RAM MUST be reported as E820_TYPE_RAM by the
+ * host so KVM maps it write-back (and applies the memory-encryption bit on
+ * encrypted hosts) rather than treating it as MMIO.
+ */
+struct kvm_gmem_ops {
+	/* Memory operations. */

[Severity: High]
Is there a missing module reference count in struct kvm_gmem_ops?

The operations table lacks an owner field (like struct module *owner) to pin the backend module.

Since the shared kvm_gmem_fops routes file operations to a foreign backend's vtable, could a user open the guest_memfd, unload the backend module, and then close the file? The release dispatcher would then call into the unloaded module's release hook, potentially causing a kernel panic.

Quoted 2 lines
include/linux/kvm_host.h +2 -0
+	int (*bind)(struct file *file, struct kvm *kvm,
+		    struct kvm_memory_slot *slot, loff_t offset);

[ ... ]

Quoted 4 lines
virt/kvm/guest_memfd.c +0 -0
index db57c5766ab60..2b277468a12f0 100644

[ ... ]

Quoted 1 line
virt/kvm/guest_memfd.c +0 -0
@@ -692,15 +782,51 @@ int kvm_gmem_bind(struct kvm *kvm, struct kvm_memory_slot *slot,

[ ... ]

Quoted 37 lines
virt/kvm/guest_memfd.c +32 -3
+int kvm_gmem_bind(struct kvm *kvm, struct kvm_memory_slot *slot,
+		  unsigned int fd, uoff_t offset)
+{
+	const struct kvm_gmem_ops *ops;
+	struct file *file;
+	int r;
+
+	BUILD_BUG_ON(sizeof(gpa_t) != sizeof(offset));
+	BUILD_BUG_ON(sizeof(gfn_t) != sizeof(slot->gmem.pgoff));
+
+	file = fget(fd);
+	if (!file)
+		return -EBADF;
+
+	ops = kvm_gmem_get_ops(file);
+	if (!ops || !ops->bind || !ops->get_pfn) {
+		r = -EINVAL;
+		goto out;
+	}
+
+	if (!PAGE_ALIGNED(offset)) {
+		r = -EINVAL;
+		goto out;
+	}
 
 	/*
-	 * Drop the reference to the file, even on success.  The file pins KVM,
-	 * not the other way 'round.  Active bindings are invalidated if the
-	 * file is closed before memslots are destroyed.
+	 * On success .bind() associates the fd with @kvm and (if the
+	 * implementation needs it) records the reference that makes the fd
+	 * pin the VM.  A .bind() that returns success is trusted to have
+	 * done so; there is no separate ownership check here.
+	 */
+	r = ops->bind(file, kvm, slot, offset);
+out:
+	/*

virt/kvm/guest_memfd.c int kvm_gmem_bind(struct kvm *kvm, struct kvm_memory_slot *slot, · line 832

Quoted 10 lines
virt/kvm/guest_memfd.c +4 -2
+	 * Drop the reference to the file even on success.  The file pins
+	 * KVM, not the other way 'round: it is the implementation's job to
+	 * invalidate its bindings if the fd is closed before the memslots
+	 * are destroyed.
 	 */
-	r = 0;
-err:
 	fput(file);
 	return r;
 }

[Severity: High]
Does this function miss initializing slot->gmem.file on a successful bind?

KVM core code relies heavily on slot->gmem.file being populated to later call unbind. If a foreign backend succeeds in ops->bind but doesn't intentionally mutate KVM's internal slot->gmem.file state, KVM might never call unbind when the memslot is subsequently freed.

Could this leak backend resources or leave dangling memslot pointers in the backend?

Quoted 1 line
virt/kvm/guest_memfd.c +0 -0
@@ -741,15 +861,41 @@ void kvm_gmem_unbind(struct kvm_memory_slot *slot)

[ ... ]

Quoted 4 lines
virt/kvm/guest_memfd.c +4 -0
+void kvm_gmem_unbind(struct kvm *kvm, struct kvm_memory_slot *slot)
+{
+	const struct kvm_gmem_ops *ops;
+	struct file *file;

virt/kvm/guest_memfd.c void kvm_gmem_unbind(struct kvm_memory_slot *slot) · line 886

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+
+	/*
+	 * Nothing to do if the underlying file was _already_ closed, as
+	 * kvm_gmem_release() invalidates and nullifies all bindings.
+	 */
+	file = READ_ONCE(slot->gmem.file);
+	if (!file)
+		return;
+
+	ops = kvm_gmem_get_ops(file);

[Severity: High]
Is it safe to dereference the file locklessly here?

The generic code previously used get_file_active() to safely obtain a reference. Because kvm_gmem_bind() intentionally drops its reference to the file on success (via fput(file)), userspace can close the guest_memfd concurrently while the memslot is being destroyed.

Could this result in a use-after-free when kvm_gmem_get_ops() attempts to dereference the unrefcounted file pointer?

Quoted 2 lines
virt/kvm/guest_memfd.c +2 -0
+	if (ops && ops->unbind)
+		ops->unbind(file, kvm, slot);

[ ... ]

Quoted 31 lines
virt/kvm/guest_memfd.c +27 -0
@@ -860,11 +1020,50 @@ static long __kvm_gmem_populate(struct kvm *kvm, struct kvm_memory_slot *slot,
 	return ret;
 }
 
+static int kvm_gmem_populate_one(const struct kvm_gmem_ops *ops,
+				      struct file *file, struct kvm *kvm,
+				      struct kvm_memory_slot *slot, gfn_t gfn,
+				      struct page *src_page,
+				      kvm_gmem_populate_cb post_populate,
+				      void *opaque)
+{
+	kvm_pfn_t pfn;
+	int ret;
+
+	/*
+	 * Resolve the PFN via the ops.  A populate() op may also copy
+	 * @src_page into the backing before the arch post_populate() step
+	 * (e.g. SNP LAUNCH_UPDATE); otherwise fall back to get_pfn().
+	 */
+	if (ops->populate)
+		ret = ops->populate(file, kvm, slot, gfn, &pfn,
+				    src_page, 0);
+	else {
+		struct page *ignored_page = NULL;
+
+		ret = ops->get_pfn(file, kvm, slot, gfn, &pfn,
+				   &ignored_page, NULL);
+		/*
+		 * Populate does not consume a refcount on the destination page.
+		 * If get_pfn() handed a refcount back through @page, drop it.
+		 * Implementations whose PFNs aren't refcounted per-call leave

virt/kvm/guest_memfd.c static long __kvm_gmem_populate(struct kvm *kvm, struct kvm_memory_slot *slot, · line 1059

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+		 * @page NULL and this is a no-op.
+		 */
+		if (!ret && ignored_page)
+			put_page(ignored_page);
+	}
+	if (ret)
+		return ret;
+
+	return post_populate(kvm, gfn, pfn, src_page, opaque);
+}

[Severity: Critical]
Does dropping the page reference before calling post_populate() introduce a time-of-check to time-of-use race?

If the backend provides a physical page via get_pfn() and we drop the pin with put_page(ignored_page) early, the page could be concurrently freed and reallocated to another process.

Could this cause the hardware post_populate callback (such as SNP RMPUPDATE) to operate on a physical page that now belongs to an innocent host process, corrupting host memory?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/f09647f427565c1789a6979470045aab78661563.1784194290.git.dwmw@amazon.co.uk?part=4
#8 lore raw

RFC PATCH 5/11 iommufd: Look up private-interconnect phys via exporter symbols

In reply to David Woodhouse

From: David Woodhouse <[email protected]>

The dma-buf phys-map dispatch used by iommufd's IOMMU_IOAS_MAP_FILE path currently knows only about the VFIO PCI exporter (looked up via symbol_get(vfio_pci_dma_buf_iommufd_map)). Widen the dispatch so additional exporters can advertise the same well-known symbol name convention and have their dma-bufs mapped without an explicit iommufd dependency in each exporter's module.

For now the dispatch tries the sample guest_memfd provider's exporter first, then falls back to VFIO PCI, both via symbol_get. This mirrors the pattern the in-tree comment already flags:

"iommufd and vfio have a circular dependency. Future work for a
phys based private interconnect will remove this."

The eventual formal negotiated dma_buf_ops op that returns phys plus a memory-type descriptor will subsume both of these lookups. The next patch plumbs the memory type through iommufd; a follow-up will convert the symbol lookups to the negotiated op.

Based on a proof-of-concept by Connor Williamson <[email protected]>

---
 drivers/iommu/iommufd/pages.c | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
drivers/iommu/iommufd/pages.c +20 -0
index 03c8379bbc34..2d4ea41460fd 100644
@@ -1470,6 +1470,26 @@ sym_vfio_pci_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
 	if (rc != -EOPNOTSUPP)
 		return rc;
 
+	/*
+	 * Prototype: try the sample gmem provider's dma-buf exporter.  This
+	 * mirrors the vfio-pci private-interconnect hook, and (like it) is
+	 * meant to be replaced by a formal negotiated exporter op returning
+	 * phys for iommufd.
+	 */
+	{
+		extern int gmem_provider_dma_buf_iommufd_map(
+			struct dma_buf_attachment *, struct phys_vec *);
+		typeof(&gmem_provider_dma_buf_iommufd_map) gfn;
+
+		gfn = symbol_get(gmem_provider_dma_buf_iommufd_map);
+		if (gfn) {
+			rc = gfn(attachment, phys);
+			symbol_put(gmem_provider_dma_buf_iommufd_map);
+			if (rc != -EOPNOTSUPP)
+				return rc;
+		}
+	}
+
 	if (!IS_ENABLED(CONFIG_VFIO_PCI_DMABUF))
 		return -EOPNOTSUPP;
 
Signature · 1 line
2.54.0
#9 lore raw

Re: [RFC PATCH 05/11] iommufd: Look up private-interconnect phys via exporter symbols

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Mapping guest_memfd CPU RAM as uncached MMIO creates memory attribute aliasing, breaking…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Mapping guest_memfd CPU RAM as uncached MMIO creates memory attribute aliasing, breaking bisection. --

--- Patch [5]: [RFC PATCH 05/11] iommufd: Look up private-interconnect phys via exporter symbols --- commit a4bfbccbc028813d0ddd8502c6dc498ce23a16cb
Author: David Woodhouse <[email protected]>

iommufd: Look up private-interconnect phys via exporter symbols

This commit widens the dma-buf phys-map dispatch in iommufd to support additional exporters by looking up a well-known symbol convention. It initially tries a sample gmem provider before falling back to VFIO PCI.

Quoted 4 lines
drivers/iommu/iommufd/pages.c +0 -0
index 03c8379bbc347..2d4ea41460fdc 100644

[ ... ]

Quoted 11 lines
drivers/iommu/iommufd/pages.c +7 -0
@@ -1470,6 +1470,26 @@ sym_vfio_pci_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
 	if (rc != -EOPNOTSUPP)
 		return rc;
 
+	/*
+	 * Prototype: try the sample gmem provider's dma-buf exporter.  This
+	 * mirrors the vfio-pci private-interconnect hook, and (like it) is
+	 * meant to be replaced by a formal negotiated exporter op returning
+	 * phys for iommufd.
+	 */
+	{

drivers/iommu/iommufd/pages.c sym_vfio_pci_dma_buf_iommufd_map(struct dma_buf_attachment *attachment, · line 1489

Quoted 10 lines
drivers/iommu/iommufd/pages.c +10 -0
+		extern int gmem_provider_dma_buf_iommufd_map(
+			struct dma_buf_attachment *, struct phys_vec *);
+		typeof(&gmem_provider_dma_buf_iommufd_map) gfn;
+
+		gfn = symbol_get(gmem_provider_dma_buf_iommufd_map);
+		if (gfn) {
+			rc = gfn(attachment, phys);
+			symbol_put(gmem_provider_dma_buf_iommufd_map);
+			if (rc != -EOPNOTSUPP)
+				return rc;

[Severity: High]
Will mapping guest_memfd CPU RAM as uncached MMIO cause memory attribute aliasing issues here?

When gmem_provider_dma_buf_iommufd_map returns a physical address for RAM, pfn_reader_fill_dmabuf() will hardcode it as BATCH_MMIO:

drivers/iommu/iommufd/pages.c:pfn_reader_fill_dmabuf() {
    ...
    batch_add_pfn_num(batch, PHYS_PFN(dmabuf->phys.paddr + start),
                      last_index - start_index + 1, BATCH_MMIO);
    ...
}

This causes batch_to_domain() to forcefully strip IOMMU_CACHE and apply IOMMU_MMIO:

drivers/iommu/iommufd/pages.c:batch_to_domain() {
    ...
    if (batch->kind == BATCH_MMIO) {
        iommu_prot &= ~IOMMU_CACHE;
        iommu_prot |= IOMMU_MMIO;
    }
    ...
}

On architectures like ARM64, this memory attribute aliasing between the CPU (cacheable) and the IOMMU (uncached) can lead to a loss of coherency, data corruption, or fatal SErrors.

Since the memory type plumbing is deferred to a later patch, could this intermediate state introduce a bisection breakage if the sample provider is utilized?

Quoted 6 lines
drivers/iommu/iommufd/pages.c +3 -0
+		}
+	}
+
 	if (!IS_ENABLED(CONFIG_VFIO_PCI_DMABUF))
 		return -EOPNOTSUPP;
 
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/f09647f427565c1789a6979470045aab78661563.1784194290.git.dwmw@amazon.co.uk?part=5
#10 lore raw

RFC PATCH 6/11 iommufd: Plumb dma-buf memory-type (RAM vs MMIO) through the phys map

In reply to David Woodhouse

From: David Woodhouse <[email protected]>

iommufd's dma-buf import path programmed the IOMMU unconditionally with BATCH_MMIO (IOMMU_MMIO set, IOMMU_CACHE cleared). This is correct for the VFIO PCI dma-buf exporter -- its phys is PCI BAR (MMIO) memory -- but it is the wrong prot for a dma-buf whose phys is RAM: on AMD-Vi the device DMA silently misroutes (Identify Controller against a gmem-provider-backed target completes with status=0 but the target region is not written).

Carry the exporter's memory type through to the fill routine:

- Add is_cpu_ram to iopt_pages_dmabuf and pfn_reader_dmabuf.
- Make sym_vfio_pci_dma_buf_iommufd_map() also fill *is_cpu_ram. VFIO PCI's exporter is MMIO (false); the sample gmem provider's exporter is CPU RAM (true).
- pfn_reader_fill_dmabuf() picks BATCH_CPU_MEMORY vs BATCH_MMIO based on the captured kind.

The eventual formal negotiated exporter op should return phys and memory type together in one call, replacing both symbol_get() lookups.

---
 drivers/iommu/iommufd/io_pagetable.h |  7 ++++++
 drivers/iommu/iommufd/pages.c        | 33 +++++++++++++++++++++++-----
 2 files changed, 34 insertions(+), 6 deletions(-)
drivers/iommu/iommufd/io_pagetable.h +7 -0
index 27e3e311d395..887ed94474c7 100644
@@ -206,6 +206,13 @@ struct iopt_pages_dmabuf {
 	/* Always PAGE_SIZE aligned */
 	unsigned long start;
 	struct list_head tracker;
+	/*
+	 * true if the exporter's phys is CPU RAM (map with IOMMU_CACHE, no
+	 * IOMMU_MMIO); false for MMIO/BAR memory (map with IOMMU_MMIO).  Set
+	 * by the exporter dispatch at map time; consulted by
+	 * pfn_reader_fill_dmabuf() to pick BATCH_CPU_MEMORY vs BATCH_MMIO.
+	 */
+	bool is_cpu_ram;
 };
 
 /*
drivers/iommu/iommufd/pages.c +27 -6
index 2d4ea41460fd..f9b2ae6d7e96 100644
@@ -1080,6 +1080,7 @@ static int pfn_reader_user_update_pinned(struct pfn_reader_user *user,
 struct pfn_reader_dmabuf {
 	struct phys_vec phys;
 	unsigned long start_offset;
+	bool is_cpu_ram;
 };
 
 static int pfn_reader_dmabuf_init(struct pfn_reader_dmabuf *dmabuf,
@@ -1091,6 +1092,7 @@ static int pfn_reader_dmabuf_init(struct pfn_reader_dmabuf *dmabuf,
 
 	dmabuf->phys = pages->dmabuf.phys;
 	dmabuf->start_offset = pages->dmabuf.start;
+	dmabuf->is_cpu_ram = pages->dmabuf.is_cpu_ram;
 	return 0;
 }
 
@@ -1106,9 +1108,15 @@ static int pfn_reader_fill_dmabuf(struct pfn_reader_dmabuf *dmabuf,
 	 * always filled using page size aligned PFNs just like the other types.
 	 * If the dmabuf has been sliced on a sub page offset then the common
 	 * batch to domain code will adjust it before mapping to the domain.
+	 *
+	 * The exporter's memory type (CPU RAM vs MMIO/BAR) selects the batch
+	 * kind so downstream iommu_map sets IOMMU_CACHE for cache-coherent RAM
+	 * or IOMMU_MMIO for BAR memory.  The kind was captured at map time by
+	 * the exporter dispatch.
 	 */
 	batch_add_pfn_num(batch, PHYS_PFN(dmabuf->phys.paddr + start),
-			  last_index - start_index + 1, BATCH_MMIO);
+			  last_index - start_index + 1,
+			  dmabuf->is_cpu_ram ? BATCH_CPU_MEMORY : BATCH_MMIO);
 	return 0;
 }
 
@@ -1459,22 +1467,31 @@ static const struct dma_buf_attach_ops iopt_dmabuf_attach_revoke_ops = {
  * iommufd and vfio have a circular dependency. Future work for a phys
  * based private interconnect will remove this.
  */
+/*
+ * Look up the exporter's phys accessor for iommufd's private-interconnect
+ * path.  Also fills *is_cpu_ram: true if the exporter's memory is normal
+ * cache-coherent RAM (needs BATCH_CPU_MEMORY / IOMMU_CACHE), false for MMIO
+ * (needs BATCH_MMIO / IOMMU_MMIO).  This will be replaced by a formal
+ * exporter op that returns phys + memory type together.
+ */
 static int
 sym_vfio_pci_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
-				 struct phys_vec *phys)
+				 struct phys_vec *phys, bool *is_cpu_ram)
 {
 	typeof(&vfio_pci_dma_buf_iommufd_map) fn;
 	int rc;
 
 	rc = iommufd_test_dma_buf_iommufd_map(attachment, phys);
-	if (rc != -EOPNOTSUPP)
+	if (rc != -EOPNOTSUPP) {
+		*is_cpu_ram = false;	/* test hook mimics VFIO MMIO */
 		return rc;
+	}
 
 	/*
 	 * Prototype: try the sample gmem provider's dma-buf exporter.  This
 	 * mirrors the vfio-pci private-interconnect hook, and (like it) is
 	 * meant to be replaced by a formal negotiated exporter op returning
-	 * phys for iommufd.
+	 * phys + memory type.  The provider serves RAM, so mark it CPU_RAM.
 	 */
 	{
 		extern int gmem_provider_dma_buf_iommufd_map(
@@ -1485,8 +1502,10 @@ sym_vfio_pci_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
 		if (gfn) {
 			rc = gfn(attachment, phys);
 			symbol_put(gmem_provider_dma_buf_iommufd_map);
-			if (rc != -EOPNOTSUPP)
+			if (rc != -EOPNOTSUPP) {
+				*is_cpu_ram = true;
 				return rc;
+			}
 		}
 	}
 
@@ -1498,6 +1517,7 @@ sym_vfio_pci_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
 		return -EOPNOTSUPP;
 	rc = fn(attachment, phys);
 	symbol_put(vfio_pci_dma_buf_iommufd_map);
+	*is_cpu_ram = false;	/* VFIO PCI dma-buf carries BAR (MMIO) memory */
 	return rc;
 }
 
@@ -1526,7 +1546,8 @@ static int iopt_map_dmabuf(struct iommufd_ctx *ictx, struct iopt_pages *pages,
 	if (rc)
 		goto err_detach;
 
-	rc = sym_vfio_pci_dma_buf_iommufd_map(attach, &pages->dmabuf.phys);
+	rc = sym_vfio_pci_dma_buf_iommufd_map(attach, &pages->dmabuf.phys,
+					      &pages->dmabuf.is_cpu_ram);
 	if (rc)
 		goto err_unpin;
 
Signature · 1 line
2.54.0
#11 lore raw

Re: [RFC PATCH 06/11] iommufd: Plumb dma-buf memory-type (RAM vs MMIO) through the phys map

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] Secondary domain attachments map MMIO DMA-bufs with BATCH_CPU_MEMORY (IOMMU_CACHE) instead of BATCH_MMIO (IOMMU_MMIO), breaking DMA routing. --

--- Patch [6]: [RFC PATCH 06/11] iommufd: Plumb dma-buf memory-type (RAM vs MMIO) through the phys map --- commit de7dbdc51049f527858115cc709f25b2cee585cb
Author: David Woodhouse <[email protected]>

iommufd: Plumb dma-buf memory-type (RAM vs MMIO) through the phys map

This commit plumbs the memory type of a dma-buf (CPU RAM vs MMIO) through the IOMMU programming path. It adds an is_cpu_ram flag to dmabuf structures to correctly choose between BATCH_CPU_MEMORY and BATCH_MMIO during mapping. This prevents silent misrouting of device DMA on AMD-Vi when the physical memory is RAM instead of a PCI BAR.

Quoted 4 lines
drivers/iommu/iommufd/pages.c +0 -0
index 2d4ea41460fdc..f9b2ae6d7e96c 100644

[ ... ]

Quoted 6 lines
drivers/iommu/iommufd/pages.c +2 -0
@@ -1106,9 +1108,15 @@ static int pfn_reader_fill_dmabuf(struct pfn_reader_dmabuf *dmabuf,
 	 * always filled using page size aligned PFNs just like the other types.
 	 * If the dmabuf has been sliced on a sub page offset then the common
 	 * batch to domain code will adjust it before mapping to the domain.
+	 *
+	 * The exporter's memory type (CPU RAM vs MMIO/BAR) selects the batch

drivers/iommu/iommufd/pages.c static int pfn_reader_fill_dmabuf(struct pfn_reader_dmabuf *dmabuf, · line 1121

Quoted 10 lines
drivers/iommu/iommufd/pages.c +5 -1
+	 * kind so downstream iommu_map sets IOMMU_CACHE for cache-coherent RAM
+	 * or IOMMU_MMIO for BAR memory.  The kind was captured at map time by
+	 * the exporter dispatch.
 	 */
 	batch_add_pfn_num(batch, PHYS_PFN(dmabuf->phys.paddr + start),
-			  last_index - start_index + 1, BATCH_MMIO);
+			  last_index - start_index + 1,
+			  dmabuf->is_cpu_ram ? BATCH_CPU_MEMORY : BATCH_MMIO);
 	return 0;
 }

[Severity: High]
This is a pre-existing issue, but does attaching a secondary domain map MMIO DMA-bufs with BATCH_CPU_MEMORY instead of BATCH_MMIO?

When reading PFNs for a secondary domain, pfn_reader_fill_span() routes the read to batch_from_domain() instead of pfn_reader_fill_dmabuf():

pfn_reader_fill_span() {
	if (span->is_used == 2) {
		/* ... */
		batch_from_domain(
			&pfns->batch, area->storage_domain, area, ...);
		return 0;
	}
}

Then batch_from_domain() extracts PFNs from the already mapped domain and unconditionally delegates to batch_add_pfn():

batch_from_domain() {
	/* ... */
	phys = iommu_iova_to_phys(domain, iova) - page_offset;
	if (!batch_add_pfn(batch, PHYS_PFN(phys)))
		return;
}

And batch_add_pfn() explicitly hardcodes BATCH_CPU_MEMORY:

static bool batch_add_pfn(struct pfn_batch *batch, unsigned long pfn)

{
	return batch_add_pfn_num(batch, pfn, 1, BATCH_CPU_MEMORY);
}

Could this silently overwrite the original memory type (e.g., BATCH_MMIO) for secondary domain mappings, causing device DMA to misroute on AMD-Vi even after this patch?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/f09647f427565c1789a6979470045aab78661563.1784194290.git.dwmw@amazon.co.uk?part=6
#12 lore raw

RFC PATCH 7/11 KVM: guest_memfd: Add ops-driven page revocation

In reply to David Woodhouse

From: David Woodhouse <[email protected]>

Add kvm_gmem_invalidate_range(): a guest_memfd backing calls it to zap the guest secondary-MMU mapping for a gfn range so the next access re-faults through ops->get_pfn(). Mirrors the existing internal __kvm_gmem_invalidate_start() for a single bound slot, bracketing the unmap with the mmu_invalidate window so a racing vCPU fault retries rather than installing a stale mapping.

The existing ops->invalidate callback is KVM -> implementation (cleanup); this new symbol is the implementation -> KVM path, useful for an overcommit manager or any subsystem that reclaims pages from a running guest. Export it for module use and add it to the KVM external-export allowlist.

---
 arch/x86/kvm/Makefile    |  3 ++-
 include/linux/kvm_host.h |  9 +++++++++
 virt/kvm/guest_memfd.c   | 39 +++++++++++++++++++++++++++++++++++++++
 3 files changed, 50 insertions(+), 1 deletion(-)
arch/x86/kvm/Makefile +2 -1
index 77337c37324b..cb963d6ecaab 100644
@@ -63,7 +63,8 @@ exports_grep_trailer := --include='*.[ch]' -nrw $(srctree)/virt/kvm $(srctree)/a
 				-e kvm_write_track_remove_gfn \
 				-e kvm_get_kvm \
 				-e kvm_get_kvm_safe \
-				-e kvm_put_kvm
+				-e kvm_put_kvm \
+				-e kvm_gmem_invalidate_range
 
 # Force grep to emit a goofy group separator that can in turn be replaced with
 # the above newline macro (newlines in Make are a nightmare).  Note, grep only
include/linux/kvm_host.h +9 -0
index b33d2f475042..04fa0cb126f6 100644
@@ -701,6 +701,15 @@ static inline bool is_kvm_gmem_file(struct file *file)
 	return file && file->f_op == &kvm_gmem_fops;
 }
 
+/*
+ * Outbound (implementation -> KVM) revocation: zap the guest's secondary MMU
+ * (NPT/EPT) mapping for a gfn range so the next guest access re-faults
+ * through the ops' get_pfn().  This is the reverse of ->invalidate (which is
+ * KVM -> implementation) and is what a backing that manages its own memory
+ * (e.g. an overcommit manager) uses to reclaim a page from a running guest.
+ */
+void kvm_gmem_invalidate_range(struct kvm *kvm, gfn_t start, gfn_t end);
+
 #endif /* CONFIG_KVM_GUEST_MEMFD */
 
 static inline bool kvm_slot_dirty_track_enabled(const struct kvm_memory_slot *slot)
virt/kvm/guest_memfd.c +39 -0
index 2b277468a12f..6c13742de068 100644
@@ -738,6 +738,45 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)
 	return __kvm_gmem_create(kvm, size, flags);
 }
 
+/*
+ * Outbound (implementation -> KVM) revocation: an implementation zaps the
+ * guest's secondary MMU mapping for a gfn range so the next guest access
+ * re-faults through ops->get_pfn().  Mirrors __kvm_gmem_invalidate_start()
+ * for a single bound slot, bracketing the unmap with the mmu_invalidate
+ * window so a racing vCPU fault retries rather than installing a stale
+ * mapping.
+ */
+void kvm_gmem_invalidate_range(struct kvm *kvm, gfn_t start, gfn_t end)
+{
+	struct kvm_memory_slot *slot;
+	bool flush = false;
+	int idx;
+
+	idx = srcu_read_lock(&kvm->srcu);
+
+	slot = gfn_to_memslot(kvm, start);
+	if (slot) {
+		struct kvm_gfn_range gfn_range = {
+			.slot		= slot,
+			.start		= start,
+			.end		= min(end, slot->base_gfn + slot->npages),
+			.may_block	= true,
+			.attr_filter	= KVM_FILTER_SHARED | KVM_FILTER_PRIVATE,
+		};
+
+		KVM_MMU_LOCK(kvm);
+		kvm_mmu_invalidate_start(kvm);
+		flush = kvm_mmu_unmap_gfn_range(kvm, &gfn_range);
+		if (flush)
+			kvm_flush_remote_tlbs(kvm);
+		kvm_mmu_invalidate_end(kvm);
+		KVM_MMU_UNLOCK(kvm);
+	}
+
+	srcu_read_unlock(&kvm->srcu, idx);
+}
+EXPORT_SYMBOL_GPL(kvm_gmem_invalidate_range);
+
 static const struct kvm_gmem_ops *kvm_gmem_get_ops(struct file *file)
 {
 	if (!is_kvm_gmem_file(file))
Signature · 1 line
2.54.0
#13 lore raw

Re: [RFC PATCH 07/11] KVM: guest_memfd: Add ops-driven page revocation

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] kvm_gmem_invalidate_range() fails to invalidate GFNs that span multiple memslots, start in an…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] kvm_gmem_invalidate_range() fails to invalidate GFNs that span multiple memslots, start in an unmapped hole, or exist in non-zero address spaces, leading to partial invalidation and potential Use-After-Free. --

--- Patch [7]: [RFC PATCH 07/11] KVM: guest_memfd: Add ops-driven page revocation --- commit 9715bf20df84962c5cc8863e7f4350b3bcb15273
Author: David Woodhouse <[email protected]>

KVM: guest_memfd: Add ops-driven page revocation

This commit adds kvm_gmem_invalidate_range() to allow a guest_memfd backing to zap the guest secondary-MMU mapping for a gfn range. This provides an implementation-to-KVM path to reclaim pages from a running guest.

Quoted 4 lines
virt/kvm/guest_memfd.c +0 -0
index 2b277468a12f0..6c13742de0680 100644

[ ... ]

Quoted 19 lines
virt/kvm/guest_memfd.c +15 -0
@@ -738,6 +738,45 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)
 	return __kvm_gmem_create(kvm, size, flags);
 }
 
+/*
+ * Outbound (implementation -> KVM) revocation: an implementation zaps the
+ * guest's secondary MMU mapping for a gfn range so the next guest access
+ * re-faults through ops->get_pfn().  Mirrors __kvm_gmem_invalidate_start()
+ * for a single bound slot, bracketing the unmap with the mmu_invalidate
+ * window so a racing vCPU fault retries rather than installing a stale
+ * mapping.
+ */
+void kvm_gmem_invalidate_range(struct kvm *kvm, gfn_t start, gfn_t end)
+{
+	struct kvm_memory_slot *slot;
+	bool flush = false;
+	int idx;
+
+	idx = srcu_read_lock(&kvm->srcu);

virt/kvm/guest_memfd.c int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args) · line 765

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+
+	slot = gfn_to_memslot(kvm, start);
+	if (slot) {
+		struct kvm_gfn_range gfn_range = {
+			.slot		= slot,
+			.start		= start,
+			.end		= min(end, slot->base_gfn + slot->npages),
+			.may_block	= true,
+			.attr_filter	= KVM_FILTER_SHARED | KVM_FILTER_PRIVATE,
+		};

[Severity: High]
Does this code fully invalidate the requested range if it spans multiple memslots or starts in an unmapped hole?

By looking up only the memslot for the start GFN and clamping the end to slot->base_gfn + slot->npages, it seems any remaining GFNs in the requested span will be skipped if the range crosses a memslot boundary.

Additionally, if the start GFN happens to fall in an unmapped hole, gfn_to_memslot() returns NULL and the entire invalidation is bypassed, even if there are valid mapped memslots further along in the range.

Finally, gfn_to_memslot() only checks Address Space 0. Could this leave stale SPTEs in alternate address spaces (like SMM), allowing the guest to access reclaimed host memory?

Quoted 12 lines
virt/kvm/guest_memfd.c +12 -0
+
+		KVM_MMU_LOCK(kvm);
+		kvm_mmu_invalidate_start(kvm);
+		flush = kvm_mmu_unmap_gfn_range(kvm, &gfn_range);
+		if (flush)
+			kvm_flush_remote_tlbs(kvm);
+		kvm_mmu_invalidate_end(kvm);
+		KVM_MMU_UNLOCK(kvm);
+	}
+
+	srcu_read_unlock(&kvm->srcu, idx);
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/f09647f427565c1789a6979470045aab78661563.1784194290.git.dwmw@amazon.co.uk?part=7
#14 lore raw

RFC PATCH 8/11 samples/kvm: Add guest_memfd backing sample

In reply to David Woodhouse

From: David Woodhouse <[email protected]>

A minimal in-tree implementation of the guest_memfd ops interface, useful both as reference code and as the substrate for the selftests that follow.

Features:

- Backs a slot from a fixed page-less physical range specified by the module parameters addr= and len=, or falls back to a CMA-allocated contiguous region when neither is given. The addr=/len= mode lets a reserved DRAM carve-out (mem=... or an explicit e820/DT reservation) become KVM slot backing without any struct page.

- Per-fd mmap capability via GMEM_PROVIDER_FLAG_MMAP_CAPABLE at GMEM_PROVIDER_SETUP time. An mmap-capable fd is bound as a gmem-only slot (KVM_MEMSLOT_GMEM_ONLY) so the host mmap and the guest fault path both route through this implementation. The mmap-capable fd is refused for hardware-encrypted VM types (SEV, SEV-ES, SEV-SNP, TDX) where a host view onto private-marked pages can only fault; the sample enforces this at bind time. KVM_X86_SW_PROTECTED_VM has no hardware encryption and is allowed.

- Page revocation via GMEM_PROVIDER_SET_PRESENT. Marking a range absent tracks it in a bitmap, invokes kvm_gmem_invalidate_range() to zap the guest NPT/EPT, and fans dma_buf_invalidate_mappings() out to any exported dma-buf so iommufd tears down its mapping. Subsequent get_pfn() on the range returns -EFAULT until it is restored with present=1. Models overcommit-style reclaim without needing the platform 's real reclaim machinery.

- A dma-buf exporter (GMEM_PROVIDER_GET_DMABUF) that yields an fd suitable for IOMMU_IOAS_MAP_FILE. The exporter mirrors the shape of drivers/vfio/pci/vfio_pci_dmabuf.c: dma_buf_attach_revocable, ->map_dma_buf via dma_buf_phys_vec_to_sgt, a single-range phys_vec, and the "well-known symbol" hook for iommufd's private-interconnect phys-map lookup.

The sample is layered on top of the shared kvm_gmem_fops: its fd is created with those fops and file->private_data points at a kvm_gmem_backing embedded at the head of its per-instance state. Release / mmap / ioctl for the fd all run through the ops table, so the sample owns no file_operations of its own.

Exposing kvm_gmem_fops for module use required promoting its export from EXPORT_SYMBOL_FOR_KVM_INTERNAL to EXPORT_SYMBOL_GPL and adding it to the KVM external-export allowlist.

SEV-SNP bind takes a psmash + rmp_make_shared sweep over the range so a new SNP VM can transition its pages private and re-encrypt them -- harmless on non-SNP hosts, where the calls return -ENODEV.

Based on a proof-of-concept by Connor Williamson <[email protected]>.

---
 arch/x86/kvm/Makefile       |   3 +-
 samples/Kconfig             |  18 +
 samples/Makefile            |   1 +
 samples/kvm/Makefile        |   2 +
 samples/kvm/gmem_provider.c | 651 ++++++++++++++++++++++++++++++++++++
 samples/kvm/gmem_provider.h |  53 +++
 virt/kvm/guest_memfd.c      |   2 +-
 7 files changed, 728 insertions(+), 2 deletions(-)
 create mode 100644 samples/kvm/Makefile
 create mode 100644 samples/kvm/gmem_provider.c
 create mode 100644 samples/kvm/gmem_provider.h
arch/x86/kvm/Makefile +2 -1
index cb963d6ecaab..535fb8cc259f 100644
@@ -64,7 +64,8 @@ exports_grep_trailer := --include='*.[ch]' -nrw $(srctree)/virt/kvm $(srctree)/a
 				-e kvm_get_kvm \
 				-e kvm_get_kvm_safe \
 				-e kvm_put_kvm \
-				-e kvm_gmem_invalidate_range
+				-e kvm_gmem_invalidate_range \
+				-e kvm_gmem_fops
 
 # Force grep to emit a goofy group separator that can in turn be replaced with
 # the above newline macro (newlines in Make are a nightmare).  Note, grep only
samples/Kconfig +18 -0
index a75e8e78330d..3482659638b5 100644
@@ -326,6 +326,24 @@ source "samples/rust/Kconfig"
 
 source "samples/damon/Kconfig"
 
+config SAMPLE_KVM_GMEM_PROVIDER
+	tristate "Build sample guest_memfd provider -- loadable module only"
+	depends on KVM_GUEST_MEMFD && X86_64 && m
+	help
+	  This builds a sample external guest_memfd provider module with two
+	  backing modes.  Loaded with addr=/len= it backs guest memory with a
+	  fixed physical range that has no struct page -- for example memory
+	  carved out of the kernel with mem= on the command line.  Without
+	  those params it falls back to a physically contiguous, page-backed
+	  region from alloc_contig_pages(), sized by the setup ioctl (easier to
+	  run, no boot param).
+
+	  It demonstrates the guest_memfd provider ABI including 2M and 1G
+	  guest mappings and, on SEV-SNP hosts, the RMP reset that lets a
+	  page-less range be re-bound to a new VM across a live update.
+
+	  If unsure, say N.
+
 endif # SAMPLES
 
 config HAVE_SAMPLE_FTRACE_DIRECT
samples/Makefile +1 -0
index 07641e177bd8..e85397e5e34f 100644
@@ -37,6 +37,7 @@ obj-$(CONFIG_SAMPLE_TPS6594_PFSM)	+= pfsm/
 subdir-$(CONFIG_SAMPLE_WATCHDOG)	+= watchdog
 subdir-$(CONFIG_SAMPLE_WATCH_QUEUE)	+= watch_queue
 obj-$(CONFIG_SAMPLE_KMEMLEAK)		+= kmemleak/
+obj-$(CONFIG_SAMPLE_KVM_GMEM_PROVIDER)	+= kvm/
 obj-$(CONFIG_SAMPLE_CORESIGHT_SYSCFG)	+= coresight/
 obj-$(CONFIG_SAMPLE_FPROBE)		+= fprobe/
 obj-$(CONFIG_SAMPLES_RUST)		+= rust/
samples/kvm/Makefile new file +2 -0
new file mode 100644
index 000000000000..dcad6e53ea78
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0
+obj-$(CONFIG_SAMPLE_KVM_GMEM_PROVIDER) += gmem_provider.o
samples/kvm/gmem_provider.c new file +651 -0

651 lines not on this page · raw message

samples/kvm/gmem_provider.h new file +53 -0

53 lines not on this page · raw message

virt/kvm/guest_memfd.c +1 -1
index 6c13742de068..2cb1b6a9d73f 100644
@@ -546,7 +546,7 @@ struct file_operations kvm_gmem_fops = {
 	.unlocked_ioctl	= kvm_gmem_fops_ioctl,
 	.compat_ioctl	= kvm_gmem_fops_ioctl,
 };
-EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_gmem_fops);
+EXPORT_SYMBOL_GPL(kvm_gmem_fops);
 
 static int kvm_gmem_migrate_folio(struct address_space *mapping,
 				  struct folio *dst, struct folio *src,
Signature · 1 line
2.54.0
#15 lore raw

Re: [RFC PATCH 08/11] samples/kvm: Add guest_memfd backing sample

Thank you for your contribution! Sashiko AI review found 14 potential issue(s) to consider: - [Critical] Missing file type validation for `setup.kvm_fd` allows arbitrary kernel memory corruption.…

Thank you for your contribution! Sashiko AI review found 14 potential issue(s) to consider:
- [Critical] Missing file type validation for setup.kvm_fd allows arbitrary kernel memory corruption.
- [Critical] gmem_release() frees memory while it is still mapped into the guest, causing host physical memory corruption.
- [High] Unprotected access to info->kvm leads to Use-After-Free and data races.
- [High] Non-atomic bitmap operations in GMEM_PROVIDER_SET_PRESENT corrupt memory revocation state.
- [High] gmem_bind tracks only a single memslot binding, preventing memory revocation for previously bound slots.
- [High] Integer underflow in revocation range causes out-of-bounds KVM invalidation.
- [High] gmem_max_order() ignores the absent bitmap, allowing KVM to install hugepage mappings over revoked pages.
- [High] gmem_mmap() does not check info->mmap_capable, allowing host access to hardware-encrypted VM memory.
- [High] gmem_unbind() fails to call psmash(), leaving 2M pages permanently stuck in the private state on SEV-SNP.
- [High] The psmash operation is completely skipped in gmem_bind if the starting physical address is not 2M aligned.
- [High] The provider does not pin its module, allowing it to be unloaded while guest_memfd instances remain active.
- [High] Integer truncation in bitmap_zalloc() leads to an unprivileged kernel heap buffer overflow.
- [Medium] Leaked provider file reference in gmem_provider_get_dmabuf error path.
- [Medium] DMAbuf exporter leaks its initial kref and fails to wait for mappings to be torn down.
--

--- Patch [8]: [RFC PATCH 08/11] samples/kvm: Add guest_memfd backing sample --- commit 7bfeb9f519ccce1291a261c36607819a68c027ce
Author: David Woodhouse <[email protected]>
Subject: samples/kvm: Add guest_memfd backing sample

This commit adds a sample guest_memfd provider module for KVM. It demonstrates page-less backing from a fixed physical range or a CMA-allocated contiguous region. It also includes page revocation via a bitmap and a dma-buf exporter.

Quoted 6 lines
samples/kvm/gmem_provider.c new file +0 -0
new file mode 100644
index 0000000000000..e30580fecd166
@@ -0,0 +1,651 @@

[ ... ]

samples/kvm/gmem_provider.c line 120

Quoted 11 lines
samples/kvm/gmem_provider.c new file +11 -0
+static int gmem_max_order(struct gmem_info *info, gfn_t gfn, unsigned long index)
+{
+	unsigned long pfn = info->base_pfn + index;
+	unsigned long remaining = info->npages - index;
+	unsigned int pud_order = PUD_SHIFT - PAGE_SHIFT;
+	unsigned int pmd_order = PMD_SHIFT - PAGE_SHIFT;
+
+	if (IS_ALIGNED(pfn, 1UL << pud_order) &&
+	    IS_ALIGNED(gfn, 1UL << pud_order) &&
+	    remaining >= (1UL << pud_order))
+		return pud_order;

[Severity: High]
Does gmem_max_order() account for pages marked absent?

When KVM queries the maximum mapping order for a present faulting page, gmem_max_order() checks alignment and remaining length, but does not check if any of the subsequent pages within the hugepage range are marked absent in info->absent.

If a subset of pages in a 2M or 1G range is revoked but the faulting page is present, could KVM install a hugepage mapping that grants the guest unauthorized access to the revoked pages within that block?

[ ... ]

Quoted 3 lines
samples/kvm/gmem_provider.c new file +3 -0
+static int gmem_bind(struct file *file, struct kvm *kvm,
+		     struct kvm_memory_slot *slot, loff_t offset)
+{

[ ... ]

samples/kvm/gmem_provider.c line 206

Quoted 3 lines
samples/kvm/gmem_provider.c new file +3 -0
+	/* Record the binding so the revoke ioctl can translate offset -> gfn. */
+	info->base_gfn = slot->base_gfn;
+	info->pgoff = start;

[Severity: High]
Does gmem_bind() only track a single memslot binding?

KVM allows a single provider fd to back multiple memslots. However, gmem_bind() overwrites info->base_gfn and info->pgoff with the new slot's coordinates.

During GMEM_PROVIDER_SET_PRESENT, KVM is only asked to invalidate the single, most recently bound GFN range. Older slots would be ignored and their guest NPT/EPT mappings never zapped. Can this result in a complete bypass of the page revocation mechanism for previously bound slots?

Quoted 6 lines
samples/kvm/gmem_provider.c new file +6 -0
+
+#if IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT)
+	/*
+	 * Reset the RMP for the range to 4K shared so a (new) SEV-SNP VM can
+	 * transition it to private and re-encrypt it.  PSMASH any 2M entries
+	 * first.  Harmless on non-SNP hosts, where these return -ENODEV.

samples/kvm/gmem_provider.c line 222

Quoted 10 lines
samples/kvm/gmem_provider.c new file +10 -0
+	 */
+	{
+		unsigned long i;
+
+		for (i = 0; i < slot->npages; i += PTRS_PER_PMD) {
+			unsigned long pfn = info->base_pfn + start + i;
+
+			if (IS_ALIGNED(pfn, PTRS_PER_PMD))
+				psmash(pfn);
+		}

[Severity: High]
Will the psmash() operation be skipped if the start address is unaligned?

The loop advances i by PTRS_PER_PMD (which is 512) and checks if the combined pfn is perfectly aligned to a 2M boundary.

If info->base_pfn + start is not 2M-aligned to begin with, adding 512 guarantees that every subsequent PFN checked will also be unaligned. psmash() would never be called for any 2M boundaries inside the range. Could this cause subsequent rmp_make_shared() calls to fail?

Quoted 8 lines
samples/kvm/gmem_provider.c new file +8 -0
+		for (i = 0; i < slot->npages; i++) {
+			unsigned long pfn = info->base_pfn + start + i;
+			int ret = rmp_make_shared(pfn, PG_LEVEL_4K);
+
+			if (ret && ret != -ENODEV)
+				pr_info_once("gmem_provider: rmp_make_shared(0x%lx) = %d\n",
+					     pfn, ret);
+		}

samples/kvm/gmem_provider.c line 240

Quoted 10 lines
samples/kvm/gmem_provider.c new file +10 -0
+	}
+#endif
+
+	/* Claim (or, on re-bind, transfer) VM ownership; pins the VM. */
+	if (info->kvm != kvm) {
+		kvm_get_kvm(kvm);
+		if (info->kvm)
+			kvm_put_kvm(info->kvm);
+		info->kvm = kvm;
+	}

[Severity: High]
Does this code handle concurrent bindings safely?

In gmem_bind(), info->kvm is read and modified without any locking. If a single provider file is concurrently bound to multiple VMs (or the same VM multiple times), multiple threads could race, reading the same old info->kvm pointer and both calling kvm_put_kvm().

This could lead to a double-put and Use-After-Free of the KVM instances. Additionally, gmem_fd_ioctl() accesses info->kvm without locks while it might be concurrently updated or freed. Could we add synchronization to protect info->kvm?

[ ... ]

Quoted 5 lines
samples/kvm/gmem_provider.c new file +5 -0
+static void gmem_unbind(struct file *file, struct kvm *kvm,
+			struct kvm_memory_slot *slot)
+{
+#if IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT)
+	struct gmem_info *info = to_gmem_info(file);

samples/kvm/gmem_provider.c line 269

Quoted 10 lines
samples/kvm/gmem_provider.c new file +10 -0
+	unsigned long start = slot->gmem.pgoff;
+	unsigned long i;
+
+	for (i = 0; i < slot->npages; i++) {
+		unsigned long pfn = info->base_pfn + start + i;
+
+		rmp_make_shared(pfn, PG_LEVEL_4K);
+	}
+#endif
+}

[Severity: High]
Is a call to psmash() required before rmp_make_shared() here?

On SEV-SNP hosts, converting a 2M private page back to the shared state using rmp_make_shared() with PG_LEVEL_4K fails unless the 2M RMP entry is first shattered using psmash().

gmem_unbind() omits the psmash() step and ignores the return value of rmp_make_shared(). This could leave 2M pages permanently marked as private. When these CMA pages are freed and reused by the host allocator, wouldn't accessing them crash the host?

[ ... ]

samples/kvm/gmem_provider.c line 295

Quoted 11 lines
samples/kvm/gmem_provider.c new file +11 -0
+static void gmem_release(struct file *file)
+{
+	struct gmem_info *info = to_gmem_info(file);
+
+	if (info->kvm)
+		kvm_put_kvm(info->kvm);
+	if (info->cma_pages)
+		free_contig_range(info->base_pfn, info->npages);
+	bitmap_free(info->absent);
+	kfree(info);
+}

[Severity: Critical]
Does gmem_release() free memory while it is still mapped into the guest?

When the provider fd is closed, gmem_release() frees info->cma_pages and the info struct. However, it does not appear to zap the guest's NPT/EPT page tables or clear the KVM slot tracking pointer.

This leaves the guest with full read/write access to the freed CMA pages after they have been reallocated to other kernel subsystems. When KVM later destroys the memslot, it could also dereference the dangling slot->gmem.file pointer. Should the mappings be explicitly torn down before freeing?

[ ... ]

samples/kvm/gmem_provider.c line 309

Quoted 13 lines
samples/kvm/gmem_provider.c new file +13 -0
+static int gmem_mmap(struct file *file, struct vm_area_struct *vma)
+{
+	struct gmem_info *info = to_gmem_info(file);
+	unsigned long npages = vma_pages(vma);
+
+	if (vma->vm_pgoff + npages > info->npages)
+		return -EINVAL;
+
+	/* Page-less backing: map raw PFNs, not folios. */
+	vm_flags_set(vma, VM_PFNMAP | VM_IO | VM_DONTEXPAND | VM_DONTDUMP);
+	return remap_pfn_range(vma, vma->vm_start, info->base_pfn + vma->vm_pgoff,
+			       npages << PAGE_SHIFT, vma->vm_page_prot);
+}

[Severity: High]
Should gmem_mmap() validate the mmap_capable policy?

gmem_bind() refuses to bind to encrypted VMs if info->mmap_capable is set, in order to protect the host. However, gmem_mmap() maps the memory to userspace without verifying info->mmap_capable.

Userspace could clear GMEM_PROVIDER_FLAG_MMAP_CAPABLE during setup, successfully bind to a SEV-SNP/TDX VM, and then call mmap() on the fd anyway. Could this allow host access to hardware-encrypted memory and cause a machine check exception or RMP violation?

[ ... ]

Quoted 4 lines
samples/kvm/gmem_provider.c new file +4 -0
+/* Called with info->dmabufs_lock held on the revoke path. */
+static void gmem_dma_buf_revoke_all(struct gmem_info *info)
+{
+	struct gmem_dmabuf *priv;

samples/kvm/gmem_provider.c line 443

Quoted 10 lines
samples/kvm/gmem_provider.c new file +10 -0
+
+	list_for_each_entry(priv, &info->dmabufs, list) {
+		dma_resv_lock(priv->dmabuf->resv, NULL);
+		if (!priv->revoked) {
+			priv->revoked = true;
+			dma_buf_invalidate_mappings(priv->dmabuf);
+		}
+		dma_resv_unlock(priv->dmabuf->resv);
+	}
+}

[Severity: Medium]
Should the revocation wait for the completion of mapping teardowns?

In gmem_dma_buf_revoke_all(), dma_buf_invalidate_mappings() is called, but it doesn't wait on priv->comp. This leaves the completion machinery unused and leaks the kref initialized in gmem_provider_get_dmabuf().

Should we properly wait for the mappings to be torn down and drop the reference?

[ ... ]

Quoted 20 lines
samples/kvm/gmem_provider.c new file +20 -0
+static int gmem_provider_get_dmabuf(struct file *file)
+{
+	struct gmem_info *info = to_gmem_info(file);
+	DEFINE_DMA_BUF_EXPORT_INFO(exp_info);
+	struct gmem_dmabuf *priv;
+	int fd;
+
+	priv = kzalloc(sizeof(*priv), GFP_KERNEL);
+	if (!priv)
+		return -ENOMEM;
+
+	priv->info = info;
+	priv->provider_file = get_file(file);
+	priv->phys.paddr = (u64)info->base_pfn << PAGE_SHIFT;
+	priv->phys.len = (u64)info->npages << PAGE_SHIFT;
+	kref_init(&priv->kref);
+	init_completion(&priv->comp);
+	INIT_LIST_HEAD(&priv->list);
+
+	exp_info.ops = &gmem_dma_buf_ops;

samples/kvm/gmem_provider.c line 474

Quoted 10 lines
samples/kvm/gmem_provider.c new file +10 -0
+	exp_info.size = priv->phys.len;
+	exp_info.flags = O_RDWR;
+	exp_info.priv = priv;
+
+	priv->dmabuf = dma_buf_export(&exp_info);
+	if (IS_ERR(priv->dmabuf)) {
+		fd = PTR_ERR(priv->dmabuf);
+		kfree(priv);
+		return fd;
+	}

[Severity: Medium]
Will this error path leak the provider file reference?

Earlier in gmem_provider_get_dmabuf(), get_file(file) is called to increment the reference count. If dma_buf_export() fails, the function frees priv and returns an error, but it doesn't appear to call fput(priv->provider_file).

Could userspace trigger this intentionally (e.g., by hitting file descriptor limits) to permanently leak the file and its associated CMA memory?

[ ... ]

Quoted 5 lines
samples/kvm/gmem_provider.c new file +5 -0
+static long gmem_fd_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
+{
+	struct gmem_info *info = to_gmem_info(file);
+	struct gmem_provider_present p;
+	unsigned long start_index, end_index;

[ ... ]

samples/kvm/gmem_provider.c line 512

Quoted 6 lines
samples/kvm/gmem_provider.c new file +6 -0
+	if (p.present) {
+		/* Restore: next guest fault calls get_pfn() and re-maps. */
+		bitmap_clear(info->absent, start_index, end_index - start_index);
+	} else {
+		/* Revoke: mark absent, then zap the guest NPT/EPT for the range. */
+		bitmap_set(info->absent, start_index, end_index - start_index);

[Severity: High]
Are these bitmap operations safe against concurrent updates?

In gmem_fd_ioctl(), GMEM_PROVIDER_SET_PRESENT uses bitmap_set() and bitmap_clear() without synchronization. These functions perform non-atomic read-modify-write operations on the underlying unsigned long elements.

If userspace concurrently revokes or restores different page ranges that fall within the same bitmap word, won't the updates race and clobber each other, potentially allowing the guest unauthorized access?

samples/kvm/gmem_provider.c line 516

Quoted 4 lines
samples/kvm/gmem_provider.c new file +4 -0
+		if (info->kvm)
+			kvm_gmem_invalidate_range(info->kvm,
+				info->base_gfn + start_index - info->pgoff,
+				info->base_gfn + end_index - info->pgoff);

[Severity: High]
Can this arithmetic underflow if start_index < info->pgoff?

If userspace specifies a revocation range that starts before the offset where the slot was bound (start_index < info->pgoff), the subtraction here will underflow to a massive unsigned value.

kvm_gmem_invalidate_range() would then use this bogus GFN range, fail to find the correct slot, and skip the invalidation entirely, leaving revoked pages mapped in the guest. Should we bounds-check start_index against info->pgoff?

[ ... ]

Quoted 12 lines
samples/kvm/gmem_provider.c new file +12 -0
+static long gmem_ctl_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
+{
+	struct gmem_provider_setup setup;
+	struct gmem_info *info;
+	struct file *kvm_file;
+	struct page *pages = NULL;
+	struct kvm *kvm;
+	unsigned long npages;
+	int fd, ret;
+
+	if (cmd != GMEM_PROVIDER_SETUP)
+		return -ENOTTY;

samples/kvm/gmem_provider.c line 552

Quoted 10 lines
samples/kvm/gmem_provider.c new file +10 -0
+
+	if (copy_from_user(&setup, (void __user *)arg, sizeof(setup)))
+		return -EFAULT;
+	if (setup.flags & ~GMEM_PROVIDER_FLAG_MMAP_CAPABLE)
+		return -EINVAL;
+
+	kvm_file = fget(setup.kvm_fd);
+	if (!kvm_file)
+		return -EBADF;
+	kvm = kvm_file->private_data;

[Severity: Critical]
Is it possible for userspace to provide a file descriptor that is not a KVM VM file?

Looking at gmem_ctl_ioctl(), the code calls fget() on setup.kvm_fd and blindly dereferences kvm_file->private_data. If an unprivileged user passes an arbitrary file descriptor (like an eventfd or socket), this would cast its private_data to a struct kvm *.

This could lead to arbitrary kernel memory corruption when kvm_get_kvm() subsequently performs an atomic increment at the offset of users_count on that arbitrary data structure. Should we verify the file's operations (e.g., checking kvm_file->f_op) before casting?

[ ... ]

samples/kvm/gmem_provider.c line 589

Quoted 1 line
samples/kvm/gmem_provider.c new file +1 -0
+	info->absent = bitmap_zalloc(info->npages, GFP_KERNEL);

[Severity: High]
Can info->npages be truncated during bitmap allocation?

info->npages is a 64-bit unsigned long. If the module is loaded with a large external addr=/len= range (e.g., 16TB), info->npages exceeds 32 bits. bitmap_zalloc() takes an unsigned int for nbits, which would silently truncate this value, allocating a smaller bitmap.

An unprivileged user could then call GMEM_PROVIDER_SET_PRESENT with a large offset that passes the 64-bit bounds check, causing bitmap_set() to write far beyond the truncated allocation. Does this allow a kernel heap buffer overflow?

[ ... ]

samples/kvm/gmem_provider.c line 603

Quoted 2 lines
samples/kvm/gmem_provider.c new file +2 -0
+	fd = anon_inode_getfd("[gmem-provider]", &kvm_gmem_fops,
+			      &info->backing, O_RDWR | O_CLOEXEC);

[Severity: High]
Is the provider module pinned when the file descriptor is created?

anon_inode_getfd() creates the fd using &kvm_gmem_fops, which belongs to the KVM module. The provider module does not take a reference to itself.

If userspace closes the control fd (/dev/gmem_provider) but keeps the provider fd open, could the gmem_provider module be unloaded via rmmod? Subsequent VM page faults or ioctls would then call into the unloaded module's gmem_ops, potentially causing a kernel panic.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/f09647f427565c1789a6979470045aab78661563.1784194290.git.dwmw@amazon.co.uk?part=8
#16 lore raw

RFC PATCH 9/11 selftests/kvm: gmem_provider KVM-only tests

In reply to David Woodhouse

From: David Woodhouse <[email protected]>

Three selftests that exercise the guest_memfd provider ABI purely from the KVM side (no iommufd, no assigned devices):

gmem_provider_test
SEV-SNP launch + re-bind against a page-less provider region. Loads a 16 MiB guest at physical addr= from the module parameters, runs SNP_LAUNCH_START -> SNP_LAUNCH_UPDATE -> SNP_LAUNCH_FINISH -> KVM_CREATE_VCPU, tears the VM down, and re-binds the same provider fd to a fresh SNP VM. Proves the LU-survivable path (fd persists, KVM refs transfer, RMP transitions clean).

gmem_provider_hugepage_test
Non-CoCo (SW_PROTECTED_VM) guest whose slot is backed by a mmap-capable provider fd. Verifies via KVM_GET_STATS that the NPT for a 1 GiB, 1G-aligned slot contains at least one 1 GiB and one 2 MiB mapping. Exercises kvm_gmem_max_mapping_level and the mmap-capable = gmem-only path.

gmem_provider_revoke_test
GMEM_PROVIDER_SET_PRESENT round trip. Reads a page from the guest (populates NPT), revokes the range, re-enters the guest to observe the fault (memory attribute goes absent, vcpu_run fails EFAULT), restores and re-enters, confirms the guest reads the original value. Exercises the provider-driven kvm_gmem_provider_invalidate helper end-to-end.

All three assume the sample provider is loaded with an addr=/len= page-less region; hugepage and revoke additionally require the fd to be set up with GMEM_PROVIDER_FLAG_MMAP_CAPABLE.

---
 tools/testing/selftests/kvm/Makefile.kvm      |   3 +
 .../kvm/x86/gmem_provider_hugepage_test.c     | 130 ++++++++++++
 .../kvm/x86/gmem_provider_revoke_test.c       | 134 ++++++++++++
 .../selftests/kvm/x86/gmem_provider_test.c    | 195 ++++++++++++++++++
 4 files changed, 462 insertions(+)
 create mode 100644 tools/testing/selftests/kvm/x86/gmem_provider_hugepage_test.c
 create mode 100644 tools/testing/selftests/kvm/x86/gmem_provider_revoke_test.c
 create mode 100644 tools/testing/selftests/kvm/x86/gmem_provider_test.c
tools/testing/selftests/kvm/Makefile.kvm +3 -0
index d28a057fa6c2..e6e9ac9da45a 100644
@@ -161,6 +161,9 @@ TEST_GEN_PROGS_x86 += rseq_test
 TEST_GEN_PROGS_x86 += steal_time
 TEST_GEN_PROGS_x86 += system_counter_offset_test
 TEST_GEN_PROGS_x86 += pre_fault_memory_test
+TEST_GEN_PROGS_x86 += x86/gmem_provider_test
+TEST_GEN_PROGS_x86 += x86/gmem_provider_hugepage_test
+TEST_GEN_PROGS_x86 += x86/gmem_provider_revoke_test
 
 # Compiled outputs used by test targets
 TEST_GEN_PROGS_EXTENDED_x86 += x86/nx_huge_pages_test
tools/testing/selftests/kvm/x86/gmem_provider_hugepage_test.c new file +130 -0

130 lines not on this page · raw message

tools/testing/selftests/kvm/x86/gmem_provider_revoke_test.c new file +134 -0

134 lines not on this page · raw message

tools/testing/selftests/kvm/x86/gmem_provider_test.c new file +195 -0

195 lines not on this page · raw message

Signature · 1 line
2.54.0
#17 lore raw

Re: [RFC PATCH 09/11] selftests/kvm: gmem_provider KVM-only tests

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] The test does not check for partial completion of KVM_SEV_SNP_LAUNCH_UPDATE, leading to…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] The test does not check for partial completion of KVM_SEV_SNP_LAUNCH_UPDATE, leading to potentially silent incomplete memory initialization.
- [Medium] The test fails to assert KVM_EXIT_MEMORY_FAULT on the revoke path because the validation is placed in an unreachable 'else' branch. --

--- Patch [9]: [RFC PATCH 09/11] selftests/kvm: gmem_provider KVM-only tests --- commit 93ae3986a0340a4d14084b20d7839ed583b0c01b
Author: David Woodhouse <[email protected]>

selftests/kvm: gmem_provider KVM-only tests

Three selftests that exercise the guest_memfd provider ABI purely from the KVM side (no iommufd, no assigned devices). These tests verify the live-update survivability, hugepage mappings, and memory revocation.

Quoted 4 lines
tools/testing/selftests/kvm/x86/gmem_provider_revoke_test.c new file +0 -0
index 0000000000000..7e711ea526748 100644

[ ... ]

Quoted 7 lines
tools/testing/selftests/kvm/x86/gmem_provider_revoke_test.c new file +7 -0
+	/* 2) Revoke: mark absent and zap the guest NPT (provider->KVM). */
+	req = (struct gmem_provider_present){ .offset = 0, .len = 4096, .present = 0 };
+	r = ioctl(gmem_fd, GMEM_PROVIDER_SET_PRESENT, &req);
+	TEST_ASSERT(!r, "revoke ioctl failed, errno %d", errno);
+
+	/* 3) Guest re-reads -> re-fault into absent get_pfn -> must NOT see MAGIC. */
+	r = _vcpu_run(vcpu);

tools/testing/selftests/kvm/x86/gmem_provider_revoke_test.c line 115

Quoted 10 lines
tools/testing/selftests/kvm/x86/gmem_provider_revoke_test.c new file +10 -0
+	if (r) {
+		pr_info("revoked: vcpu_run failed (errno %d) -- guest faulted, as expected\n",
+			errno);
+	} else {
+		TEST_ASSERT(vcpu->run->exit_reason == KVM_EXIT_MEMORY_FAULT,
+			    "revoked: expected fault or KVM_EXIT_MEMORY_FAULT, got %u (%s)",
+			    vcpu->run->exit_reason,
+			    exit_reason_str(vcpu->run->exit_reason));
+		pr_info("revoked: KVM_EXIT_MEMORY_FAULT as expected\n");
+	}

[Severity: Medium]
Since KVM_EXIT_MEMORY_FAULT always causes the KVM_RUN ioctl to return -1 with errno EFAULT, won't _vcpu_run(vcpu) return a non-zero value here?

If so, this execution path would take the if (r) branch, completely bypassing the exit reason validation in the else block. Should this check be moved or adjusted to properly assert that the exit reason is indeed KVM_EXIT_MEMORY_FAULT?

Quoted 6 lines
tools/testing/selftests/kvm/x86/gmem_provider_revoke_test.c new file +6 -0
+
+	/* 4) Restore: mark present again. */
+	req.present = 1;
+	r = ioctl(gmem_fd, GMEM_PROVIDER_SET_PRESENT, &req);
+	TEST_ASSERT(!r, "restore ioctl failed, errno %d", errno);
+

[ ... ]

Quoted 4 lines
tools/testing/selftests/kvm/x86/gmem_provider_test.c new file +0 -0
index 0000000000000..d7caa11616dfe 100644

[ ... ]

Quoted 4 lines
tools/testing/selftests/kvm/x86/gmem_provider_test.c new file +4 -0
+	struct kvm_sev_snp_launch_start start = { .policy = 0x30000 };
+	ret = sev_ioctl(vm_fd, sev_fd, KVM_SEV_SNP_LAUNCH_START, &start);
+	if (ret) { perror("SNP_LAUNCH_START"); goto out; }
+

tools/testing/selftests/kvm/x86/gmem_provider_test.c line 102

Quoted 10 lines
tools/testing/selftests/kvm/x86/gmem_provider_test.c new file +10 -0
+	printf("[VM%d] SNP_LAUNCH_UPDATE (code + zero, %luMB)\n",
+	       vm_num, GUEST_MEM_SIZE >> 20);
+	struct kvm_sev_snp_launch_update update = {
+		.gfn_start = 0,
+		.uaddr = (uint64_t)(unsigned long)src,
+		.len = PAGE_SIZE_4K,
+		.type = KVM_SEV_SNP_PAGE_TYPE_NORMAL,
+	};
+	ret = sev_ioctl(vm_fd, sev_fd, KVM_SEV_SNP_LAUNCH_UPDATE, &update);
+	if (ret) { perror("SNP_LAUNCH_UPDATE code"); goto out; }

[Severity: Medium]
If a signal interrupts the KVM_SEV_SNP_LAUNCH_UPDATE ioctl, KVM might return 0 but leave update.len > 0 indicating a partial completion.

Does this code need a loop to check update.len and retry the remaining length to prevent silent partial initialization?

tools/testing/selftests/kvm/x86/gmem_provider_test.c line 111

Quoted 9 lines
tools/testing/selftests/kvm/x86/gmem_provider_test.c new file +9 -0
+
+	struct kvm_sev_snp_launch_update update_zero = {
+		.gfn_start = 1,
+		.uaddr = (uint64_t)(unsigned long)(src + PAGE_SIZE_4K),
+		.len = GUEST_MEM_SIZE - PAGE_SIZE_4K,
+		.type = KVM_SEV_SNP_PAGE_TYPE_ZERO,
+	};
+	ret = sev_ioctl(vm_fd, sev_fd, KVM_SEV_SNP_LAUNCH_UPDATE, &update_zero);
+	if (ret) { perror("SNP_LAUNCH_UPDATE zero"); goto out; }

[Severity: Medium]
Similarly, could a signal interrupting this update_zero ioctl cause a partial completion here as well? If the return value is 0 but update_zero.len is still greater than 0, the rest of the 16MB guest memory would be left uninitialized, potentially causing flaky test failures later.

Quoted 3 lines
tools/testing/selftests/kvm/x86/gmem_provider_test.c new file +3 -0
+
+	struct kvm_sev_snp_launch_finish finish = { 0 };
+	ret = sev_ioctl(vm_fd, sev_fd, KVM_SEV_SNP_LAUNCH_FINISH, &finish);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/f09647f427565c1789a6979470045aab78661563.1784194290.git.dwmw@amazon.co.uk?part=9
#18 lore raw

RFC PATCH 10/11 selftests/kvm: gmem_provider iommufd tests

In reply to David Woodhouse

From: David Woodhouse <[email protected]>

Three selftests that exercise the guest_memfd provider ABI from the iommufd side, going progressively closer to a real assigned-device setup:

gmem_provider_iommufd_test
Dual-map. A KVM memslot and an iommufd IOAS are both backed by the same provider dma-buf. The guest writes a magic pattern into the slot; the host mmap of the same provider fd sees the guest's write; the IOAS also holds a mapping of the same backing. Proves KVM and iommufd converge on the same provider phys via two different fds (the KVM guest_memfd fd and the dma-buf fd).

gmem_provider_vfio_test
A real vfio-pci device is bound to iommufd and attached to an IOAS that has the provider region mapped. Confirms the attach path accepts a dma-buf-backed IOAS without complaint; does not issue device DMA. Requires an unused PCI device already bound to vfio-pci and exposed as /dev/vfio/devices/vfio0 (overridable via GMEM_VFIO_CDEV).

gmem_provider_nvme_dma_test
Full round trip. Binds an NVMe controller to vfio-pci, attaches it to an IOAS with the provider region mapped at IOVA_DST, initialises NVMe admin queues (also in the IOAS via anonymous pages), submits Identify Controller with PRP1=IOVA_DST, and verifies the 4 KiB response via the host mmap of the same provider fd (VID/SSVID/MN check). Then revokes the target range with GMEM_PROVIDER_SET_PRESENT and re-submits Identify to the same
IOVA: iommufd's iopt_revoke_notify tears down the mapping and the device DMA either faults at the IOMMU (visible as IO_PAGE_FAULT in dmesg on AMD-Vi / equivalent on VT-d, SMMUv3) or completes with an NVMe error; either way the provider region is not overwritten. Restores and confirms fresh mappings succeed.

Requires an EBS/NVMe scratch device on the test host bound to vfio-pci; the tests SKIP cleanly if no such device is available.

---
 tools/testing/selftests/kvm/Makefile.kvm      |   9 +-
 .../kvm/x86/gmem_provider_iommufd_test.c      | 150 +++++++
 .../kvm/x86/gmem_provider_nvme_dma_test.c     | 365 ++++++++++++++++++
 .../kvm/x86/gmem_provider_vfio_test.c         | 134 +++++++
 4 files changed, 655 insertions(+), 3 deletions(-)
 create mode 100644 tools/testing/selftests/kvm/x86/gmem_provider_iommufd_test.c
 create mode 100644 tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c
 create mode 100644 tools/testing/selftests/kvm/x86/gmem_provider_vfio_test.c
tools/testing/selftests/kvm/Makefile.kvm +6 -3
index e6e9ac9da45a..7f46843e7428 100644
@@ -77,6 +77,12 @@ TEST_GEN_PROGS_x86 += x86/evmcs_smm_controls_test
 TEST_GEN_PROGS_x86 += x86/exit_on_emulation_failure_test
 TEST_GEN_PROGS_x86 += x86/fastops_test
 TEST_GEN_PROGS_x86 += x86/fix_hypercall_test
+TEST_GEN_PROGS_x86 += x86/gmem_provider_test
+TEST_GEN_PROGS_x86 += x86/gmem_provider_hugepage_test
+TEST_GEN_PROGS_x86 += x86/gmem_provider_revoke_test
+TEST_GEN_PROGS_x86 += x86/gmem_provider_iommufd_test
+TEST_GEN_PROGS_x86 += x86/gmem_provider_vfio_test
+TEST_GEN_PROGS_x86 += x86/gmem_provider_nvme_dma_test
 TEST_GEN_PROGS_x86 += x86/hwcr_msr_test
 TEST_GEN_PROGS_x86 += x86/hyperv_clock
 TEST_GEN_PROGS_x86 += x86/hyperv_cpuid
@@ -161,9 +167,6 @@ TEST_GEN_PROGS_x86 += rseq_test
 TEST_GEN_PROGS_x86 += steal_time
 TEST_GEN_PROGS_x86 += system_counter_offset_test
 TEST_GEN_PROGS_x86 += pre_fault_memory_test
-TEST_GEN_PROGS_x86 += x86/gmem_provider_test
-TEST_GEN_PROGS_x86 += x86/gmem_provider_hugepage_test
-TEST_GEN_PROGS_x86 += x86/gmem_provider_revoke_test
 
 # Compiled outputs used by test targets
 TEST_GEN_PROGS_EXTENDED_x86 += x86/nx_huge_pages_test
tools/testing/selftests/kvm/x86/gmem_provider_iommufd_test.c new file +150 -0

150 lines not on this page · raw message

tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c new file +365 -0

365 lines not on this page · raw message

tools/testing/selftests/kvm/x86/gmem_provider_vfio_test.c new file +134 -0

134 lines not on this page · raw message

Signature · 1 line
2.54.0
#19 lore raw

Re: [RFC PATCH 10/11] selftests/kvm: gmem_provider iommufd tests

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [Medium] The NVMe DMA test hardcodes the Amazon PCI Vendor ID (0x1d0f), causing false failures on generic…

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [Medium] The NVMe DMA test hardcodes the Amazon PCI Vendor ID (0x1d0f), causing false failures on generic hardware.
- [Medium] Missing compiler memory barrier before ringing the NVMe Submission Queue doorbell allows dangerous compiler reordering.
- [Medium] gmem_provider_iommufd_test fails to exercise the KVM guest_memfd private memory path because it does not set the KVM_MEMORY_ATTRIBUTE_PRIVATE attribute.
- [Medium] The test claims to confirm a fresh IOMMU_IOAS_MAP_FILE succeeds after restoring the page, but does not actually issue the ioctl.
- [Low] Comment incorrectly claims the NVMe completion phase bit is inverted, contradicting the code and the NVMe specification.
--

--- Patch [10]: [RFC PATCH 10/11] selftests/kvm: gmem_provider iommufd tests --- commit 104877080caa9ea2c6214f716d67d2b54448bb37

Author: David Woodhouse <[email protected]>
Date:   Thu Jul 16 09:31:30 2026 +0000

selftests/kvm: gmem_provider iommufd tests

Three selftests that exercise the guest_memfd provider ABI from the iommufd side, going progressively closer to a real assigned-device setup.

Quoted 5 lines
tools/testing/selftests/kvm/x86/gmem_provider_iommufd_test.c new file +0 -0
new file mode 100644
index 0000000000000..0b2fc097b5a91

[ ... ]

tools/testing/selftests/kvm/x86/gmem_provider_iommufd_test.c

Quoted 10 lines
tools/testing/selftests/kvm/x86/gmem_provider_iommufd_test.c new file +10 -0
+	hva = mmap(NULL, DATA_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, gmem_fd, 0);
+	TEST_ASSERT(hva != MAP_FAILED,
+		    "provider mmap failed errno=%d", errno);
+	r = __vm_set_user_memory_region2(vm, DATA_SLOT, KVM_MEM_GUEST_MEMFD,
+					 DATA_GPA, DATA_SIZE, hva, gmem_fd, 0);
+	TEST_ASSERT(!r, "KVM_SET_USER_MEMORY_REGION2 failed r=%d errno=%d", r, errno);
+	virt_map(vm, DATA_GPA, DATA_GPA, 1);
+
+	/*
+	 * 3) iommufd side: allocate IOAS

[Severity: Medium]
Does main() actually exercise the KVM guest_memfd private memory path?

Because the KVM_MEMORY_ATTRIBUTE_PRIVATE attribute is never set on this GPA via vm_mem_set_private(), KVM will fault on the shared memory HVA.

Does this completely bypass the KVM guest_memfd logic, with the guest write reaching the provider fd via the HVA mmap path instead?

[ ... ]

Quoted 5 lines
tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c new file +0 -0
new file mode 100644
index 0000000000000..8c8a4b2e8ac96

[ ... ]

Quoted 6 lines
tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c new file +6 -0
+	/* Identify Controller SQE at slot 0. */
+	{
+		uint32_t *s = (uint32_t *)sq_buf;
+		memset(s, 0, 64);
+		s[0]  = 0x00010006;	/* CID=1 << 16 | OPC=Identify */
+		s[1]  = 0;		/* NSID */

tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c line 234

Quoted 10 lines
tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c new file +10 -0
+		/* PRP1 (offset 24 in SQE = dword 6) */
+		s[6]  = (uint32_t)IOVA_DST;
+		s[7]  = (uint32_t)(IOVA_DST >> 32);
+		s[8]  = 0;
+		s[9]  = 0;		/* PRP2 */
+		s[10] = 0x01;		/* CDW10: CNS = Identify Controller */
+	}
+
+	/* Ring SQ0 tail doorbell. */
+	wr32(bar, NVME_SQ0TDBL, 1);

[Severity: Medium]
Is there a risk of the compiler reordering the SQE initialization after the doorbell ring in main()?

Since the SQE is prepared via non-volatile stores and the doorbell is written via a volatile cast, the C standard permits reordering non-volatile stores after volatile stores. Could this result in the NVMe controller processing an incomplete or zeroed command?

Would it be safer to add a compiler barrier before writing the doorbell?

[ ... ]

Quoted 9 lines
tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c new file +9 -0
+	/* Provider region now holds Identify Controller data.  VID/SSVID at bytes 0..3
+	 * must equal the device's PCI vendor + subsystem vendor (both are Amazon here). */
+	{
+		uint16_t vid  = ((uint16_t *)provider_hva)[0];
+		uint16_t ssvid = ((uint16_t *)provider_hva)[1];
+		uint8_t first = ((uint8_t *)provider_hva)[0];
+		uint8_t poison_still = ((uint8_t *)provider_hva)[8];
+		char mn[41] = {};
+		memcpy(mn, (char *)provider_hva + 24, 40);

tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c line 275

Quoted 10 lines
tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c new file +10 -0
+		fprintf(stderr, "MARKER: read done; byte0=0x%02x byte8=0x%02x\n",
+			first, poison_still);
+		fflush(stderr);
+		pr_info("Identify Controller in provider: VID=0x%04x SSVID=0x%04x MN='%s'\n",
+			vid, ssvid, mn);
+		fflush(stdout);
+		TEST_ASSERT(vid == 0x1d0f,
+			    "unexpected VID 0x%04x in provider region -- Identify DMA landed elsewhere?\n"
+			    "  poison=0x%02x byte0=0x%02x (poison intact=DMA didn't land here)",
+			    vid, poison_still, first);

[Severity: Medium]
Does main() hardcode the Amazon PCI Vendor ID here?

If this test is run on a non-Amazon NVMe drive, won't this assertion cause it to fail on generic hardware?

Should we fetch the PCI Vendor ID from the config space instead of hardcoding it to 0x1d0f?

[ ... ]

tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c line 318

Quoted 11 lines
tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c new file +11 -0
+		/* Issue a second Identify Controller aimed at the revoked IOVA.
+		 * Use a new CID and place the SQE in slot 1; the SQ ring will
+		 * wrap for larger runs but we only ever use slots 0 and 1.
+		 */
+		memset(&s[16], 0, 64);
+		s[16] = 0x00020006;			/* CID=2 << 16 | OPC=Identify */
+		s[16 + 6] = (uint32_t)IOVA_DST;
+		s[16 + 7] = (uint32_t)(IOVA_DST >> 32);
+		s[16 + 10] = 0x01;			/* CNS = Identify Controller */
+
+		wr32(bar, NVME_SQ0TDBL, 2);

[Severity: Medium]
Similar to the first command submission in main(), does this need a compiler barrier before the doorbell ring to prevent the compiler from sinking the SQE initialization?

tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c line 323

Quoted 5 lines
tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c new file +5 -0
+		pr_info("Identify Controller (revoked target) submitted (SQ0 tail=2)\n");
+
+		/* Poll for CQE at slot 1 with phase bit inverted from first pass. */
+		for (i = 0; i < 5000; i++) {
+			if ((c[4 + 3] & 0x10000))	/* CQE 1 P bit */

[Severity: Low]
Is this comment accurate?

Since this is only the second command in a 64-entry queue, the controller is still on its first pass. The phase bit remains 1 and does not invert, which matches the code's correct check for a 1 bit.

[ ... ]

tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c line 355

Quoted 6 lines
tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c new file +6 -0
+		/* Restore and confirm a fresh IOMMU_IOAS_MAP_FILE succeeds. */
+		rev.present = 1;
+		ret = ioctl(gmem_fd, GMEM_PROVIDER_SET_PRESENT, &rev);
+		TEST_ASSERT(ret == 0, "SET_PRESENT(restore) errno=%d", errno);
+		pr_info("Restore + revoke round trip complete\n");
+	}

[Severity: Medium]
The comment in main() mentions confirming a fresh IOMMU_IOAS_MAP_FILE succeeds, but does the test actually attempt to issue this ioctl after restoring the page?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/f09647f427565c1789a6979470045aab78661563.1784194290.git.dwmw@amazon.co.uk?part=10
#20 lore raw

RFC PATCH 11/11 samples/kvm, selftests/kvm: Allow the gmem_provider NVMe DMA test on arm64

In reply to David Woodhouse

From: David Woodhouse <[email protected]>

The sample provider and the NVMe DMA selftest have no x86 specifics. Drop the X86_64 gate on the sample's Kconfig (arm64 also has KVM_GUEST_MEMFD; the SEV RMP reset is already guarded by CONFIG_AMD_MEM_ENCRYPT) and move the NVMe DMA selftest from TEST_GEN_PROGS_x86 to TEST_GEN_PROGS_COMMON so it also builds on architectures with an IOMMU (arm64 SMMU-v3, ...).

The test itself does not need to change: it uses KVM_CREATE_VM(0) as a client for the sample provider's SETUP ioctl and then exercises the iommufd + dma-buf + provider revoke path with direct NVMe MMIO, none of which is x86-specific. On arm64 it validates the same flow through the ARM SMMU.

---
 samples/Kconfig                                                 | 2 +-
 tools/testing/selftests/kvm/Makefile.kvm                        | 2 +-
 .../selftests/kvm/{x86 => }/gmem_provider_nvme_dma_test.c       | 0
 3 files changed, 2 insertions(+), 2 deletions(-)
 rename tools/testing/selftests/kvm/{x86 => }/gmem_provider_nvme_dma_test.c (100%)
samples/Kconfig +1 -1
index 3482659638b5..d26a03dea072 100644
@@ -328,7 +328,7 @@ source "samples/damon/Kconfig"
 
 config SAMPLE_KVM_GMEM_PROVIDER
 	tristate "Build sample guest_memfd provider -- loadable module only"
-	depends on KVM_GUEST_MEMFD && X86_64 && m
+	depends on KVM_GUEST_MEMFD && (X86_64 || ARM64) && m
 	help
 	  This builds a sample external guest_memfd provider module with two
 	  backing modes.  Loaded with addr=/len= it backs guest memory with a
tools/testing/selftests/kvm/Makefile.kvm +1 -1
index 7f46843e7428..12004a487c32 100644
@@ -58,6 +58,7 @@ TEST_PROGS_x86 += x86/nx_huge_pages_test.sh
 # Compiled test targets valid on all architectures with libkvm support
 TEST_GEN_PROGS_COMMON = demand_paging_test
 TEST_GEN_PROGS_COMMON += dirty_log_test
+TEST_GEN_PROGS_COMMON += gmem_provider_nvme_dma_test
 TEST_GEN_PROGS_COMMON += guest_print_test
 TEST_GEN_PROGS_COMMON += irqfd_test
 TEST_GEN_PROGS_COMMON += kvm_binary_stats_test
@@ -82,7 +83,6 @@ TEST_GEN_PROGS_x86 += x86/gmem_provider_hugepage_test
 TEST_GEN_PROGS_x86 += x86/gmem_provider_revoke_test
 TEST_GEN_PROGS_x86 += x86/gmem_provider_iommufd_test
 TEST_GEN_PROGS_x86 += x86/gmem_provider_vfio_test
-TEST_GEN_PROGS_x86 += x86/gmem_provider_nvme_dma_test
 TEST_GEN_PROGS_x86 += x86/hwcr_msr_test
 TEST_GEN_PROGS_x86 += x86/hyperv_clock
 TEST_GEN_PROGS_x86 += x86/hyperv_cpuid
tools/testing/selftests/kvm/gmem_provider_nvme_dma_test.c renamed from tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c +0 -0
similarity index 100%
rename from tools/testing/selftests/kvm/x86/gmem_provider_nvme_dma_test.c
rename to tools/testing/selftests/kvm/gmem_provider_nvme_dma_test.c
Signature · 1 line
2.54.0
#21 lore raw

Re: [RFC PATCH 11/11] samples/kvm, selftests/kvm: Allow the gmem_provider NVMe DMA test on arm64

Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider: - [Critical] The gmem_provider sample module blindly trusts the `setup.kvm_fd` file descriptor, leading to…

Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider:
- [Critical] The gmem_provider sample module blindly trusts the setup.kvm_fd file descriptor, leading to type confusion and local privilege escalation.
- [High] A data race on the info->kvm pointer between gmem_bind and gmem_fd_ioctl allows a concurrent binding to drop the VM reference while it is actively being used, leading to a Use-After-Free.
- [Medium] The NVMe DMA selftest hardcodes the Amazon PCI Vendor ID (0x1d0f), causing it to fail on non-Amazon NVMe devices.
- [Medium] The selftest implicitly assumes a 4KB system page size, causing IOMMU mapping failures on architectures with larger page sizes.
- [Medium] The selftest bypasses architecture-specific I/O accessors and omits mandatory memory barriers, causing data races on weakly-ordered architectures.
- [Medium] The selftest performs raw, native-endian memory accesses on strictly little-endian PCI configuration space and NVMe registers, causing corruption on big-endian architectures. --

--- Patch [11]: [RFC PATCH 11/11] samples/kvm, selftests/kvm: Allow the gmem_provider NVMe DMA test on arm64 --- commit fc0ebbb277714921db32af720eb2c5783d061ea0
Author: David Woodhouse <[email protected]>

samples/kvm, selftests/kvm: Allow the gmem_provider NVMe DMA test on arm64

The sample provider and the NVMe DMA selftest have no x86 specifics. Drop the X86_64 gate on the sample's Kconfig (arm64 also has KVM_GUEST_MEMFD; the SEV RMP reset is already guarded by CONFIG_AMD_MEM_ENCRYPT) and move the NVMe DMA selftest from TEST_GEN_PROGS_x86 to TEST_GEN_PROGS_COMMON so it also builds on architectures with an IOMMU (arm64 SMMU-v3, ...).

samples/Kconfig source "samples/damon/Kconfig" · line 331

Quoted 10 lines
samples/Kconfig +1 -1
index 3482659638b5b..d26a03dea0728 100644
@@ -328,7 +328,7 @@ source "samples/damon/Kconfig"
 
 config SAMPLE_KVM_GMEM_PROVIDER
 	tristate "Build sample guest_memfd provider -- loadable module only"
-	depends on KVM_GUEST_MEMFD && X86_64 && m
+	depends on KVM_GUEST_MEMFD && (X86_64 || ARM64) && m

[Severity: Critical]
Is it safe to blindly trust the kvm_fd here?

In gmem_ctl_ioctl(), the user-provided setup.kvm_fd is resolved and used like this:

samples/kvm/gmem_provider.c:gmem_ctl_ioctl() {
    ...
	kvm_file = fget(setup.kvm_fd);
	if (!kvm_file)
		return -EBADF;
	kvm = kvm_file->private_data;
	if (!kvm) {
		fput(kvm_file);
		return -EINVAL;
	}
	kvm_get_kvm(kvm);
    ...
}

If a user passes an arbitrary file descriptor, it could lead to type confusion since we don't verify the file's operations before extracting private_data and performing an out-of-bounds refcount_inc(&kvm->users_count).

[Severity: High]
Can gmem_fd_ioctl() safely use info->kvm without synchronization?

In gmem_fd_ioctl(), info->kvm is used without holding a lock:

samples/kvm/gmem_provider.c:gmem_fd_ioctl() {
    ...
		if (info->kvm)
			kvm_gmem_invalidate_range(info->kvm,
				info->base_gfn + start_index - info->pgoff,
				info->base_gfn + end_index - info->pgoff);
    ...
}

Concurrently, gmem_bind() can swap info->kvm and drop the underlying reference:

samples/kvm/gmem_provider.c:gmem_bind() {
    ...
	if (info->kvm != kvm) {
		kvm_get_kvm(kvm);
		if (info->kvm)
			kvm_put_kvm(info->kvm);
		info->kvm = kvm;
	}
    ...
}

Could this concurrent binding drop the VM reference to zero while it is being accessed by the ioctl, leading to a use-after-free?

[ ... ]

tools/testing/selftests/kvm/Makefile.kvm TEST_PROGS_x86 += x86/nx_huge_pages_test.sh · line 61

Quoted 9 lines
tools/testing/selftests/kvm/Makefile.kvm +1 -0
index 7f46843e7428f..12004a487c326 100644
@@ -58,6 +58,7 @@ TEST_PROGS_x86 += x86/nx_huge_pages_test.sh
 # Compiled test targets valid on all architectures with libkvm support
 TEST_GEN_PROGS_COMMON = demand_paging_test
 TEST_GEN_PROGS_COMMON += dirty_log_test
+TEST_GEN_PROGS_COMMON += gmem_provider_nvme_dma_test

[Severity: Medium]
Will this regression cause the test to fail on host hardware that doesn't use an Amazon NVMe device?

The test hardcodes the Amazon PCI Vendor ID:

tools/testing/selftests/kvm/gmem_provider_nvme_dma_test.c:main() {
    ...
		TEST_ASSERT(vid == 0x1d0f,
			    "unexpected VID 0x%04x in provider region -- Identify DMA landed elsewhere?\n"
    ...
}

Should the expected VID be read dynamically from offset 0x00 instead?

[Severity: Medium]
Does the implicit 4KB system page size assumption introduce a regression on architectures that commonly use larger page sizes, such as arm64?

The test uses hardcoded 4KB offsets and lengths for IOMMU mapping:

tools/testing/selftests/kvm/gmem_provider_nvme_dma_test.c:main() {
    ...
	TEST_ASSERT(!ioas_map_user(iommufd_fd, alloc.out_ioas_id, sq_buf, IOVA_SQ, 0x1000),
		    "IOAS_MAP(sq) errno=%d", errno);
	TEST_ASSERT(!ioas_map_user(iommufd_fd, alloc.out_ioas_id, cq_buf, IOVA_CQ, 0x1000),
		    "IOAS_MAP(cq) errno=%d", errno);
    ...
}

Since iommufd requires mapping lengths and IOVAs to be aligned to the system page size, won't this fail on kernels running with 16KB or 64KB page sizes?

[Severity: Medium]
Can a data race occur on weakly-ordered architectures without memory barriers?

The custom MMIO accessors use plain volatile writes:

tools/testing/selftests/kvm/gmem_provider_nvme_dma_test.c:wr32() {
    ...
static void     wr32(void *b, uint32_t o, uint32_t v) { *(volatile uint32_t *)((char *)b + o) = v; }
    ...
}

When ringing the doorbell:

tools/testing/selftests/kvm/gmem_provider_nvme_dma_test.c:main() {
    ...
	/* Ring SQ0 tail doorbell. */
	wr32(bar, NVME_SQ0TDBL, 1);
    ...
}

Without an explicit memory barrier, is the CPU free to reorder the MMIO write to the doorbell ahead of the normal RAM writes to the Submission Queue Entry?

[Severity: Medium]
Does this code corrupt device state on big-endian architectures?

Since the test is now built for all architectures, it will run on big-endian systems. However, the test uses native-endian assignments to interact with little-endian PCI configuration space and NVMe registers:

tools/testing/selftests/kvm/gmem_provider_nvme_dma_test.c:main() {
    ...
	TEST_ASSERT(pread(vfio_fd, &pci_cmd, 2, cfg_off + 0x04) == 2, "cfg CMD read");
	pci_cmd |= 0x0006;
	TEST_ASSERT(pwrite(vfio_fd, &pci_cmd, 2, cfg_off + 0x04) == 2, "cfg CMD write");
    ...
}

And for the NVMe SQE:

tools/testing/selftests/kvm/gmem_provider_nvme_dma_test.c:main() {
    ...
		s[0]  = 0x00010006;	/* CID=1 << 16 | OPC=Identify */
    ...
}

Will these direct native-endian accesses produce byte-swapped data on big-endian CPUs and cause the test to fail?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/f09647f427565c1789a6979470045aab78661563.1784194290.git.dwmw@amazon.co.uk?part=11
#22 lore raw

Re: [RFC PATCH 01/11] KVM: selftests: sev_smoke_test: Only run VM types the host offers

In reply to David Woodhouse
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The test silently returns 0 (PASS) if no SEV VM types are offered by KVM, masking the lack of…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The test silently returns 0 (PASS) if no SEV VM types are offered by KVM, masking the lack of test coverage. --

--- Patch [1]: [RFC PATCH 01/11] KVM: selftests: sev_smoke_test: Only run VM types the host offers --- commit c4fa8ea2868d0892d394adecf158fe07893c3980
Author: David Woodhouse <[email protected]>

KVM: selftests: sev_smoke_test: Only run VM types the host offers

sev_smoke_test is updated to gate the plain SEV subtest on KVM_CAP_VM_TYPES, preventing the test from aborting when all SEV ASIDs are assigned to SEV-SNP. This ensures the test runs only the VM types the host actually offers.

Quoted 7 lines
tools/testing/selftests/kvm/x86/sev_smoke_test.c +0 -0
index 6b2cbe2a90b7c..bf27b6187afac 100644
@@ -247,7 +247,14 @@ int main(int argc, char *argv[])
 {
 	TEST_REQUIRE(kvm_cpu_has(X86_FEATURE_SEV));

tools/testing/selftests/kvm/x86/sev_smoke_test.c int main(int argc, char *argv[]) · line 257

Quoted 10 lines
tools/testing/selftests/kvm/x86/sev_smoke_test.c +8 -1
 
-	test_sev_smoke(guest_sev_code, KVM_X86_SEV_VM, 0);
+	/*
+	 * Only exercise VM types the host actually offers.  CPUID reporting
+	 * SEV does not guarantee KVM offers the SEV VM type: when all SEV
+	 * ASIDs are assigned to SEV-SNP, KVM_X86_SEV_VM is unavailable even
+	 * though X86_FEATURE_SEV is set.  Gate every type on KVM_CAP_VM_TYPES.
+	 */
+	if (kvm_check_cap(KVM_CAP_VM_TYPES) & BIT(KVM_X86_SEV_VM))
+		test_sev_smoke(guest_sev_code, KVM_X86_SEV_VM, 0);

[Severity: Medium]
Does this code silently return 0 (PASS) if the host offers no SEV VM types?

If none of the KVM_CAP_VM_TYPES conditions evaluate to true, the program will fall through to return 0. This masks a lack of test coverage by falsely indicating a successful test run, rather than properly skipping the test.

Quoted 3 lines
tools/testing/selftests/kvm/x86/sev_smoke_test.c +0 -0
 	if (kvm_check_cap(KVM_CAP_VM_TYPES) & BIT(KVM_X86_SEV_ES_VM))
 		test_sev_smoke(guest_sev_es_code, KVM_X86_SEV_ES_VM, SEV_POLICY_ES);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/f09647f427565c1789a6979470045aab78661563.1784194290.git.dwmw@amazon.co.uk?part=1
Reviewed-by on v1 1/11
#23 lore raw

Re: [RFC PATCH 01/11] KVM: selftests: sev_smoke_test: Only run VM types the host offers

In reply to David Woodhouse
Quoted 9 lines · David Woodhouse

From: David Woodhouse <[email protected]>

sev_smoke_test ran the plain SEV subtest unconditionally, gated only on the X86_FEATURE_SEV CPUID bit, while gating SEV-ES and SNP on the KVM_CAP_VM_TYPES bits. CPUID reporting SEV does not mean KVM offers the SEV VM type: when all SEV ASIDs are assigned to SEV-SNP, KVM_X86_SEV_VM is unavailable even though X86_FEATURE_SEV is set. On such a host the test aborts in KVM_CREATE_VM instead of exercising the available modes.

Quoted 4 lines

Gate the SEV subtest on KVM_CAP_VM_TYPES like the others, so the test runs the VM types the host actually offers.