Skip to contentSkip to conversation

KVM: Allow alternative providers of guest_memfd backed by PFNMAP memory

RFC PATCH In review David Woodhouse 7 participants 52 messages Jul 20 – Oct 15

Subsystems (17)
lore
Share & tools
lore
#0 lore raw

v2 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 spent 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 state 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 how 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-v2

Changes since v1 (mostly Sashiko feedback):

Core (KVM / SEV):
- populate: drop the transient page reference after ->post_populate() rather than before, so the callback still sees the ref it relies on
- kvm_gmem_invalidate_range(): walk every address space and all memslots in the range, not just address space 0 / a single slot
- SEV: the guest_memfd cache flush hit a WARN_ON_ONCE on a failed temporary mapping; that path is reachable from userspace (hole-punch), so downgrade to pr_warn_ratelimited to avoid a panic_on_warn DoS
- Export file_is_kvm() (EXPORT_SYMBOL_GPL) so an external provider can confirm the fd handed to it at setup really is a KVM instance

Sample provider (samples/kvm/gmem_provider.c):
- Serialize per-fd state (info->kvm, bound_slot, present bitmap) under a new info->lock; v1 accessed info->kvm without locking, racing bind/unbind against release
- Validate setup.kvm_fd via file_is_kvm() before using it
- Fix bitmap_zalloc(unsigned int) truncation -> kvzalloc with BITS_TO_LONGS
- Fix integer underflow in SET_PRESENT when start_index < pgoff
- gmem_release: zap active guest mappings + clear slot->gmem.file before freeing the backing
- Pin THIS_MODULE while a provider fd is open
- gmem_mmap: refuse if the fd was not created mmap-capable
- gmem_max_order: clamp by the absent bitmap
- Bind/unbind: symmetric psmash + rmp_make_shared with proper 2MiB alignment

Selftests:
- Revoke test: assert the revoked access faults unconditionally
- iommufd test: mark the range KVM_MEMORY_ATTRIBUTE_PRIVATE so the guest actually exercises the provider path rather than the shared HVA mmap
- NVMe DMA test: read the vendor ID from PCI config and add compiler barriers before the doorbell writes

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                              |   5 +-
 arch/x86/kvm/svm/sev.c                             |  93 ++-
 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                        | 772 +++++++++++++++++++++
 samples/kvm/gmem_provider.h                        |  53 ++
 tools/testing/selftests/kvm/Makefile.kvm           |   6 +
 .../selftests/kvm/gmem_provider_nvme_dma_test.c    | 376 ++++++++++
 .../kvm/x86/gmem_provider_hugepage_test.c          | 130 ++++
 .../selftests/kvm/x86/gmem_provider_iommufd_test.c | 158 +++++
 .../selftests/kvm/x86/gmem_provider_revoke_test.c  | 135 ++++
 .../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                             | 391 +++++++++--
 virt/kvm/kvm_main.c                                |   8 +-
 virt/kvm/kvm_mm.h                                  |   4 +-
 23 files changed, 2577 insertions(+), 103 deletions(-)
#1 lore raw

RFC PATCH v2 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.55.0
#2 lore raw

RFC PATCH v2 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.55.0
#3 lore raw

RFC PATCH v2 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  | 93 +++++++++++++++++++++++++++++++++++------
 arch/x86/virt/svm/sev.c | 27 ++++++++----
 2 files changed, 100 insertions(+), 20 deletions(-)
arch/x86/kvm/svm/sev.c +81 -12
index 427229347876..125779c82bc4 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,38 @@ 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 (!va) {
+		/*
+		 * memremap() can fail under memory pressure (vmalloc space
+		 * exhaustion).  Callers reach us during guest_memfd hole-
+		 * punching, so this is user-triggerable; ratelimit rather
+		 * than WARN, otherwise panic_on_warn hosts turn it into a
+		 * denial of service.
+		 */
+		pr_warn_ratelimited("SEV: memremap failed for cache flush pfn=%llx size=%zu\n",
+				    pfn, size);
+		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 +5242,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.55.0
#4 lore raw

RFC PATCH v2 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]>.

---
 arch/x86/kvm/Makefile    |   5 +-
 include/linux/kvm_host.h |  82 ++++++++++
 virt/kvm/guest_memfd.c   | 339 +++++++++++++++++++++++++++++++--------
 virt/kvm/kvm_main.c      |   8 +-
 virt/kvm/kvm_mm.h        |   4 +-
 5 files changed, 365 insertions(+), 73 deletions(-)
arch/x86/kvm/Makefile +4 -1
index 77337c37324b..36a319f382b7 100644
@@ -63,7 +63,10 @@ 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 \
+				-e kvm_gmem_fops \
+				-e file_is_kvm
 
 # 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 +82 -0

88 lines not on this page · raw message

virt/kvm/guest_memfd.c +273 -66

500 lines not on this page · raw message

virt/kvm/kvm_main.c +4 -4
index e44c20c04961..3af5270d2a90 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;
@@ -5475,7 +5475,7 @@ bool file_is_kvm(struct file *file)
 {
 	return file && file->f_op == &kvm_vm_fops;
 }
-EXPORT_SYMBOL_FOR_KVM_INTERNAL(file_is_kvm);
+EXPORT_SYMBOL_GPL(file_is_kvm);
 
 static int kvm_dev_ioctl_create_vm(unsigned long type)
 {
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.55.0
#5 lore raw

RFC PATCH v2 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.55.0
#6 lore raw

RFC PATCH v2 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.55.0
#7 lore raw

RFC PATCH v2 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.

---
 include/linux/kvm_host.h |  9 +++++++
 virt/kvm/guest_memfd.c   | 52 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 61 insertions(+)
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 +52 -0

58 lines not on this page · raw message

Signature · 1 line
2.55.0
#8 lore raw

RFC PATCH v2 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]>.

---
 samples/Kconfig             |  18 +
 samples/Makefile            |   1 +
 samples/kvm/Makefile        |   2 +
 samples/kvm/gmem_provider.c | 772 ++++++++++++++++++++++++++++++++++++
 samples/kvm/gmem_provider.h |  53 +++
 virt/kvm/guest_memfd.c      |   2 +-
 6 files changed, 847 insertions(+), 1 deletion(-)
 create mode 100644 samples/kvm/Makefile
 create mode 100644 samples/kvm/gmem_provider.c
 create mode 100644 samples/kvm/gmem_provider.h
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 +772 -0

772 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 1da22da0a6ec..d284bb70fe05 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.55.0
#9 lore raw

RFC PATCH v2 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       | 135 ++++++++++++
 .../selftests/kvm/x86/gmem_provider_test.c    | 195 ++++++++++++++++++
 4 files changed, 463 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 +135 -0

135 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.55.0
#10 lore raw

RFC PATCH v2 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      | 158 ++++++++
 .../kvm/x86/gmem_provider_nvme_dma_test.c     | 376 ++++++++++++++++++
 .../kvm/x86/gmem_provider_vfio_test.c         | 134 +++++++
 4 files changed, 674 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 +158 -0

158 lines not on this page · raw message

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

376 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.55.0
#11 lore raw

RFC PATCH v2 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.55.0
#13 lore raw
Quoted 9 lines · Paolo Bonzini
Quoted 4 lines · David Woodhouse

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-v2

In the meanwhile, I have very ignorantly applied patches 1 and 2 as testsuite fixes. :)

Thanks. I think #3 can go in on its own too; will try to drum up some review for that...

#14 lore raw
In reply to David Woodhouse
Quoted 4 lines · David Woodhouse

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

Quoted 8 lines

• No struct page overheads

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

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

Also, no need to split/merge pages when converting from private to shared if the host mappings can't depend on the refcounts in struct pages :).

Quoted 9 lines

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 state to be passed over KHO/kexec.

Thanks for raising this, good to know that there is more interest!

Vishal and I have been working on guest_memfd with HugeTLB for a while now. I'll be restarting upstream work on HugeTLB after the conversions series merges.

Vishal, Frank and I brought up having guest_memfd with HugeTLB with VM_PFNMAP mappings at a guest_memfd biweekly meeting a while ago. The consensus was that guest_memfd HugeTLB must support GUP and so VM_PFNMAP can't be the only way that guest_memfd supports HugeTLB.

Your proposal is true non-page-struct memory, which has been on the discussion guest_memfd biweekly discussion backlog for a while now. Google is definitely also interested in this.

Frank also described some use cases [1] other than HugeTLB and the regular PAGE_SIZE pages from the buddy that is currently supported.

I submitted a proposal for LPC 2026 to discuss the interface. What I had in mind was to have the KVM_GUEST_MEMFD_CREATE ioctl take a "template" fd. guest_memfd will then read off what it needs from the "template" fd (ops, like you have here), and the "template" fd could be VFIO [2] or HugeTLB.

You have a provider_fd = open("/dev/gmem_provider"), how about passing that provider_fd to guest_memfd, where /dev/gmem_provider could represent the page-less memory, like:

  ioctl(kvm_fd, KVM_GUEST_MEMFD_CREATE, provider_fd);

It would be cool if the fallback could be set up flexibly, like:

  ioctl(kvm_fd, KVM_GUEST_MEMFD_CREATE,
        [provider_fd, fallback_provider_fd, ...]);

I think guest_memfd should be the wrapper around other memory providers because then the CoCo shared/private logic and special page table handling for both host and stage 2 page tables is centralized in guest_memfd, and also, KVM doesn't have to understand other, different kinds of fds other than guest_memfd.

[1] https://lore.kernel.org/all/CAPTztWajm_JLpp9BjRcX=h72r25ELrXeGkOXVachybBxLJGS=g@mail.gmail.com/
[2] https://lore.kernel.org/all/CAEvNRgFpJWQ5M5sQhGpQUV3GbBq9N+MQhhaxdxa=D8ky94SCsw@mail.gmail.com/

Quoted 8 lines

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.

Quoted 6 lines

It's largely AI-built at the moment. My main design concerns are around how 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.

IIUC from this series, you're creating a dmabuf fd out of a guest_memfd, what does "taking pages away" mean, in this case, from where/who?

Quoted 3 lines

[...snip...]

#15 lore raw
Quoted 61 lines · Ackerley Tng
Quoted 4 lines · David Woodhouse

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

Quoted 8 lines

 • No struct page overheads

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

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

Also, no need to split/merge pages when converting from private to shared if the host mappings can't depend on the refcounts in struct pages :).

Quoted 9 lines

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 state to be passed over KHO/kexec.

Thanks for raising this, good to know that there is more interest!

Vishal and I have been working on guest_memfd with HugeTLB for a while now. I'll be restarting upstream work on HugeTLB after the conversions series merges.

Vishal, Frank and I brought up having guest_memfd with HugeTLB with VM_PFNMAP mappings at a guest_memfd biweekly meeting a while ago. The consensus was that guest_memfd HugeTLB must support GUP and so VM_PFNMAP can't be the only way that guest_memfd supports HugeTLB.

Your proposal is true non-page-struct memory, which has been on the discussion guest_memfd biweekly discussion backlog for a while now. Google is definitely also interested in this.

Frank also described some use cases [1] other than HugeTLB and the regular PAGE_SIZE pages from the buddy that is currently supported.

I submitted a proposal for LPC 2026 to discuss the interface. What I had in mind was to have the KVM_GUEST_MEMFD_CREATE ioctl take a "template" fd. guest_memfd will then read off what it needs from the "template" fd (ops, like you have here), and the "template" fd could be VFIO [2] or HugeTLB.

You have a provider_fd = open("/dev/gmem_provider"), how about passing that provider_fd to guest_memfd, where /dev/gmem_provider could represent the page-less memory, like:

  ioctl(kvm_fd, KVM_GUEST_MEMFD_CREATE, provider_fd);

It would be cool if the fallback could be set up flexibly, like:

Quoted 8 lines

  ioctl(kvm_fd, KVM_GUEST_MEMFD_CREATE, [provider_fd, fallback_provider_fd, ...]);

I think guest_memfd should be the wrapper around other memory providers because then the CoCo shared/private logic and special page table handling for both host and stage 2 page tables is centralized in guest_memfd, and also, KVM doesn't have to understand other, different kinds of fds other than guest_memfd.

Yeah. My approach was to make those "other kinds of fds" essentially the same — they are "a guest_memfd", and KVM didn't have to understand anything else (after a little bit of rework to have the generic ops so that other code can create its own guest_memfds). As opposed to the approach in Xu Yilun's TDISP series, which did teach KVM about a new kind of memslot.

Likewise, I used dma-buf so that IOMMUFD didn't have to understand anything new either.

I like your approach, inverting the wrapping of guest_memfd/dma-buf. The provider then gives a plain dma-buf (not associated with any KVM as it is in my current code). Userspace can use that *directly* with the IOMMU, and passes it to your KVM_GUEST_MEMFD_CREATE in order to get a guest_memfd for use with a given KVM. I think a lot of the warts in my series fall away if we do it that way round.

I'll have a go at reworking it that way round... and see what different warts it ends up with. The interesting part will be getting actual PFNs out of the dma-buf (which is already under active discussion).

I'm not sure I understand the 'fallback provider' part. If one provider doesn't have a page for a given address, KVM would iterate over them all until it finds one that does? Is that about falling back from one THP pool to another? Is this something that the generic KVM code needs to know about, or could it be handled *within* a provider, which can chain to the next pool if it can't find a page? Wouldn't we want that done transparently for both KVM and IOMMU consumers?

Quoted 19 lines

[1] https://lore.kernel.org/all/CAPTztWajm_JLpp9BjRcX=h72r25ELrXeGkOXVachybBxLJGS=g@mail.gmail.com/
[2] https://lore.kernel.org/all/CAEvNRgFpJWQ5M5sQhGpQUV3GbBq9N+MQhhaxdxa=D8ky94SCsw@mail.gmail.com/

Quoted 8 lines

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.

Quoted 6 lines

It's largely AI-built at the moment. My main design concerns are around how 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.

Quoted 2 lines

IIUC from this series, you're creating a dmabuf fd out of a guest_memfd, what does "taking pages away" mean, in this case, from where/who?

Taken away from the guest. Ballooning pages out, either for traditional memory overcommit, or for the models where a guest donates some of its pages to the system to run a "child" which is properly isolated from the guest.

The physical page is reclaimed and needs to be taken out of the KVM and IOMMU stage2 mappings. If KVM wants to touch it again it must call the provider to get a new PFN for that range. This is roughly equivalent to the MMU notifier path on userspace VMAs in the normal memslot case. IOMMUFD has no equivalent of that for userspace addresses — IOMMU_IOAS_MAP pins the pages so they *can't* go away, which is why I used dma-buf for the IOMMUFD interface.

I've actually been fleshing out the overcommit path a bit more, experimenting with adding async-pf support to guest_memfd in
https://git.infradead.org/?p=users/dwmw2/linux.git;a=commitdiff;h=894dd0fcb34
(the sample provider just pretends its pages are slow to populate, so the guest gets to run something else while a "reclaimed" page comes back).

#16 lore raw
Quoted 78 lines · David Woodhouse
Quoted 61 lines · Ackerley Tng
Quoted 4 lines · David Woodhouse

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

Quoted 8 lines

 • No struct page overheads

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

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

Also, no need to split/merge pages when converting from private to shared if the host mappings can't depend on the refcounts in struct pages :).

Quoted 9 lines

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 state to be passed over KHO/kexec.

Thanks for raising this, good to know that there is more interest!

Vishal and I have been working on guest_memfd with HugeTLB for a while now. I'll be restarting upstream work on HugeTLB after the conversions series merges.

Vishal, Frank and I brought up having guest_memfd with HugeTLB with VM_PFNMAP mappings at a guest_memfd biweekly meeting a while ago. The consensus was that guest_memfd HugeTLB must support GUP and so VM_PFNMAP can't be the only way that guest_memfd supports HugeTLB.

Your proposal is true non-page-struct memory, which has been on the discussion guest_memfd biweekly discussion backlog for a while now. Google is definitely also interested in this.

Frank also described some use cases [1] other than HugeTLB and the regular PAGE_SIZE pages from the buddy that is currently supported.

I submitted a proposal for LPC 2026 to discuss the interface. What I had in mind was to have the KVM_GUEST_MEMFD_CREATE ioctl take a "template" fd. guest_memfd will then read off what it needs from the "template" fd (ops, like you have here), and the "template" fd could be VFIO [2] or HugeTLB.

You have a provider_fd = open("/dev/gmem_provider"), how about passing that provider_fd to guest_memfd, where /dev/gmem_provider could represent the page-less memory, like:

  ioctl(kvm_fd, KVM_GUEST_MEMFD_CREATE, provider_fd);

It would be cool if the fallback could be set up flexibly, like:

Quoted 8 lines

  ioctl(kvm_fd, KVM_GUEST_MEMFD_CREATE, [provider_fd, fallback_provider_fd, ...]);

I think guest_memfd should be the wrapper around other memory providers because then the CoCo shared/private logic and special page table handling for both host and stage 2 page tables is centralized in guest_memfd, and also, KVM doesn't have to understand other, different kinds of fds other than guest_memfd.

Yeah. My approach was to make those "other kinds of fds" essentially the same — they are "a guest_memfd", and KVM didn't have to understand anything else (after a little bit of rework to have the generic ops so that other code can create its own guest_memfds). As opposed to the approach in Xu Yilun's TDISP series, which did teach KVM about a new kind of memslot.

Quoted 7 lines

Likewise, I used dma-buf so that IOMMUFD didn't have to understand anything new either.

I like your approach, inverting the wrapping of guest_memfd/dma-buf. The provider then gives a plain dma-buf (not associated with any KVM as it is in my current code). Userspace can use that *directly* with the IOMMU,

A wrinkle we will have to iron out is kind of the opposite problem, to make sure that while guest_memfd thinks a range of offsets (PAGE_SIZE or larger) is CoCo-private, the PFNs in that range must not be mapped anywhere else in the host, or IOMMU.

One of the options I was thinking of was to seal off the template fd, perhaps with an inode flag like S_IMMUTABLE, but not even allow reads, and unlike S_IMMUTABLE, the (new) flag must not be changeable by userspace.

Another option would be to just close the template fd so it'll not be used, and the PFNs behind that template fd would just be completely in guest_memfd ownership.

All non-guest_memfd paths to access the PFNs must be closed off, or perhaps more precisely, any path that is not checked for CoCo-shared/private status before building page table entries must be closed off.

For CoCo-shared memory as tracked by guest_memfd (or non-CoCo, which would use SHARED), the PFNs can still be mmap()-ed and actually set up in userspace page tables.

Then, to use CoCo-shared memory for IO, IOMMUFD would also have to take the guest_memfd (which IOMMUFD probably has to do, for CoCo-private memory for Confidential IO, since CoCo-private memory can't be mapped to userspace). Perhaps through IOMMU_IOAS_MAP_FILE?

In the process of mapping, IOMMUFD would tell guest_memfd "I have some of your PFNs mapped.", and when guest_memfd gets a private->shared conversion request, guest_memfd would get IOMMUFD to drop the mappings. (perhaps some kind of MMU notifier setup)

Do you plan to use this for non-CoCo?

Quoted 8 lines

and passes it to your KVM_GUEST_MEMFD_CREATE in order to get a guest_memfd for use with a given KVM. I think a lot of the warts in my series fall away if we do it that way round.

I'll have a go at reworking it that way round... and see what different warts it ends up with. The interesting part will be getting actual PFNs out of the dma-buf (which is already under active discussion).

If we go with the above, IOMMUFD would get PFNs from guest_memfd instead of dma-buf.

Quoted 3 lines

I'm not sure I understand the 'fallback provider' part. If one provider doesn't have a page for a given address, KVM would iterate over them all until it finds one that does?

If each provider provides a .get_pfn() op, guest_memfd's kvm_gmem_get_pfn() would try the first provider's .get_pfn() and if that errors out, try the next one.

guest_memfd today uses a standard struct address_space to track the pages that it owns. guest_memfd will have to use something else that can track both pages and PFNs, and probably which provider it came from.

The more you probe me, the more complicated it's sounding. :) Still worth pursuing if it's good to have though.

Quoted 4 lines

Is that about falling back from one
THP pool to another? Is this something that the generic KVM code needs to know about, or could it be handled *within* a provider, which can chain to the next pool if it can't find a page?

Handling that within a provider could be nice too, so instead of guest_memfd trying .get_pfn()s in series, the provider will try a hard-coded pair/list of PFN sources and then deal with the complexity on behalf guest_memfd?

The flipside is for every combination of providers, the owner of the virtualization service would have to maintain a custom kernel module for the managing pages?

Maybe the flipside isn't too bad, actually, to provide more flexibility.

Quoted 25 lines

Wouldn't we want that
done transparently for both KVM and IOMMU consumers?

Quoted 19 lines

[1] https://lore.kernel.org/all/CAPTztWajm_JLpp9BjRcX=h72r25ELrXeGkOXVachybBxLJGS=g@mail.gmail.com/
[2] https://lore.kernel.org/all/CAEvNRgFpJWQ5M5sQhGpQUV3GbBq9N+MQhhaxdxa=D8ky94SCsw@mail.gmail.com/

Quoted 8 lines

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.

Quoted 6 lines

It's largely AI-built at the moment. My main design concerns are around how 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.

Quoted 2 lines

IIUC from this series, you're creating a dmabuf fd out of a guest_memfd, what does "taking pages away" mean, in this case, from where/who?

Quoted 7 lines

Taken away from the guest. Ballooning pages out, either for traditional memory overcommit, or for the models where a guest donates some of its pages to the system to run a "child" which is properly isolated from the guest.

The physical page is reclaimed and needs to be taken out of the KVM and IOMMU stage2 mappings.

Will the VMM be doing a PUNCH_HOLE on the dma-buf fd or guest_memfd to actually reclaim the page, or do you have something else in mind?

Quoted 13 lines

If KVM wants to touch it again it must call the
provider to get a new PFN for that range. This is roughly equivalent to the MMU notifier path on userspace VMAs in the normal memslot case. IOMMUFD has no equivalent of that for userspace addresses — IOMMU_IOAS_MAP pins the pages so they *can't* go away, which is why I used dma-buf for the IOMMUFD interface.

I've actually been fleshing out the overcommit path a bit more, experimenting with adding async-pf support to guest_memfd in
https://git.infradead.org/?p=users/dwmw2/linux.git;a=commitdiff;h=894dd0fcb34
(the sample provider just pretends its pages are slow to populate, so the guest gets to run something else while a "reclaimed" page comes back).

#17 lore raw

cover KVM: guest_memfd: back guest_memfd with an imported dma-buf

In reply to David Woodhouse

From: Fred Griffoul <[email protected]>

This extends David Woodhouse's "KVM: Allow alternative providers of guest_memfd backed by PFNMAP memory" RFC (v2) to let guest_memfd import a dma-buf as its page source:

https://lore.kernel.org/kvm/[email protected]/

The memory owner is a plain dma-buf exporter, linking against neither KVM nor iommufd. guest_memfd imports it for the guest (stage-2) plane and iommufd imports the same buffer for the device (DMA) plane, so one object and one invalidation protocol serve both. This is a concrete answer to the "how do we plug into iommufd without masquerading as a dma-buf" question from David's cover: the provider does not pretend to be anything; the dma-buf is the shared object.

Applies on top of David's v2 series.

Patches:

1 KVM: guest_memfd: Add a writable result to get_pfn()
Give get_pfn() a writable out-param so a backing can map a page present but read-only (KVM_MEM_READONLY is rejected on guest_memfd slots). A guest write then exits as a memory fault. Stage-2 only; KVM's own host-mapped accesses are unaffected.

2 dma-buf: Add get_phys() to describe a physical run
New exporter op: for an offset+len, return one physically contiguous backed run and an attribute word (RAM/MMIO, plus READONLY). -ENOENT for an unbacked byte, -ENODEV when revoked. Lets a page-table-building importer ask where the memory is instead of taking a scatterlist. Converts vfio-pci, the iommufd selftest exporter and the sample; iommufd behaviour is unchanged.

3 dma-buf: Add ranged mapping invalidation
Invalidate a byte range rather than the whole buffer. The callback means "re-query this range" and covers loss, replacement and read-only flips. Importers without the callback still get a whole-buffer invalidation.

4 dma-buf: Allow dynamic attach without a device
Allow a dynamic importer with no struct device, for a consumer (KVM) that only needs the physical layout and builds its own tables. Such an importer must not map the attachment for DMA.

5 KVM: guest_memfd: Add dma-buf backing
Add GUEST_MEMFD_FLAG_USE_DMABUF and a dmabuf_fd to KVM_CREATE_GUEST_MEMFD. guest_memfd attaches as a revocable importer without a device, serves faults from get_phys() (largest aligned RAM run, read-only honoured), and zaps the range on the invalidation callback.

6 samples/kvm, selftests/kvm: Exercise dma-buf backing
Turn the sample into a dma-buf exporter (a toy memory owner: one root region, a child per VM, move/donate/reclaim, absent and read-only pages, a scratch page, per-child ioctl allowlists) and move the selftests to feed one dma-buf fd to both guest_memfd and iommufd.

Scope: non-confidential VMs, RAM backings only; iommufd keeps its single-range import for now. As with David's series, this is largely AI-assisted and is posted to get the interface shape reviewed.

Fred Griffoul (6):
KVM: guest_memfd: Add a writable result to get_pfn()
dma-buf: Add get_phys() to describe a physical run
dma-buf: Add ranged mapping invalidation
dma-buf: Allow dynamic attach without a device
KVM: guest_memfd: Add dma-buf backing samples/kvm, selftests/kvm: Exercise dma-buf backing

 arch/arm64/kvm/mmu.c                          |   13 +-
 arch/arm64/kvm/nested.c                       |   10 +-
 arch/x86/kvm/mmu/mmu.c                        |   18 +-
 arch/x86/kvm/svm/sev.c                        |    4 +-
 drivers/dma-buf/dma-buf.c                     |   92 +-
 drivers/iommu/iommufd/iommufd_private.h       |    8 -
 drivers/iommu/iommufd/iommufd_test.h          |   16 +
 drivers/iommu/iommufd/pages.c                 |   74 +-
 drivers/iommu/iommufd/selftest.c              |  106 +-
 drivers/vfio/pci/vfio_pci_dmabuf.c            |   58 +-
 include/linux/dma-buf.h                       |   70 +
 include/linux/kvm_host.h                      |   12 +-
 include/linux/vfio_pci_core.h                 |    3 -
 include/trace/events/dma_buf.h                |    2 +-
 include/uapi/linux/kvm.h                      |    6 +-
 samples/kvm/gmem_provider.c                   | 1311 ++++++++++-------
 samples/kvm/gmem_provider.h                   |  144 +-
 tools/include/uapi/linux/kvm.h                |    6 +-
 tools/testing/selftests/kvm/Makefile.kvm      |    3 +-
 .../kvm/gmem_provider_nvme_dma_test.c         |   28 +-
 .../testing/selftests/kvm/include/kvm_util.h  |   25 +-
 .../testing/selftests/kvm/x86/gmem_poc_test.c |  824 +++++++++++
 .../kvm/x86/gmem_provider_hugepage_test.c     |   30 +-
 .../kvm/x86/gmem_provider_iommufd_test.c      |   42 +-
 .../kvm/x86/gmem_provider_readonly_test.c     |  172 +++
 .../kvm/x86/gmem_provider_revoke_test.c       |   34 +-
 .../selftests/kvm/x86/gmem_provider_test.c    |  190 +--
 .../kvm/x86/gmem_provider_vfio_test.c         |   45 +-
 virt/kvm/Kconfig                              |    1 +
 virt/kvm/guest_memfd.c                        |  252 +++-
 30 files changed, 2703 insertions(+), 896 deletions(-)
 create mode 100644 tools/testing/selftests/kvm/x86/gmem_poc_test.c
 create mode 100644 tools/testing/selftests/kvm/x86/gmem_provider_readonly_test.c

--
2.47.3

#18 lore raw

RFC PATCH 1/6 KVM: guest_memfd: Add a writable result to get_pfn()

From: Fred Griffoul <[email protected]>

A guest_memfd backing has no way to tell KVM that a page must stay mapped but must not be written by the guest. get_pfn() returns only a frame, and KVM takes write access from the memslot flags. KVM_MEM_READONLY is not an option: KVM refuses it on guest_memfd slots, because it emulates a write to a read-only slot as MMIO, which private memory cannot support.

Add a writable output to get_pfn(). KVM sets it to true before the call, and the backing may clear it. When it is false, the x86 and arm64 stage-2 fault paths map the page without write permission. A guest write to that page then exits to userspace as a memory fault; KVM first releases any page that the backing returned. Callers that do not map the page pass NULL.

The result applies to stage-2 mappings only. When KVM writes guest memory through the memslot's host address, the permissions of the host mapping apply.

---
 arch/arm64/kvm/mmu.c        | 13 ++++++++-----
 arch/arm64/kvm/nested.c     | 10 +++++++---
 arch/x86/kvm/mmu/mmu.c      | 18 ++++++++++++++++--
 arch/x86/kvm/svm/sev.c      |  4 ++--
 include/linux/kvm_host.h    | 11 ++++++++---
 samples/kvm/gmem_provider.c |  3 ++-
 virt/kvm/guest_memfd.c      | 13 ++++++++-----
 7 files changed, 51 insertions(+), 21 deletions(-)
arch/arm64/kvm/mmu.c +8 -5
index 6c941aaa10c6..32e591edc69d 100644
@@ -1607,7 +1607,7 @@ struct kvm_s2_fault_desc {
 
 static int gmem_abort(const struct kvm_s2_fault_desc *s2fd)
 {
-	bool write_fault, exec_fault;
+	bool write_fault, exec_fault, writable;
 	bool perm_fault = kvm_vcpu_trap_is_permission_fault(s2fd->vcpu);
 	enum kvm_pgtable_walk_flags flags = KVM_PGTABLE_WALK_SHARED;
 	enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_R;
@@ -1641,14 +1641,17 @@ static int gmem_abort(const struct kvm_s2_fault_desc *s2fd)
 	/* Pairs with the smp_wmb() in kvm_mmu_invalidate_end(). */
 	smp_rmb();
 
-	ret = kvm_gmem_get_pfn(kvm, s2fd->memslot, gfn, &pfn, &page, NULL);
-	if (ret) {
+	ret = kvm_gmem_get_pfn(kvm, s2fd->memslot, gfn, &pfn, &page, NULL,
+			       &writable);
+	if (ret || (write_fault && !writable)) {
 		kvm_prepare_memory_fault_exit(s2fd->vcpu, s2fd->fault_ipa, PAGE_SIZE,
 					      write_fault, exec_fault, false);
-		return ret;
+		if (!ret)
+			kvm_release_faultin_page(kvm, page, true, false);
+		return ret ?: -EFAULT;
 	}
 
-	if (!(s2fd->memslot->flags & KVM_MEM_READONLY))
+	if (!(s2fd->memslot->flags & KVM_MEM_READONLY) && writable)
 		prot |= KVM_PGTABLE_PROT_W;
 
 	if (s2fd->nested)
arch/arm64/kvm/nested.c +7 -3
index fb54f6dad995..9ad1fa029835 100644
@@ -1411,12 +1411,16 @@ static int kvm_translate_vncr(struct kvm_vcpu *vcpu, bool *is_gmem)
 		if (is_error_noslot_pfn(pfn) || (write_fault && !writable))
 			return -EFAULT;
 	} else {
-		ret = kvm_gmem_get_pfn(vcpu->kvm, memslot, gfn, &pfn, &page, NULL);
-		if (ret) {
+		ret = kvm_gmem_get_pfn(vcpu->kvm, memslot, gfn, &pfn, &page, NULL,
+				       &writable);
+		if (ret || (write_fault && !writable)) {
 			kvm_prepare_memory_fault_exit(vcpu, vt->wr.pa, PAGE_SIZE,
 					      write_fault, false, false);
-			return ret;
+			if (!ret)
+				kvm_release_faultin_page(vcpu->kvm, page, true, false);
+			return ret ?: -EFAULT;
 		}
+		vt->wr.pw &= writable;
 	}
 
 	scoped_guard(write_lock, &vcpu->kvm->mmu_lock) {
arch/x86/kvm/mmu/mmu.c +16 -2
index 234d0a95abf5..17ac2bfdc164 100644
@@ -4612,6 +4612,7 @@ static void kvm_mmu_finish_page_fault(struct kvm_vcpu *vcpu,
 static int kvm_mmu_faultin_pfn_gmem(struct kvm_vcpu *vcpu,
 				    struct kvm_page_fault *fault)
 {
+	bool writable;
 	int max_order, r;
 
 	if (!kvm_slot_has_gmem(fault->slot)) {
@@ -4620,13 +4621,26 @@ static int kvm_mmu_faultin_pfn_gmem(struct kvm_vcpu *vcpu,
 	}
 
 	r = kvm_gmem_get_pfn(vcpu->kvm, fault->slot, fault->gfn, &fault->pfn,
-			     &fault->refcounted_page, &max_order);
+			     &fault->refcounted_page, &max_order, &writable);
 	if (r) {
 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
 		return r;
 	}
 
-	fault->map_writable = !(fault->slot->flags & KVM_MEM_READONLY);
+	/*
+	 * The memory's owner has the final say on writability, on top of the
+	 * memslot flag: a page it reports read-only is mapped read-only, and a
+	 * guest write to it exits to userspace rather than being installed.
+	 */
+	fault->map_writable = !(fault->slot->flags & KVM_MEM_READONLY) &&
+			      writable;
+	if (fault->write && !fault->map_writable) {
+		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
+		kvm_release_faultin_page(vcpu->kvm, fault->refcounted_page,
+				 true, false);
+		fault->refcounted_page = NULL;
+		return -EFAULT;
+	}
 	fault->max_level = kvm_max_level_for_order(max_order);
 
 	return RET_PF_CONTINUE;
arch/x86/kvm/svm/sev.c +2 -2
index 125779c82bc4..983e19f7dbd2 100644
@@ -4063,7 +4063,7 @@ static void sev_snp_init_protected_guest_state(struct kvm_vcpu *vcpu)
 	 * The new VMSA will be private memory guest memory, so retrieve the
 	 * PFN from the gmem backend.
 	 */
-	if (kvm_gmem_get_pfn(vcpu->kvm, slot, gfn, &pfn, &page, NULL))
+	if (kvm_gmem_get_pfn(vcpu->kvm, slot, gfn, &pfn, &page, NULL, NULL))
 		return;
 
 	/*
@@ -4996,7 +4996,7 @@ void sev_handle_rmp_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code)
 		return;
 	}
 
-	ret = kvm_gmem_get_pfn(kvm, slot, gfn, &pfn, &page, &order);
+	ret = kvm_gmem_get_pfn(kvm, slot, gfn, &pfn, &page, &order, NULL);
 	if (ret) {
 		pr_warn_ratelimited("SEV: Unexpected RMP fault, no backing page for private GPA 0x%llx\n",
 				    gpa);
include/linux/kvm_host.h +8 -3
index 04fa0cb126f6..f84f3ab44acf 100644
@@ -660,9 +660,14 @@ struct kvm_gmem_ops {
 		    struct kvm_memory_slot *slot, loff_t offset);
 	void (*unbind)(struct file *file, struct kvm *kvm,
 		       struct kvm_memory_slot *slot);
+	/*
+	 * @writable: [out] clear to have KVM map the page read-only; a guest
+	 * write then exits as a memory fault.  NULL if the caller does not care.
+	 */
 	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);
+		       kvm_pfn_t *pfn, struct page **page, int *max_order,
+		       bool *writable);
 	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);
@@ -2651,12 +2656,12 @@ static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)
 #ifdef CONFIG_KVM_GUEST_MEMFD
 int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 		     gfn_t gfn, kvm_pfn_t *pfn, struct page **page,
-		     int *max_order);
+		     int *max_order, bool *writable);
 #else
 static inline int kvm_gmem_get_pfn(struct kvm *kvm,
 				   struct kvm_memory_slot *slot, gfn_t gfn,
 				   kvm_pfn_t *pfn, struct page **page,
-				   int *max_order)
+				   int *max_order, bool *writable)
 {
 	KVM_BUG_ON(1, kvm);
 	return -EIO;
samples/kvm/gmem_provider.c +2 -1
index 9728f5a8029b..75197c088762 100644
@@ -157,7 +157,8 @@ static int gmem_max_order(struct gmem_info *info, gfn_t gfn, unsigned long index
 
 static int gmem_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)
+			kvm_pfn_t *pfn, struct page **page, int *max_order,
+			bool *writable)
 {
 	struct gmem_info *info = to_gmem_info(file);
 	pgoff_t index = gfn - slot->base_gfn + slot->gmem.pgoff;
virt/kvm/guest_memfd.c +8 -5
index d284bb70fe05..0f4bf2cc5e8e 100644
@@ -624,7 +624,7 @@ static void kvm_gmem_native_unbind(struct file *slot_file, struct kvm *kvm,
 static int  kvm_gmem_native_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 *max_order, bool *writable);
 static void kvm_gmem_native_release(struct file *file);
 static int  kvm_gmem_native_mmap(struct file *file,
 				 struct vm_area_struct *vma);
@@ -988,7 +988,7 @@ static struct folio *__kvm_gmem_get_pfn(struct file *file,
 static int kvm_gmem_native_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 *max_order, bool *writable)
 {
 	pgoff_t index = kvm_gmem_get_index(slot, gfn);
 	struct folio *folio;
@@ -1016,7 +1016,7 @@ static int kvm_gmem_native_get_pfn(struct file *file, struct kvm *kvm,
 
 int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 		     gfn_t gfn, kvm_pfn_t *pfn, struct page **page,
-		     int *max_order)
+		     int *max_order, bool *writable)
 {
 	const struct kvm_gmem_ops *ops;
 
@@ -1029,7 +1029,10 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 		return -EFAULT;
 
 	*page = NULL;
-	return ops->get_pfn(file, kvm, slot, gfn, pfn, page, max_order);
+	if (writable)
+		*writable = true;
+	return ops->get_pfn(file, kvm, slot, gfn, pfn, page, max_order,
+			    writable);
 }
 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_gmem_get_pfn);
 
@@ -1093,7 +1096,7 @@ static int kvm_gmem_populate_one(const struct kvm_gmem_ops *ops,
 				    src_page, 0);
 	else
 		ret = ops->get_pfn(file, kvm, slot, gfn, &pfn,
-				   &ignored_page, NULL);
+				   &ignored_page, NULL, NULL);
 	if (ret)
 		return ret;
 
Signature · 1 line
2.47.3
#19 lore raw

RFC PATCH 2/6 dma-buf: Add get_phys() to describe a physical run

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

iommufd and KVM write physical addresses into their own page tables. To do so, they must ask the exporter which frames back an offset of a dma-buf, whether that memory is RAM or MMIO, and whether it may be written.

Add a get_phys() operation. The importer passes an offset and a maximum length. The exporter reports one run: the frames that start at the offset, are backed and physically contiguous, and share one attribute word. The run never exceeds the length. The exporter may end it early, so importers must not assume that it is the longest possible run.

get_phys() returns -ENOENT when the byte at the offset is not backed, and -ENODEV when the buffer is revoked. The caller holds the reservation, and either pins the attachment or handles revocation. A reported frame stays valid until an invalidation that covers it returns.

The attribute word holds the memory type and a READONLY flag. Zero means writable RAM. Importers refuse unknown types, reserved bits and unknown flags, so attributes added later fail safely. Two flag bits are
reserved: one for holes and one for confidential memory.

Convert vfio-pci, the iommufd selftest exporter and the KVM sample. iommufd behaves as before: it maps a buffer only when one writable run covers all of it.

---
 drivers/dma-buf/dma-buf.c               |  47 +++++++++++
 drivers/iommu/iommufd/iommufd_private.h |   8 --
 drivers/iommu/iommufd/iommufd_test.h    |  16 ++++
 drivers/iommu/iommufd/pages.c           |  74 ++++-------------
 drivers/iommu/iommufd/selftest.c        | 106 ++++++++++++++++++++----
 drivers/vfio/pci/vfio_pci_dmabuf.c      |  58 ++++++-------
 include/linux/dma-buf.h                 |  54 ++++++++++++
 include/linux/vfio_pci_core.h           |   3 -
 samples/kvm/gmem_provider.c             |  39 ++++-----
 9 files changed, 267 insertions(+), 138 deletions(-)
drivers/dma-buf/dma-buf.c +47 -0
index d504c636dc29..66b85d53ed22 100644
@@ -1389,6 +1389,53 @@ void dma_buf_invalidate_mappings(struct dma_buf *dmabuf)
 }
 EXPORT_SYMBOL_NS_GPL(dma_buf_invalidate_mappings, "DMA_BUF");
 
+/**
+ * dma_buf_get_phys - describe the run that starts at an offset
+ * @attach: attachment to query
+ * @offset: first buffer byte to describe
+ * @len: maximum number of bytes to describe
+ * @phys: physical address and length of the run
+ * @attr: DMA_BUF_PHYS_ATTR_* word of the run
+ *
+ * A run is the longest stretch of backed bytes starting at @offset whose
+ * frames are physically contiguous and share one attribute word. On success
+ * *@phys starts at the byte at @offset and covers at most @len bytes; it may
+ * be shorter than the run.
+ *
+ * The dma-buf reservation must be held. The attachment must be pinned or have
+ * revocable importer operations. A frame remains valid until a covering
+ * invalidation callback returns; the exporter must invalidate a changed range
+ * before reusing its old frames.
+ *
+ * Returns:
+ *
+ * 0 on success, -ENOENT if the byte at @offset is not backed, -ENODEV if the
+ * buffer is revoked, -EOPNOTSUPP if the exporter cannot describe itself this
+ * way, or another negative error code.
+ */
+int dma_buf_get_phys(struct dma_buf_attachment *attach, u64 offset, u64 len,
+		     struct phys_vec *phys, u32 *attr)
+{
+	u64 end;
+	int ret;
+
+	if (WARN_ON_ONCE(!attach || !attach->dmabuf || !phys || !attr))
+		return -EINVAL;
+	if (!len || check_add_overflow(offset, len, &end) ||
+	    end > attach->dmabuf->size)
+		return -EINVAL;
+
+	dma_resv_assert_held(attach->dmabuf->resv);
+	if (!attach->dmabuf->ops->get_phys)
+		return -EOPNOTSUPP;
+
+	ret = attach->dmabuf->ops->get_phys(attach, offset, len, phys, attr);
+	if (!ret && WARN_ON_ONCE(!phys->len || phys->len > len))
+		return -EIO;
+	return ret;
+}
+EXPORT_SYMBOL_NS_GPL(dma_buf_get_phys, "DMA_BUF");
+
 /**
  * DOC: cpu access
  *
drivers/iommu/iommufd/iommufd_private.h +0 -8
index 43fbc5bed8de..5cded585c227 100644
@@ -716,8 +716,6 @@ bool iommufd_should_fail(void);
 int __init iommufd_test_init(void);
 void iommufd_test_exit(void);
 bool iommufd_selftest_is_mock_dev(struct device *dev);
-int iommufd_test_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
-				     struct phys_vec *phys);
 #else
 static inline void iommufd_test_syz_conv_iova_id(struct iommufd_ucmd *ucmd,
 						 unsigned int ioas_id,
@@ -739,11 +737,5 @@ static inline bool iommufd_selftest_is_mock_dev(struct device *dev)
 {
 	return false;
 }
-static inline int
-iommufd_test_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
-				 struct phys_vec *phys)
-{
-	return -EOPNOTSUPP;
-}
 #endif
 #endif
drivers/iommu/iommufd/iommufd_test.h +16 -0
index 52b78cbcc920..28fd9c43edc4 100644
@@ -31,6 +31,8 @@ enum {
 	IOMMU_TEST_OP_PASID_CHECK_HWPT,
 	IOMMU_TEST_OP_DMABUF_GET,
 	IOMMU_TEST_OP_DMABUF_REVOKE,
+	IOMMU_TEST_OP_MD_CHECK_MAPPED,
+	IOMMU_TEST_OP_MD_IOVA_TO_PHYS,
 };
 
 enum {
@@ -193,6 +195,20 @@ struct iommu_test_cmd {
 			__s32 dmabuf_fd;
 			__u32 revoked;
 		} dmabuf_revoke;
+		struct {
+			/*
+			 * 1: every page in [iova, iova+length) must be mapped;
+			 * 0: none of them may be. Mixed is an error.
+			 */
+			__u32 mapped;
+			__u32 __reserved;
+			__aligned_u64 iova;
+			__aligned_u64 length;
+		} check_mapped;
+		struct {
+			__aligned_u64 iova;
+			__aligned_u64 out_phys;	/* 0 if unmapped */
+		} iova_to_phys;
 	};
 	__u32 last;
 };
drivers/iommu/iommufd/pages.c +14 -60

92 lines not on this page · raw message

drivers/iommu/iommufd/selftest.c +90 -16

134 lines not on this page · raw message

drivers/vfio/pci/vfio_pci_dmabuf.c +29 -29

75 lines not on this page · raw message

include/linux/dma-buf.h +54 -0

78 lines not on this page · raw message

include/linux/vfio_pci_core.h +0 -3
index 9a1674c152aa..2a1d13abdb0c 100644
@@ -257,7 +257,4 @@ vfio_pci_core_get_iomap(struct vfio_pci_core_device *vdev, unsigned int bar)
 	return vdev->barmap[bar];
 }
 
-int vfio_pci_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
-				 struct phys_vec *phys);
-
 #endif /* VFIO_PCI_CORE_H */
samples/kvm/gmem_provider.c +17 -22
index 75197c088762..b6824fe5d228 100644
@@ -487,35 +487,30 @@ static void gmem_dma_buf_release(struct dma_buf *dmabuf)
 	kfree(priv);
 }
 
-static const struct dma_buf_ops gmem_dma_buf_ops = {
-	.attach		= gmem_dma_buf_attach,
-	.map_dma_buf	= gmem_dma_buf_map,
-	.unmap_dma_buf	= gmem_dma_buf_unmap,
-	.release	= gmem_dma_buf_release,
-};
-
-/*
- * Private interconnect for iommufd (mirrors vfio_pci_dma_buf_iommufd_map).
- * Returns the single contiguous phys range for the exported region so iommufd
- * can program the IOMMU directly, bypassing the DMA API.
- */
-int gmem_provider_dma_buf_iommufd_map(struct dma_buf_attachment *attach,
-				      struct phys_vec *phys);
-int gmem_provider_dma_buf_iommufd_map(struct dma_buf_attachment *attach,
-				      struct phys_vec *phys)
+/* Report this flat sample region through the generic dma-buf operation. */
+static int gmem_dma_buf_get_phys(struct dma_buf_attachment *attach,
+				 u64 offset, u64 len,
+				 struct phys_vec *phys, u32 *attr)
 {
-	struct gmem_dmabuf *priv;
+	struct gmem_dmabuf *priv = attach->dmabuf->priv;
 
 	dma_resv_assert_held(attach->dmabuf->resv);
-	if (attach->dmabuf->ops != &gmem_dma_buf_ops)
-		return -EOPNOTSUPP;
-	priv = attach->dmabuf->priv;
 	if (priv->revoked)
 		return -ENODEV;
-	*phys = priv->phys;
+
+	phys->paddr = priv->phys.paddr + offset;
+	phys->len = len;
+	*attr = DMA_BUF_PHYS_ATTR_RAM;
 	return 0;
 }
-EXPORT_SYMBOL_FOR_MODULES(gmem_provider_dma_buf_iommufd_map, "iommufd");
+
+static const struct dma_buf_ops gmem_dma_buf_ops = {
+	.attach		= gmem_dma_buf_attach,
+	.map_dma_buf	= gmem_dma_buf_map,
+	.unmap_dma_buf	= gmem_dma_buf_unmap,
+	.release	= gmem_dma_buf_release,
+	.get_phys	= gmem_dma_buf_get_phys,
+};
 
 /* Called with info->dmabufs_lock held on the revoke path. */
 static void gmem_dma_buf_revoke_all(struct gmem_info *info)
Signature · 1 line
2.47.3
maintainer
#20 lore raw

Re: [RFC PATCH 2/6] dma-buf: Add get_phys() to describe a physical run

Quoted 6 lines · Fred Griffoul

From: Fred Griffoul <[email protected]>

iommufd and KVM write physical addresses into their own page tables. To do so, they must ask the exporter which frames back an offset of a dma-buf, whether that memory is RAM or MMIO, and whether it may be written.

Well filling page tables by the importer is an absolutely clear NO-GO for the DMA-buf design, we have gotten down that path already and it took us years to remove this functionality again.

The problem you are facing here is that dma_buf_mmap() doesn't work because you don't have a VMA.

I can understand the reasoning that you don't want to have a VMA, but I don't think that this is a valid justification to add complexity to DMA-buf and especially bring an approach back which we have already deprecated.

A possible solution might be Jasons patch set to directly negotiate exposing PCI BAR regions as DMA-buf, but that certainly needs more discussion.

But the approach outlined here is an absolutely clear NAK from my side.

Regards,
Christian.

Quoted 629 lines

Add a get_phys() operation. The importer passes an offset and a maximum length. The exporter reports one run: the frames that start at the offset, are backed and physically contiguous, and share one attribute word. The run never exceeds the length. The exporter may end it early, so importers must not assume that it is the longest possible run.

get_phys() returns -ENOENT when the byte at the offset is not backed, and -ENODEV when the buffer is revoked. The caller holds the reservation, and either pins the attachment or handles revocation. A reported frame stays valid until an invalidation that covers it returns.

The attribute word holds the memory type and a READONLY flag. Zero means writable RAM. Importers refuse unknown types, reserved bits and unknown flags, so attributes added later fail safely. Two flag bits are
reserved: one for holes and one for confidential memory.

Convert vfio-pci, the iommufd selftest exporter and the KVM sample. iommufd behaves as before: it maps a buffer only when one writable run covers all of it.

---
 drivers/dma-buf/dma-buf.c               |  47 +++++++++++
 drivers/iommu/iommufd/iommufd_private.h |   8 --
 drivers/iommu/iommufd/iommufd_test.h    |  16 ++++
 drivers/iommu/iommufd/pages.c           |  74 ++++-------------
 drivers/iommu/iommufd/selftest.c        | 106 ++++++++++++++++++++----
 drivers/vfio/pci/vfio_pci_dmabuf.c      |  58 ++++++-------
 include/linux/dma-buf.h                 |  54 ++++++++++++
 include/linux/vfio_pci_core.h           |   3 -
 samples/kvm/gmem_provider.c             |  39 ++++-----
 9 files changed, 267 insertions(+), 138 deletions(-)
drivers/dma-buf/dma-buf.c +47 -0
index d504c636dc29..66b85d53ed22 100644
@@ -1389,6 +1389,53 @@ void dma_buf_invalidate_mappings(struct dma_buf *dmabuf)
 }
 EXPORT_SYMBOL_NS_GPL(dma_buf_invalidate_mappings, "DMA_BUF");
 
+/**
+ * dma_buf_get_phys - describe the run that starts at an offset
+ * @attach: attachment to query
+ * @offset: first buffer byte to describe
+ * @len: maximum number of bytes to describe
+ * @phys: physical address and length of the run
+ * @attr: DMA_BUF_PHYS_ATTR_* word of the run
+ *
+ * A run is the longest stretch of backed bytes starting at @offset whose
+ * frames are physically contiguous and share one attribute word. On success
+ * *@phys starts at the byte at @offset and covers at most @len bytes; it may
+ * be shorter than the run.
+ *
+ * The dma-buf reservation must be held. The attachment must be pinned or have
+ * revocable importer operations. A frame remains valid until a covering
+ * invalidation callback returns; the exporter must invalidate a changed range
+ * before reusing its old frames.
+ *
+ * Returns:
+ *
+ * 0 on success, -ENOENT if the byte at @offset is not backed, -ENODEV if the
+ * buffer is revoked, -EOPNOTSUPP if the exporter cannot describe itself this
+ * way, or another negative error code.
+ */
+int dma_buf_get_phys(struct dma_buf_attachment *attach, u64 offset, u64 len,
+                    struct phys_vec *phys, u32 *attr)
+{
+       u64 end;
+       int ret;
+
+       if (WARN_ON_ONCE(!attach || !attach->dmabuf || !phys || !attr))
+               return -EINVAL;
+       if (!len || check_add_overflow(offset, len, &end) ||
+           end > attach->dmabuf->size)
+               return -EINVAL;
+
+       dma_resv_assert_held(attach->dmabuf->resv);
+       if (!attach->dmabuf->ops->get_phys)
+               return -EOPNOTSUPP;
+
+       ret = attach->dmabuf->ops->get_phys(attach, offset, len, phys, attr);
+       if (!ret && WARN_ON_ONCE(!phys->len || phys->len > len))
+               return -EIO;
+       return ret;
+}
+EXPORT_SYMBOL_NS_GPL(dma_buf_get_phys, "DMA_BUF");
+
 /**
  * DOC: cpu access
  *
drivers/iommu/iommufd/iommufd_private.h +0 -8
index 43fbc5bed8de..5cded585c227 100644
@@ -716,8 +716,6 @@ bool iommufd_should_fail(void);
 int __init iommufd_test_init(void);
 void iommufd_test_exit(void);
 bool iommufd_selftest_is_mock_dev(struct device *dev);
-int iommufd_test_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
-                                    struct phys_vec *phys);
 #else
 static inline void iommufd_test_syz_conv_iova_id(struct iommufd_ucmd *ucmd,
                                                 unsigned int ioas_id,
@@ -739,11 +737,5 @@ static inline bool iommufd_selftest_is_mock_dev(struct device *dev)
 {
        return false;
 }
-static inline int
-iommufd_test_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
-                                struct phys_vec *phys)
-{
-       return -EOPNOTSUPP;
-}
 #endif
 #endif
drivers/iommu/iommufd/iommufd_test.h +16 -0
index 52b78cbcc920..28fd9c43edc4 100644
@@ -31,6 +31,8 @@ enum {
        IOMMU_TEST_OP_PASID_CHECK_HWPT,
        IOMMU_TEST_OP_DMABUF_GET,
        IOMMU_TEST_OP_DMABUF_REVOKE,
+       IOMMU_TEST_OP_MD_CHECK_MAPPED,
+       IOMMU_TEST_OP_MD_IOVA_TO_PHYS,
 };
 
 enum {
@@ -193,6 +195,20 @@ struct iommu_test_cmd {
                        __s32 dmabuf_fd;
                        __u32 revoked;
                } dmabuf_revoke;
+               struct {
+                       /*
+                        * 1: every page in [iova, iova+length) must be mapped;
+                        * 0: none of them may be. Mixed is an error.
+                        */
+                       __u32 mapped;
+                       __u32 __reserved;
+                       __aligned_u64 iova;
+                       __aligned_u64 length;
+               } check_mapped;
+               struct {
+                       __aligned_u64 iova;
+                       __aligned_u64 out_phys; /* 0 if unmapped */
+               } iova_to_phys;
        };
        __u32 last;
 };
drivers/iommu/iommufd/pages.c +14 -60
index f9b2ae6d7e96..196d1bb330c2 100644
@@ -1463,68 +1463,12 @@ static const struct dma_buf_attach_ops iopt_dmabuf_attach_revoke_ops = {
        .invalidate_mappings = iopt_revoke_notify,
 };
 
-/*
- * 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, 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) {
-               *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 + memory type.  The provider serves RAM, so mark it CPU_RAM.
-        */
-       {
-               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) {
-                               *is_cpu_ram = true;
-                               return rc;
-                       }
-               }
-       }
-
-       if (!IS_ENABLED(CONFIG_VFIO_PCI_DMABUF))
-               return -EOPNOTSUPP;
-
-       fn = symbol_get(vfio_pci_dma_buf_iommufd_map);
-       if (!fn)
-               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;
-}
-
 static int iopt_map_dmabuf(struct iommufd_ctx *ictx, struct iopt_pages *pages,
                           struct dma_buf *dmabuf)
 {
        struct dma_buf_attachment *attach;
+       struct phys_vec pv;
+       u32 attr;
        int rc;
 
        attach = dma_buf_dynamic_attach(dmabuf, iommufd_global_device(),
@@ -1546,10 +1490,20 @@ 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,
-                                             &pages->dmabuf.is_cpu_ram);
+       /* One backed, writable run covering the buffer: refuse the rest. */
+       rc = dma_buf_get_phys(attach, 0, dmabuf->size, &pv, &attr);
+       if (rc == -ENOENT)
+               rc = -EOPNOTSUPP;
        if (rc)
                goto err_unpin;
+       if (pv.len != dmabuf->size || !dma_buf_phys_attr_known(attr) ||
+           (attr & DMA_BUF_PHYS_ATTR_FLAGS_MASK)) {
+               rc = -EOPNOTSUPP;
+               goto err_unpin;
+       }
+       pages->dmabuf.phys = pv;
+       pages->dmabuf.is_cpu_ram =
+               dma_buf_phys_attr_type(attr) == DMA_BUF_PHYS_ATTR_RAM;
 
        dma_resv_unlock(dmabuf->resv);
 
drivers/iommu/iommufd/selftest.c +90 -16
index af07c642a526..0899272d1e66 100644
@@ -1962,32 +1962,31 @@ static void iommufd_test_dma_buf_release(struct dma_buf *dmabuf)
        kfree(priv);
 }
 
-static const struct dma_buf_ops iommufd_test_dmabuf_ops = {
-       .attach = iommufd_test_dma_buf_attach,
-       .detach = iommufd_test_dma_buf_detach,
-       .map_dma_buf = iommufd_test_dma_buf_map,
-       .release = iommufd_test_dma_buf_release,
-       .unmap_dma_buf = iommufd_test_dma_buf_unmap,
-};
-
-int iommufd_test_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
-                                    struct phys_vec *phys)
+static int iommufd_test_dma_buf_get_phys(struct dma_buf_attachment *attachment,
+                                        u64 offset, u64 len,
+                                        struct phys_vec *phys, u32 *attr)
 {
        struct iommufd_test_dma_buf *priv = attachment->dmabuf->priv;
 
        dma_resv_assert_held(attachment->dmabuf->resv);
-
-       if (attachment->dmabuf->ops != &iommufd_test_dmabuf_ops)
-               return -EOPNOTSUPP;
-
        if (priv->revoked)
                return -ENODEV;
 
-       phys->paddr = virt_to_phys(priv->memory);
-       phys->len = priv->length;
+       phys->paddr = virt_to_phys(priv->memory) + offset;
+       phys->len = len;
+       *attr = DMA_BUF_PHYS_ATTR_MMIO;
        return 0;
 }
 
+static const struct dma_buf_ops iommufd_test_dmabuf_ops = {
+       .attach = iommufd_test_dma_buf_attach,
+       .detach = iommufd_test_dma_buf_detach,
+       .map_dma_buf = iommufd_test_dma_buf_map,
+       .release = iommufd_test_dma_buf_release,
+       .unmap_dma_buf = iommufd_test_dma_buf_unmap,
+       .get_phys = iommufd_test_dma_buf_get_phys,
+};
+
 static int iommufd_test_dmabuf_get(struct iommufd_ucmd *ucmd,
                                   unsigned int open_flags,
                                   size_t len)
@@ -2031,6 +2030,73 @@ static int iommufd_test_dmabuf_get(struct iommufd_ucmd *ucmd,
        return rc;
 }
 
+/*
+ * Report the physical address the mock domain resolves @iova to, or 0 if
+ * it is unmapped.  Lets a test check that two IOVAs share one frame (a
+ * scratch substitution) without knowing the frame in advance.
+ */
+static int iommufd_test_md_iova_to_phys(struct iommufd_ucmd *ucmd,
+                                       unsigned int mockpt_id,
+                                       unsigned long iova)
+{
+       struct iommu_test_cmd *cmd = ucmd->cmd;
+       struct iommufd_hw_pagetable *hwpt;
+       struct mock_iommu_domain *mock;
+       unsigned int page_size;
+       int rc;
+
+       hwpt = get_md_pagetable(ucmd, mockpt_id, &mock);
+       if (IS_ERR(hwpt))
+               return PTR_ERR(hwpt);
+
+       page_size = 1 << __ffs(mock->domain.pgsize_bitmap);
+       if (iova % page_size) {
+               rc = -EINVAL;
+               goto out_put;
+       }
+       cmd->iova_to_phys.out_phys =
+               mock->domain.ops->iova_to_phys(&mock->domain, iova);
+       rc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));
+out_put:
+       iommufd_put_object(ucmd->ictx, &hwpt->obj);
+       return rc;
+}
+
+static int iommufd_test_md_check_mapped(struct iommufd_ucmd *ucmd,
+                                       unsigned int mockpt_id,
+                                       unsigned long iova, size_t length,
+                                       bool mapped)
+{
+       struct iommufd_hw_pagetable *hwpt;
+       struct mock_iommu_domain *mock;
+       unsigned int page_size;
+       int rc = 0;
+
+       hwpt = get_md_pagetable(ucmd, mockpt_id, &mock);
+       if (IS_ERR(hwpt))
+               return PTR_ERR(hwpt);
+
+       page_size = 1 << __ffs(mock->domain.pgsize_bitmap);
+       if (iova % page_size || length % page_size || !length) {
+               rc = -EINVAL;
+               goto out_put;
+       }
+
+       for (; length; length -= page_size, iova += page_size) {
+               bool is_mapped =
+                       mock->domain.ops->iova_to_phys(&mock->domain, iova) != 0;
+
+               if (is_mapped != mapped) {
+                       rc = -ENOENT;
+                       goto out_put;
+               }
+       }
+
+out_put:
+       iommufd_put_object(ucmd->ictx, &hwpt->obj);
+       return rc;
+}
+
 static int iommufd_test_dmabuf_revoke(struct iommufd_ucmd *ucmd, int fd,
                                      bool revoked)
 {
@@ -2143,6 +2209,14 @@ int iommufd_test(struct iommufd_ucmd *ucmd)
                return iommufd_test_dmabuf_revoke(ucmd,
                                                  cmd->dmabuf_revoke.dmabuf_fd,
                                                  cmd->dmabuf_revoke.revoked);
+       case IOMMU_TEST_OP_MD_CHECK_MAPPED:
+               return iommufd_test_md_check_mapped(ucmd, cmd->id,
+                                                   cmd->check_mapped.iova,
+                                                   cmd->check_mapped.length,
+                                                   cmd->check_mapped.mapped);
+       case IOMMU_TEST_OP_MD_IOVA_TO_PHYS:
+               return iommufd_test_md_iova_to_phys(ucmd, cmd->id,
+                                                   cmd->iova_to_phys.iova);
        default:
                return -EOPNOTSUPP;
        }
drivers/vfio/pci/vfio_pci_dmabuf.c +29 -29
index c16f460c01d6..381c3d338e8c 100644
@@ -99,46 +99,46 @@ static void vfio_pci_dma_buf_release(struct dma_buf *dmabuf)
        kfree(priv);
 }
 
-static const struct dma_buf_ops vfio_pci_dmabuf_ops = {
-       .attach = vfio_pci_dma_buf_attach,
-       .map_dma_buf = vfio_pci_dma_buf_map,
-       .unmap_dma_buf = vfio_pci_dma_buf_unmap,
-       .release = vfio_pci_dma_buf_release,
-};
-
 /*
- * This is a temporary "private interconnect" between VFIO DMABUF and iommufd.
- * It allows the two co-operating drivers to exchange the physical address of
- * the BAR. This is to be replaced with a formal DMABUF system for negotiated
- * interconnect types.
+ * Report the BAR's physical range for importers which program it into their own
+ * translation tables, such as iommufd. A BAR is MMIO, never cache-coherent RAM.
  *
- * If this function succeeds the following are true:
- *  - There is one physical range and it is pointing to MMIO
- *  - When move_notify is called it means revoke, not move, vfio_dma_buf_map
- *    will fail if it is currently revoked
+ * When move_notify is called it means revoke, not move, so this fails while
+ * revoked and vfio_dma_buf_map() does the same.
  */
-int vfio_pci_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
-                                struct phys_vec *phys)
+static int vfio_pci_dma_buf_get_phys(struct dma_buf_attachment *attachment,
+                                    u64 offset, u64 len,
+                                    struct phys_vec *phys, u32 *attr)
 {
-       struct vfio_pci_dma_buf *priv;
+       struct vfio_pci_dma_buf *priv = attachment->dmabuf->priv;
+       u32 i;
 
        dma_resv_assert_held(attachment->dmabuf->resv);
-
-       if (attachment->dmabuf->ops != &vfio_pci_dmabuf_ops)
-               return -EOPNOTSUPP;
-
-       priv = attachment->dmabuf->priv;
        if (priv->revoked)
                return -ENODEV;
 
-       /* More than one range to iommufd will require proper DMABUF support */
-       if (priv->nr_ranges != 1)
-               return -EOPNOTSUPP;
-
-       *phys = priv->phys_vec[0];
+       /* Report from @offset to the end of the BAR range containing it. */
+       for (i = 0; i < priv->nr_ranges; i++) {
+               if (offset < priv->phys_vec[i].len)
+                       break;
+               offset -= priv->phys_vec[i].len;
+       }
+       if (i == priv->nr_ranges)
+               return -EINVAL;
+       phys->paddr = priv->phys_vec[i].paddr + offset;
+       phys->len = min_t(u64, priv->phys_vec[i].len - offset, len);
+       *attr = DMA_BUF_PHYS_ATTR_MMIO;
        return 0;
 }
-EXPORT_SYMBOL_FOR_MODULES(vfio_pci_dma_buf_iommufd_map, "iommufd");
+
+static const struct dma_buf_ops vfio_pci_dmabuf_ops = {
+       .attach = vfio_pci_dma_buf_attach,
+       .map_dma_buf = vfio_pci_dma_buf_map,
+       .unmap_dma_buf = vfio_pci_dma_buf_unmap,
+       .release = vfio_pci_dma_buf_release,
+       .get_phys = vfio_pci_dma_buf_get_phys,
+};
+
 
 int vfio_pci_core_fill_phys_vec(struct phys_vec *phys_vec,
                                struct vfio_region_dma_range *dma_ranges,
include/linux/dma-buf.h +54 -0
index d1203da56fc5..b223962e20c2 100644
@@ -13,6 +13,7 @@
 #ifndef __DMA_BUF_H__
 #define __DMA_BUF_H__
 
+#include <linux/bitfield.h>
 #include <linux/iosys-map.h>
 #include <linux/file.h>
 #include <linux/err.h>
@@ -23,6 +24,7 @@
 #include <linux/dma-fence.h>
 #include <linux/wait.h>
 #include <linux/pci-p2pdma.h>
+#include <linux/types.h>
 
 struct device;
 struct dma_buf;
@@ -182,6 +184,29 @@ struct dma_buf_ops {
                              struct sg_table *,
                              enum dma_data_direction);
 
+       /**
+        * @get_phys:
+        *
+        * Describe the run that starts at @offset, for an importer that
+        * programs its own translation tables. A run is the longest stretch
+        * of backed bytes whose frames are physically contiguous and share
+        * one attribute word. Report it in *@phys, starting at the byte at
+        * @offset and clipped at @offset + @len, with its DMA_BUF_PHYS_ATTR_*
+        * word in *@attr. The exporter may stop before the end of the run;
+        * importers must not assume the reported run is maximal.
+        *
+        * Return 0 on success, -ENOENT if the byte at @offset is not backed,
+        * -ENODEV if the buffer is revoked, or another negative error. Do not
+        * wait for memory to become available.
+        *
+        * The dma-buf reservation is held. The attachment must be pinned or
+        * have revocable importer operations. A reported frame remains valid
+        * until a covering invalidation callback returns; an exporter must
+        * invalidate every change before reusing an old frame.
+        */
+       int (*get_phys)(struct dma_buf_attachment *attach, u64 offset, u64 len,
+                       struct phys_vec *phys, u32 *attr);
+
        /* TODO: Add try_map_dma_buf version, to return immed with -EBUSY
         * if the call would block.
         */
@@ -576,6 +601,35 @@ void dma_buf_unmap_attachment(struct dma_buf_attachment *, struct sg_table *,
                                enum dma_data_direction);
 void dma_buf_invalidate_mappings(struct dma_buf *dma_buf);
 bool dma_buf_attach_revocable(struct dma_buf_attachment *attach);
+/* bits 0-7: memory type (a value, not flags) */
+#define DMA_BUF_PHYS_ATTR_TYPE_MASK    GENMASK(7, 0)
+#define DMA_BUF_PHYS_ATTR_RAM          0x00    /* cache-coherent system RAM */
+#define DMA_BUF_PHYS_ATTR_MMIO         0x01    /* device MMIO, uncached */
+/* bits 8-15: reserved for a second value field; must be zero */
+#define DMA_BUF_PHYS_ATTR_RSVD_MASK    GENMASK(15, 8)
+/* bits 16-31: flags; undefined bits must be zero */
+#define DMA_BUF_PHYS_ATTR_READONLY     BIT(16)
+/* BIT(17): reserved (hole, for importers that walk across gaps) */
+/* BIT(18): reserved (private, for confidential computing) */
+#define DMA_BUF_PHYS_ATTR_FLAGS_MASK   (DMA_BUF_PHYS_ATTR_READONLY)
+
+static inline u32 dma_buf_phys_attr_type(u32 attrs)
+{
+       return FIELD_GET(DMA_BUF_PHYS_ATTR_TYPE_MASK, attrs);
+}
+
+static inline bool dma_buf_phys_attr_known(u32 attrs)
+{
+       return dma_buf_phys_attr_type(attrs) <= DMA_BUF_PHYS_ATTR_MMIO &&
+              !(attrs & DMA_BUF_PHYS_ATTR_RSVD_MASK) &&
+              !(attrs & ~(DMA_BUF_PHYS_ATTR_TYPE_MASK |
+                         DMA_BUF_PHYS_ATTR_RSVD_MASK |
+                         DMA_BUF_PHYS_ATTR_FLAGS_MASK));
+}
+
+int dma_buf_get_phys(struct dma_buf_attachment *attach, u64 offset, u64 len,
+                    struct phys_vec *phys, u32 *attr);
+
 int dma_buf_begin_cpu_access(struct dma_buf *dma_buf,
                             enum dma_data_direction dir);
 int dma_buf_end_cpu_access(struct dma_buf *dma_buf,
include/linux/vfio_pci_core.h +0 -3
index 9a1674c152aa..2a1d13abdb0c 100644
@@ -257,7 +257,4 @@ vfio_pci_core_get_iomap(struct vfio_pci_core_device *vdev, unsigned int bar)
        return vdev->barmap[bar];
 }
 
-int vfio_pci_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
-                                struct phys_vec *phys);
-
 #endif /* VFIO_PCI_CORE_H */
samples/kvm/gmem_provider.c +17 -23
index 75197c088762..b6824fe5d228 100644
@@ -487,35 +487,30 @@ static void gmem_dma_buf_release(struct dma_buf *dmabuf)
        kfree(priv);
 }
 
-static const struct dma_buf_ops gmem_dma_buf_ops = {
-       .attach         = gmem_dma_buf_attach,
-       .map_dma_buf    = gmem_dma_buf_map,
-       .unmap_dma_buf  = gmem_dma_buf_unmap,
-       .release        = gmem_dma_buf_release,
-};
-
-/*
- * Private interconnect for iommufd (mirrors vfio_pci_dma_buf_iommufd_map).
- * Returns the single contiguous phys range for the exported region so iommufd
- * can program the IOMMU directly, bypassing the DMA API.
- */
-int gmem_provider_dma_buf_iommufd_map(struct dma_buf_attachment *attach,
-                                     struct phys_vec *phys);
-int gmem_provider_dma_buf_iommufd_map(struct dma_buf_attachment *attach,
-                                     struct phys_vec *phys)
+/* Report this flat sample region through the generic dma-buf operation. */
+static int gmem_dma_buf_get_phys(struct dma_buf_attachment *attach,
+                                u64 offset, u64 len,
+                                struct phys_vec *phys, u32 *attr)
 {
-       struct gmem_dmabuf *priv;
+       struct gmem_dmabuf *priv = attach->dmabuf->priv;
 
        dma_resv_assert_held(attach->dmabuf->resv);
-       if (attach->dmabuf->ops != &gmem_dma_buf_ops)
-               return -EOPNOTSUPP;
-       priv = attach->dmabuf->priv;
        if (priv->revoked)
                return -ENODEV;
-       *phys = priv->phys;
+
+       phys->paddr = priv->phys.paddr + offset;
+       phys->len = len;
+       *attr = DMA_BUF_PHYS_ATTR_RAM;
        return 0;
 }
-EXPORT_SYMBOL_FOR_MODULES(gmem_provider_dma_buf_iommufd_map, "iommufd");
+
+static const struct dma_buf_ops gmem_dma_buf_ops = {
+       .attach         = gmem_dma_buf_attach,
+       .map_dma_buf    = gmem_dma_buf_map,
+       .unmap_dma_buf  = gmem_dma_buf_unmap,
+       .release        = gmem_dma_buf_release,
+       .get_phys       = gmem_dma_buf_get_phys,
+};
 
 /* Called with info->dmabufs_lock held on the revoke path. */
 static void gmem_dma_buf_revoke_all(struct gmem_info *info)
--

2.47.3

#21 lore raw

Re: [RFC PATCH 2/6] dma-buf: Add get_phys() to describe a physical run

Quoted 3 lines · On 10/5/26 Christian König wrote:

Well filling page tables by the importer is an absolutely clear NO-GO for the DMA-buf design, we have gotten down that path already and it took us years to remove this functionality again.

Understood, thanks for the quick and clear answers on this patch and on patch 3.

Quoted 2 lines

The problem you are facing here is that dma_buf_mmap() doesn't work because you don't have a VMA.

Right: the memory has no struct page and is deliberately not mapped in the host, so there is no VMA to hand to KVM.

I'll post a new version of this series. It drops get_phys(), the ranged invalidation and the guest_memfd dma-buf import (patches 2-5), and it does not touch drivers/dma-buf, as you suggested in the PAL discussion:

https://lore.kernel.org/all/[email protected]/

KVM gets its frames through the KVM-private guest_memfd provider interface from David's series. iommufd gets them through a private interface with the exporter, as it already does for vfio-pci. The new version adds a small registry in iommufd for that, which replaces the symbol_get() of the sample in David's series. The dma-buf is then only the handle and the existing revoke.

Thanks,
Fred

maintainer
#22 lore raw

Re: [RFC PATCH 2/6] dma-buf: Add get_phys() to describe a physical run

Quoted 18 lines · Fred Griffoul
Quoted 3 lines · On 10/5/26 Christian König wrote:

Well filling page tables by the importer is an absolutely clear NO-GO for the DMA-buf design, we have gotten down that path already and it took us years to remove this functionality again.

Understood, thanks for the quick and clear answers on this patch and on patch 3.

Quoted 2 lines

The problem you are facing here is that dma_buf_mmap() doesn't work because you don't have a VMA.

Right: the memory has no struct page and is deliberately not mapped in the host, so there is no VMA to hand to KVM.

I'll post a new version of this series. It drops get_phys(), the ranged invalidation and the guest_memfd dma-buf import (patches 2-5), and it does not touch drivers/dma-buf, as you suggested in the PAL discussion:

Quoted 8 lines

https://lore.kernel.org/all/[email protected]/

KVM gets its frames through the KVM-private guest_memfd provider interface from David's series. iommufd gets them through a private interface with the exporter, as it already does for vfio-pci. The new version adds a small registry in iommufd for that, which replaces the symbol_get() of the sample in David's series. The dma-buf is then only the handle and the existing revoke.

Yeah that approach sounds totally sane to me.

We have drivers which stuff all kind of resources, not just memory, into a DMA-buf. That ranges from MMIO BARs to trigger FW operations (doorbells) over full HW blocks (ordered appends, global wave sync etc...) where two or more applications need to share which one is used.

That you then have a exporter private interface is for accessing this is perfectly ok.

The problem you are facing here is more that this is not limited to one driver/module but multiple ones and you don't want module inter dependencies because of the symbols.

So symbol_get() is probably the right thing to do as long as we don't have something like weak symbols or similar.

Regards,
Christian.

Quoted 3 lines

Thanks,
Fred

#23 lore raw

Re: [RFC PATCH 2/6] dma-buf: Add get_phys() to describe a physical run

Quoted 18 lines · Christian König
Quoted 6 lines

KVM gets its frames through the KVM-private guest_memfd provider interface from David's series. iommufd gets them through a private interface with the exporter, as it already does for vfio-pci. The new version adds a small registry in iommufd for that, which replaces the symbol_get() of the sample in David's series. The dma-buf is then only the handle and the existing revoke.

Yeah that approach sounds totally sane to me.

We have drivers which stuff all kind of resources, not just memory, into a DMA-buf. That ranges from MMIO BARs to trigger FW operations (doorbells) over full HW blocks (ordered appends, global wave sync etc...) where two or more applications need to share which one is used.

That you then have a exporter private interface is for accessing this is perfectly ok.

Quoted 6 lines

The problem you are facing here is more that this is not limited to one driver/module but multiple ones and you don't want module inter dependencies because of the symbols.

So symbol_get() is probably the right thing to do as long as we don't have something like weak symbols or similar.

I don't want to keep expanding this hack in iommufd. If dmabuf is to be used then dmabuf needs to provide a pluggable way to fill the iommu_domain that many exporters can plug into. I don't want to hardwire every exporter into iommufd, that makes no sense.

The existing arrangement is to motivate solving this problem generically, not something to be expanded on.

Jason

#24 lore raw

Re: [RFC PATCH 2/6] dma-buf: Add get_phys() to describe a physical run

Quoted 7 lines · Jason Gunthorpe

I don't want to keep expanding this hack in iommufd. If dmabuf is to be used then dmabuf needs to provide a pluggable way to fill the iommu_domain that many exporters can plug into. I don't want to hardwire every exporter into iommufd, that makes no sense.

The existing arrangement is to motivate solving this problem generically, not something to be expanded on.

Agreed. The iommufd registry I mentioned above was never posted, and I have dropped it.

The series I posted since takes another route, without dma-buf:

https://lore.kernel.org/all/[email protected]/

It adds a small interface in mm for drivers that own memory. Such a driver hands out files, and for each page of a file it tells the caller which frame backs it. iommufd maps the file with IOMMU_IOAS_MAP_FILE and builds the iommu_domain itself, and the driver revokes a range when it changes. So iommufd never knows which driver it is talking to, and there is no symbol_get(). guest_memfd uses the same files for the guest. The iommufd part is patch 5:

https://lore.kernel.org/all/[email protected]/

The iommufd part is mainly there to show the interface, and it needs more work. Its revoke unmaps and then remaps, so a device can hit a hole. I would rebuild it on the REPLACE operation David discussed with you at LPC, with the scratch page as a quirk on the IOAS.

Is this the kind of generic interface you had in mind, or would you rather have it hang off dma-buf?

Thanks,
Fred

#25 lore raw

RFC PATCH 3/6 dma-buf: Add ranged mapping invalidation

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

dma_buf_invalidate_mappings() tells every importer that the whole buffer changed. An exporter that changes one part of its memory cannot say which bytes changed, so importers throw away mappings that are still valid.

Add an exporter helper that invalidates a byte range, and an importer callback that receives it. The callback means that the address, the attributes or the backing of the range changed. If part of the range is no longer backed, get_phys() returns -ENOENT for it. Importers must stop using their old answer before the callback returns. Importers that do not implement the callback still receive a whole-buffer invalidation.

---
 drivers/dma-buf/dma-buf.c | 30 ++++++++++++++++++++++++++++++
 include/linux/dma-buf.h   | 16 ++++++++++++++++
 2 files changed, 46 insertions(+)
drivers/dma-buf/dma-buf.c +30 -0
index 66b85d53ed22..e7010163eb2f 100644
@@ -1389,6 +1389,36 @@ void dma_buf_invalidate_mappings(struct dma_buf *dmabuf)
 }
 EXPORT_SYMBOL_NS_GPL(dma_buf_invalidate_mappings, "DMA_BUF");
 
+/**
+ * dma_buf_invalidate_mappings_range - notify attachments that a range changed
+ * @dmabuf: buffer whose layout changed
+ * @offset: first changed byte
+ * @length: number of changed bytes
+ *
+ * Importers with a ranged callback stop using their old mappings of the range
+ * before returning. Other importers receive the existing whole-buffer
+ * callback, which is correct but coarser. The reservation lock must be held.
+ */
+void dma_buf_invalidate_mappings_range(struct dma_buf *dmabuf,
+				       unsigned long offset,
+				       unsigned long length)
+{
+	struct dma_buf_attachment *attach;
+
+	dma_resv_assert_held(dmabuf->resv);
+	list_for_each_entry(attach, &dmabuf->attachments, node) {
+		const struct dma_buf_attach_ops *ops = attach->importer_ops;
+
+		if (!ops)
+			continue;
+		if (ops->invalidate_mappings_range)
+			ops->invalidate_mappings_range(attach, offset, length);
+		else if (ops->invalidate_mappings)
+			ops->invalidate_mappings(attach);
+	}
+}
+EXPORT_SYMBOL_NS_GPL(dma_buf_invalidate_mappings_range, "DMA_BUF");
+
 /**
  * dma_buf_get_phys - describe the run that starts at an offset
  * @attach: attachment to query
include/linux/dma-buf.h +16 -0
index b223962e20c2..55c3fe60a0ba 100644
@@ -485,6 +485,19 @@ struct dma_buf_attach_ops {
 	 * required behavior.
 	 */
 	void (*invalidate_mappings)(struct dma_buf_attachment *attach);
+
+	/**
+	 * @invalidate_mappings_range: [optional] a byte range changed
+	 *
+	 * The exporter changed the address, attributes or backing of
+	 * [@offset, @offset + @length). The importer must stop using its old
+	 * answer for that range before returning.
+	 * Importers without this callback receive @invalidate_mappings for
+	 * the whole buffer instead.
+	 */
+	void (*invalidate_mappings_range)(struct dma_buf_attachment *attach,
+					  unsigned long offset,
+					  unsigned long length);
 };
 
 /**
@@ -600,6 +613,9 @@ struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *,
 void dma_buf_unmap_attachment(struct dma_buf_attachment *, struct sg_table *,
 				enum dma_data_direction);
 void dma_buf_invalidate_mappings(struct dma_buf *dma_buf);
+void dma_buf_invalidate_mappings_range(struct dma_buf *dma_buf,
+				       unsigned long offset,
+				       unsigned long length);
 bool dma_buf_attach_revocable(struct dma_buf_attachment *attach);
 /* bits 0-7: memory type (a value, not flags) */
 #define DMA_BUF_PHYS_ATTR_TYPE_MASK	GENMASK(7, 0)
Signature · 1 line
2.47.3
maintainer
#26 lore raw

Re: [RFC PATCH 3/6] dma-buf: Add ranged mapping invalidation

Quoted 7 lines · Fred Griffoul

From: Fred Griffoul <[email protected]>

dma_buf_invalidate_mappings() tells every importer that the whole buffer changed. An exporter that changes one part of its memory cannot say which bytes changed, so importers throw away mappings that are still valid.

Quoted 6 lines

Add an exporter helper that invalidates a byte range, and an importer callback that receives it. The callback means that the address, the attributes or the backing of the range changed. If part of the range is no longer backed, get_phys() returns -ENOENT for it. Importers must stop using their old answer before the callback returns. Importers that do not implement the callback still receive a whole-buffer invalidation.

Yeah that is exactly one of the reasons why we don't allow that.

Clear NAK to the whole approach. See the reply to patch #2 for a detailed description.

Regards,
Christian.

Quoted 85 lines
---
 drivers/dma-buf/dma-buf.c | 30 ++++++++++++++++++++++++++++++
 include/linux/dma-buf.h   | 16 ++++++++++++++++
 2 files changed, 46 insertions(+)
drivers/dma-buf/dma-buf.c +30 -0
index 66b85d53ed22..e7010163eb2f 100644
@@ -1389,6 +1389,36 @@ void dma_buf_invalidate_mappings(struct dma_buf *dmabuf)
 }
 EXPORT_SYMBOL_NS_GPL(dma_buf_invalidate_mappings, "DMA_BUF");
 
+/**
+ * dma_buf_invalidate_mappings_range - notify attachments that a range changed
+ * @dmabuf: buffer whose layout changed
+ * @offset: first changed byte
+ * @length: number of changed bytes
+ *
+ * Importers with a ranged callback stop using their old mappings of the range
+ * before returning. Other importers receive the existing whole-buffer
+ * callback, which is correct but coarser. The reservation lock must be held.
+ */
+void dma_buf_invalidate_mappings_range(struct dma_buf *dmabuf,
+                                      unsigned long offset,
+                                      unsigned long length)
+{
+       struct dma_buf_attachment *attach;
+
+       dma_resv_assert_held(dmabuf->resv);
+       list_for_each_entry(attach, &dmabuf->attachments, node) {
+               const struct dma_buf_attach_ops *ops = attach->importer_ops;
+
+               if (!ops)
+                       continue;
+               if (ops->invalidate_mappings_range)
+                       ops->invalidate_mappings_range(attach, offset, length);
+               else if (ops->invalidate_mappings)
+                       ops->invalidate_mappings(attach);
+       }
+}
+EXPORT_SYMBOL_NS_GPL(dma_buf_invalidate_mappings_range, "DMA_BUF");
+
 /**
  * dma_buf_get_phys - describe the run that starts at an offset
  * @attach: attachment to query
include/linux/dma-buf.h +16 -1
index b223962e20c2..55c3fe60a0ba 100644
@@ -485,6 +485,19 @@ struct dma_buf_attach_ops {
         * required behavior.
         */
        void (*invalidate_mappings)(struct dma_buf_attachment *attach);
+
+       /**
+        * @invalidate_mappings_range: [optional] a byte range changed
+        *
+        * The exporter changed the address, attributes or backing of
+        * [@offset, @offset + @length). The importer must stop using its old
+        * answer for that range before returning.
+        * Importers without this callback receive @invalidate_mappings for
+        * the whole buffer instead.
+        */
+       void (*invalidate_mappings_range)(struct dma_buf_attachment *attach,
+                                         unsigned long offset,
+                                         unsigned long length);
 };
 
 /**
@@ -600,6 +613,9 @@ struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *,
 void dma_buf_unmap_attachment(struct dma_buf_attachment *, struct sg_table *,
                                enum dma_data_direction);
 void dma_buf_invalidate_mappings(struct dma_buf *dma_buf);
+void dma_buf_invalidate_mappings_range(struct dma_buf *dma_buf,
+                                      unsigned long offset,
+                                      unsigned long length);
 bool dma_buf_attach_revocable(struct dma_buf_attachment *attach);
 /* bits 0-7: memory type (a value, not flags) */
 #define DMA_BUF_PHYS_ATTR_TYPE_MASK    GENMASK(7, 0)
--

2.47.3

#27 lore raw

RFC PATCH 4/6 dma-buf: Allow dynamic attach without a device

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

dma_buf_dynamic_attach() requires a struct device: the device for which the buffer is mapped for DMA. Exporters may also check it before they accept the attachment. An importer that does not perform DMA has no such device. iommufd already attaches with a global placeholder device for this reason. KVM would need one too, although it only needs to know where the memory is so that it can map it into a guest.

Allow @dev to be NULL for a dynamic importer. Such an importer learns where the memory is from get_phys() and builds its own mappings. It must not map the attachment for DMA, and dma_buf_map_attachment() refuses an attachment without a device. An exporter that needs a device to answer can refuse the attachment in its attach op, as it can for any other reason.

---
 drivers/dma-buf/dma-buf.c      | 15 +++++++++++++--
 include/trace/events/dma_buf.h |  2 +-
 2 files changed, 14 insertions(+), 3 deletions(-)
drivers/dma-buf/dma-buf.c +13 -2
index e7010163eb2f..3d43b529a523 100644
@@ -1007,6 +1007,13 @@ dma_buf_pin_on_map(struct dma_buf_attachment *attach)
  * Note that this can fail if the backing storage of @dmabuf is in a place not
  * accessible to @dev, and cannot be moved to a more suitable place. This is
  * indicated with the error code -EBUSY.
+ *
+ * @dev may be NULL for a dynamic importer that is not a DMA master: one that
+ * only asks the exporter where the memory is, through &dma_buf_ops.get_phys,
+ * and builds its own mappings from the answer.  Such an importer must never
+ * call dma_buf_map_attachment(), and an exporter that needs a device to
+ * answer (a peer-to-peer check, say) refuses the attachment in its
+ * &dma_buf_ops.attach.
  */
 struct dma_buf_attachment *
 dma_buf_dynamic_attach(struct dma_buf *dmabuf, struct device *dev,
@@ -1016,7 +1023,7 @@ dma_buf_dynamic_attach(struct dma_buf *dmabuf, struct device *dev,
 	struct dma_buf_attachment *attach;
 	int ret;
 
-	if (WARN_ON(!dmabuf || !dev))
+	if (WARN_ON(!dmabuf || (!dev && !importer_ops)))
 		return ERR_PTR(-EINVAL);
 
 	attach = kzalloc_obj(*attach);
@@ -1175,6 +1182,9 @@ struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *attach,
 
 	if (WARN_ON(!attach || !attach->dmabuf))
 		return ERR_PTR(-EINVAL);
+	/* An importer without a device cannot be a DMA master. */
+	if (WARN_ON(!attach->dev))
+		return ERR_PTR(-EINVAL);
 
 	dma_resv_assert_held(attach->dmabuf->resv);
 
@@ -1847,7 +1857,8 @@ static int dma_buf_debug_show(struct seq_file *s, void *unused)
 		attach_count = 0;
 
 		list_for_each_entry(attach_obj, &buf_obj->attachments, node) {
-			seq_printf(s, "\t%s\n", dev_name(attach_obj->dev));
+			seq_printf(s, "\t%s\n", attach_obj->dev ?
+				   dev_name(attach_obj->dev) : "none");
 			attach_count++;
 		}
 		dma_resv_unlock(buf_obj->resv);
include/trace/events/dma_buf.h +1 -1
index 3bb88d05bcc8..7cabca53b798 100644
@@ -40,7 +40,7 @@ DECLARE_EVENT_CLASS(dma_buf_attach_dev,
 	TP_ARGS(dmabuf, attach, is_dynamic, dev),
 
 	TP_STRUCT__entry(
-		__string(	dev_name,			dev_name(dev))
+		__string(dev_name, dev ? dev_name(dev) : "none")
 		__string(	exp_name,			dmabuf->exp_name)
 		__field(	size_t,				size)
 		__field(	ino_t,				ino)
Signature · 1 line
2.47.3
#28 lore raw

RFC PATCH 5/6 KVM: guest_memfd: Add dma-buf backing

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

A memory owner that exports a dma-buf should be able to use that one object for both guest stage-2 mappings and device IOMMU mappings. A second, KVM-specific backing interface would duplicate the description of the memory layout and the rules for invalidating it.

Add GUEST_MEMFD_FLAG_USE_DMABUF and a dmabuf_fd field to KVM_CREATE_GUEST_MEMFD. This backing has its own kvm_gmem_ops. guest_memfd attaches to the buffer as a revocable importer without a device. At creation, it asks for the run at offset 0 and refuses MMIO or unknown attributes, so a buffer that KVM can never map fails early. Offset 0 may be unbacked.

On a fault, guest_memfd takes the reservation once. It asks get_phys() about the PUD-sized, PMD-sized and page-sized blocks around the faulting page, in that order, and maps the first block that one aligned RAM run covers. If the page is not backed or the run is not supported, the fault returns -EFAULT. A READONLY run is mapped without stage-2 write permission.

The invalidation callback only runs KVM's invalidation over the affected range. It does not allocate memory or call the exporter. A fault that read the layout during the change sees mmu_invalidate_seq move and retries.

Callbacks can start as soon as guest_memfd attaches. A dma-buf-backed file is therefore added to the inode's list of guest_memfd files under filemap_invalidate_lock.

mmap() uses the exporter's dma-buf mmap. fallocate() and populate are not supported. Import the DMA_BUF symbol namespace so that a CONFIG_KVM=m build passes modpost.

---
 include/linux/kvm_host.h       |   1 +
 include/uapi/linux/kvm.h       |   6 +-
 tools/include/uapi/linux/kvm.h |   6 +-
 virt/kvm/Kconfig               |   1 +
 virt/kvm/guest_memfd.c         | 239 +++++++++++++++++++++++++++++++--
 5 files changed, 243 insertions(+), 10 deletions(-)
include/linux/kvm_host.h +1 -0
index f84f3ab44acf..0158dc46580b 100644
@@ -834,6 +834,7 @@ static inline u64 kvm_gmem_get_supported_flags(struct kvm *kvm)
 
 	if (!kvm || kvm_arch_supports_gmem_init_shared(kvm))
 		flags |= GUEST_MEMFD_FLAG_INIT_SHARED;
+	flags |= GUEST_MEMFD_FLAG_USE_DMABUF;
 
 	return flags;
 }
include/uapi/linux/kvm.h +5 -1
index 419011097fa8..f8c83013773d 100644
@@ -1654,11 +1654,15 @@ struct kvm_memory_attributes {
 #define KVM_CREATE_GUEST_MEMFD	_IOWR(KVMIO,  0xd4, struct kvm_create_guest_memfd)
 #define GUEST_MEMFD_FLAG_MMAP		(1ULL << 0)
 #define GUEST_MEMFD_FLAG_INIT_SHARED	(1ULL << 1)
+#define GUEST_MEMFD_FLAG_USE_DMABUF	(1ULL << 2)
 
 struct kvm_create_guest_memfd {
 	__u64 size;
 	__u64 flags;
-	__u64 reserved[6];
+	/* With USE_DMABUF, memory comes from this dma-buf's leading bytes. */
+	__s32 dmabuf_fd;
+	__u32 pad;
+	__u64 reserved[5];
 };
 
 #define KVM_PRE_FAULT_MEMORY	_IOWR(KVMIO, 0xd5, struct kvm_pre_fault_memory)
tools/include/uapi/linux/kvm.h +5 -1
index d0c0c8605976..ebeb2bc353ed 100644
@@ -1644,11 +1644,15 @@ struct kvm_memory_attributes {
 #define KVM_CREATE_GUEST_MEMFD	_IOWR(KVMIO,  0xd4, struct kvm_create_guest_memfd)
 #define GUEST_MEMFD_FLAG_MMAP		(1ULL << 0)
 #define GUEST_MEMFD_FLAG_INIT_SHARED	(1ULL << 1)
+#define GUEST_MEMFD_FLAG_USE_DMABUF	(1ULL << 2)
 
 struct kvm_create_guest_memfd {
 	__u64 size;
 	__u64 flags;
-	__u64 reserved[6];
+	/* With USE_DMABUF, memory comes from this dma-buf's leading bytes. */
+	__s32 dmabuf_fd;
+	__u32 pad;
+	__u64 reserved[5];
 };
 
 #define KVM_PRE_FAULT_MEMORY	_IOWR(KVMIO, 0xd5, struct kvm_pre_fault_memory)
virt/kvm/Kconfig +1 -0
index 794976b88c6f..7ac4c8a371eb 100644
@@ -105,6 +105,7 @@ config KVM_GENERIC_MEMORY_ATTRIBUTES
 
 config KVM_GUEST_MEMFD
        select XARRAY_MULTI
+       select DMA_SHARED_BUFFER
        bool
 
 config HAVE_KVM_ARCH_GMEM_PREPARE
virt/kvm/guest_memfd.c +231 -8

321 lines not on this page · raw message

Signature · 1 line
2.47.3
#29 lore raw

RFC PATCH 6/6 samples/kvm, selftests/kvm: Exercise dma-buf backing

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

Turn the sample into a dma-buf exporter, and move every supported test to dma-buf-backed guest_memfd. Doing both in one commit avoids a state where the sample and the tests use different interfaces.

The sample owns one root region and creates a child descriptor for each VM. It supports moving, donating and reclaiming pages, absent pages, read-only ranges, a scratch page and per-child ioctl allowlists.

The sample's get_phys() reports the run at the requested offset. It uses bitmap searches to find where presence or read-only state changes. An absent page returns -ENOENT. In scratch mode, an absent page of a root child is reported as the read-only scratch page instead. Scratch mode applies only to root children, because a mode change invalidates only them. Every change of ownership sends a ranged invalidation.

Each test passes one dma-buf fd to both guest_memfd and iommufd. New tests cover:

- two VMMs, checking what the guest, the device and the host see;
- SET_PRESENT and SET_READONLY racing with one KVM_CREATE_GUEST_MEMFD, so that lockdep checks attachment setup;
- a 2 MiB-aligned region in which every other page is replaced by the scratch page. The guest reads zeros and its own data, and KVM maps the region with 4 KiB pages. An untouched aligned region still maps at 2 MiB.

The sample sizes the CMA root before children overlap, and publishes each child only after its ownership and allowlist are set. Confidential VMs are out of scope; their test is an explicit skip.

---
 samples/kvm/gmem_provider.c                   | 1287 ++++++++++-------
 samples/kvm/gmem_provider.h                   |  144 +-
 tools/testing/selftests/kvm/Makefile.kvm      |    3 +-
 .../kvm/gmem_provider_nvme_dma_test.c         |   28 +-
 .../testing/selftests/kvm/include/kvm_util.h  |   25 +-
 .../testing/selftests/kvm/x86/gmem_poc_test.c |  824 +++++++++++
 .../kvm/x86/gmem_provider_hugepage_test.c     |   30 +-
 .../kvm/x86/gmem_provider_iommufd_test.c      |   42 +-
 .../kvm/x86/gmem_provider_readonly_test.c     |  172 +++
 .../kvm/x86/gmem_provider_revoke_test.c       |   34 +-
 .../selftests/kvm/x86/gmem_provider_test.c    |  190 +--
 .../kvm/x86/gmem_provider_vfio_test.c         |   45 +-
 12 files changed, 2091 insertions(+), 733 deletions(-)
 create mode 100644 tools/testing/selftests/kvm/x86/gmem_poc_test.c
 create mode 100644 tools/testing/selftests/kvm/x86/gmem_provider_readonly_test.c
samples/kvm/gmem_provider.c +796 -491
index b6824fe5d228..2cde5bcb71ca 100644
@@ -1,43 +1,46 @@
 // SPDX-License-Identifier: GPL-2.0
 /*
- * gmem_provider - sample external guest_memfd provider.
+ * gmem_provider - sample owner of page-less memory, shared as a dma-buf.
  *
- * Demonstrates the KVM guest_memfd provider ABI with two backing modes:
+ * A toy owner of physical memory: one root region carved into children, one
+ * child per VM, ranges that MOVE between children or are DONATEd to the root
+ * and RECLAIMed, a shared scratch frame for revoked pages, and a per-fd
+ * ioctl allowlist fixed by the creator.  The provider owns the frames and is
+ * the single authority for who may map them.
  *
- *  - External (page-less): loaded with addr=/len=, backs guest memory with a
- *    fixed physical range that has no struct page -- e.g. memory carved out of
- *    the kernel with mem= on the command line.  This is the case the provider
- *    ABI exists for; get_pfn() returns bare PFNs KVM treats as non-refcounted.
+ * It is a dma-buf exporter and nothing else.  A child fd hands out a dma-buf
+ * for the child's memory; a VMM gives that dma-buf to KVM_CREATE_GUEST_MEMFD
+ * for the guest and to iommufd for its devices.  An ownership change here is
+ * one ranged invalidation of the child's dma-bufs; every importer drops the
+ * changed view and re-reads the layout. The owner knows nothing of KVM, or which
+ * importer is a guest and which is a device.
  *
- *  - CMA fallback (page-backed): when addr=/len= are not given, allocates a
- *    physically contiguous region via alloc_contig_pages() sized by the setup
- *    ioctl.  Easier to run (no mem= boot param), and still exercises 2M/1G
- *    mappings.  Not preserved across kexec/live update.
- *
- * On SEV-SNP hosts, bind() resets the range's RMP entries to 4K shared so a
- * (new) SNP VM can re-encrypt it, which is what allows re-binding the range to
- * a fresh VM across a live update.
+ * Backing:
+ *  - External (page-less): loaded with addr=/len=, a fixed physical range with
+ *    no struct page, e.g. carved out with memmap= on the command line.
+ *  - CMA fallback: without addr=/len=, alloc_contig_pages() sized by SETUP.
  *
  * Usage:
- *   # page-less external range:
- *   insmod gmem_provider.ko addr=0x5D40000000 len=0x1000000
- *   # or CMA fallback (no params); size comes from the ioctl
- *   insmod gmem_provider.ko
- *   fd = open("/dev/gmem_provider"); ioctl(fd, GMEM_PROVIDER_SETUP, {kvm_fd, size});
- *   pass the returned fd + KVM_MEM_GUEST_MEMFD to KVM_SET_USER_MEMORY_REGION2.
+ *   insmod gmem_provider.ko addr=0x180000000 len=0x42000000
+ *   ctl = open("/dev/gmem_provider");
+ *   child = ioctl(ctl, GMEM_PROVIDER_NEW_CHILD, {offset, len, allow}); # control
+ *   dmabuf = ioctl(child, GMEM_PROVIDER_GET_DMABUF);                     # VMM
+ *   gmem = ioctl(vm, KVM_CREATE_GUEST_MEMFD, {size, USE_DMABUF, dmabuf});
+ *   KVM_SET_USER_MEMORY_REGION2(..., KVM_MEM_GUEST_MEMFD, gmem);
+ *   IOMMU_IOAS_MAP_FILE(ioas, dmabuf, ...);
+ *
+ * The one rule: change ownership state, drop the provider lock, then revoke.
  */
 
 #include <linux/anon_inodes.h>
-#include <linux/bitmap.h>
 #include <linux/dma-buf.h>
-#include <linux/dma-buf-mapping.h>
 #include <linux/dma-resv.h>
+#include <linux/bitmap.h>
 #include <linux/file.h>
 #include <linux/fs.h>
 #include <linux/gfp.h>
 #include <linux/highmem.h>
 #include <linux/io.h>
-#include <linux/kvm_host.h>
 #include <linux/miscdevice.h>
 #include <linux/mm.h>
 #include <linux/module.h>
@@ -50,7 +53,6 @@
 
 #include "gmem_provider.h"
 
-MODULE_IMPORT_NS("DMA_BUF");
 
 static unsigned long long addr;
 module_param(addr, ullong, 0444);
@@ -63,444 +65,294 @@ MODULE_PARM_DESC(len, "size in bytes of the external backing region (optional)")
 
 struct gmem_info {
 	/*
-	 * MUST be first: file->private_data points here.  is_kvm_gmem_file()
-	 * on the KVM side proves the reinterpretation is safe.
-	 */
-	struct kvm_gmem_backing backing;
-
-	/*
-	 * Protects everything below (except the immutable base_pfn/npages/
-	 * cma_pages fields set at setup).  Ordering: info->lock is a leaf;
-	 * do not acquire other locks under it.  KVM's slots_lock is already
-	 * held on the .bind/.unbind paths so info->lock is only needed to
-	 * serialise those against ioctl(SET_PRESENT).
+	 * Protects everything below except the immutable fields set at setup
+	 * and the dma-buf list.  Ordering: gmem_root.lock, then
+	 * info->dmabufs_lock, then a dma-buf reservation.  info->lock is a
+	 * leaf: it is dropped before any invalidation.
 	 */
 	struct mutex lock;
 
-	/* Kept locally: kvm_gmem_ops does not carry a kvm pointer. */
-	struct kvm *kvm;
-
-	/*
-	 * Single active memslot binding.  Used at release time to zap any
-	 * still-active guest mappings before the memory disappears.  NULL
-	 * when no memslot is bound (or the last one has been unbound).
-	 */
-	struct kvm_memory_slot *bound_slot;
 
-	bool mmap_capable;			/* -> KVM_MEMSLOT_GMEM_ONLY at bind */
+	bool mmap_capable;			/* child and dma-buf may be mmap()ed */
 
 	unsigned long base_pfn;
 	unsigned long npages;
-	struct page *cma_pages;			/* non-NULL if CMA-allocated */
-	gfn_t base_gfn;				/* recorded at bind, for revoke */
-	pgoff_t pgoff;				/* provider offset (pages) of the slot */
+	struct page *cma_pages;			/* non-NULL if CMA-allocated (SETUP path only) */
+
+	/*
+	 * Toy descriptor tree.  A child created by NEW_CHILD is a sub-range
+	 * of the root region: @root_index is its first page within the root,
+	 * @owned marks which of its pages are currently granted to it (a page
+	 * MOVEd out or DONATEd is not owned; a page revoked by SET_PRESENT is
+	 * owned but absent).  @allow is the ioctl allowlist.  SETUP-created
+	 * providers have no root and own everything.
+	 */
+	unsigned long root_index;
+	unsigned long *owned;			/* NULL for SETUP-created providers */
+	u32 allow;
+	struct list_head root_link;		/* gmem_root.children */
 	unsigned long *absent;			/* bitmap of currently-revoked pages */
-	struct list_head dmabufs;		/* struct gmem_dmabuf entries */
-	struct mutex dmabufs_lock;
+	unsigned long *readonly;		/* bitmap of pages the guest may not write */
+	struct address_space *mapping;		/* our file's: host windows live here */
+	struct list_head dmabufs;		/* exported dma-bufs (struct gmem_dmabuf) */
+	struct mutex dmabufs_lock;		/* protects @dmabufs */
 };
 
 static struct gmem_info *to_gmem_info(struct file *file)
 {
-	return container_of(file->private_data, struct gmem_info, backing);
+	return file->private_data;
 }
 
-/* Map a backing PFN for CPU access: page-backed via kmap, page-less via memremap. */
-static void *gmem_map_pfn(kvm_pfn_t pfn)
-{
-	if (pfn_valid(pfn))
-		return kmap_local_pfn(pfn);
-	return memremap(PFN_PHYS(pfn), PAGE_SIZE, MEMREMAP_WB);
-}
+/*
+ * The root of the toy descriptor tree: one backing region owned by the
+ * control device.  Children carve sub-ranges out of it.  All ownership
+ * transitions (NEW_CHILD, MOVE, DONATE, RECLAIM) run under root.lock, which
+ * is taken before any child's info->lock.
+ */
+static struct gmem_root {
+	struct mutex lock;			/* protects the fields below */
+	unsigned long base_pfn;
+	unsigned long npages;
+	struct page *cma_pages;
+	unsigned long *owned;			/* pages some child currently owns */
+	unsigned long *donated;			/* pages parked at the root */
+	struct list_head children;
+	bool scratch_enabled;
+} gmem_root;
 
-static void gmem_unmap_pfn(kvm_pfn_t pfn, void *vaddr)
-{
-	if (!vaddr)
-		return;
-	if (pfn_valid(pfn))
-		kunmap_local(vaddr);
-	else
-		memunmap(vaddr);
-}
+/*
+ * One zeroed scratch frame for the whole module.  When scratch mode is on,
+ * a revoked page of a root child reports this frame read-only to every
+ * importer, so a device that cannot tolerate an IOMMU fault lands here.
+ */
+static struct page *gmem_scratch_page;
 
-/* Largest order KVM may map at @gfn, snapped to 4K/2M/1G. */
-static int gmem_max_order(struct gmem_info *info, gfn_t gfn, unsigned long index)
+static inline unsigned long gmem_scratch_pfn(void)
 {
-	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;
-	unsigned long absent_next;
-
-	/*
-	 * A hugepage may not span any revoked page.  Clamp by the distance to
-	 * the next absent bit; scanning is cheap because @absent is a plain
-	 * bitmap and the caller already checked test_bit(index).
-	 */
-	if (info->absent) {
-		absent_next = find_next_bit(info->absent, info->npages,
-					    index + 1);
-		remaining = min(remaining, absent_next - index);
-	}
-
-	if (IS_ALIGNED(pfn, 1UL << pud_order) &&
-	    IS_ALIGNED(gfn, 1UL << pud_order) &&
-	    remaining >= (1UL << pud_order))
-		return pud_order;
-
-	if (IS_ALIGNED(pfn, 1UL << pmd_order) &&
-	    IS_ALIGNED(gfn, 1UL << pmd_order) &&
-	    remaining >= (1UL << pmd_order))
-		return pmd_order;
-
-	return 0;
+	return page_to_pfn(gmem_scratch_page);
 }
 
-static int gmem_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,
-			bool *writable)
+/*
+ * Is page @index of @info currently reachable by the guest and devices?
+ * Callable with or without info->lock: every change to the bitmaps is
+ * followed by an invalidation of the range, so a lock-free answer is either
+ * current or about to be superseded.
+ */
+static inline bool gmem_page_present(struct gmem_info *info, unsigned long index)
 {
-	struct gmem_info *info = to_gmem_info(file);
-	pgoff_t index = gfn - slot->base_gfn + slot->gmem.pgoff;
-
-	if (index >= info->npages)
-		return -EINVAL;
-
-	/* Revoked (absent) page: behave like not-present so the fault fails. */
+	if (info->owned && !test_bit(index, info->owned))
+		return false;
 	if (info->absent && test_bit(index, info->absent))
-		return -EFAULT;
-
-	*pfn = info->base_pfn + index;
-	if (max_order)
-		*max_order = gmem_max_order(info, gfn, index);
-	return 0;
+		return false;
+	return true;
 }
 
-static int gmem_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)
-{
-	struct gmem_info *info = to_gmem_info(file);
-	pgoff_t index = gfn - slot->base_gfn + slot->gmem.pgoff;
-
-	if (index >= info->npages)
-		return -EINVAL;
-
-	*pfn = info->base_pfn + index;
+static void gmem_release(struct file *file);
+static int gmem_mmap(struct file *file, struct vm_area_struct *vma);
+static long gmem_fd_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
 
-	if (src_page) {
-		void *dst, *src;
 
-		/* Map dst first: memremap() may sleep, kmap_local_page() must not. */
-		dst = gmem_map_pfn(*pfn);
-		if (!dst)
-			return -ENOMEM;
-		src = kmap_local_page(src_page);
-		memcpy(dst, src, PAGE_SIZE);
-		kunmap_local(src);
-		gmem_unmap_pfn(*pfn, dst);
-	}
-	return 0;
-}
-
-static int gmem_bind(struct file *file, struct kvm *kvm,
-		     struct kvm_memory_slot *slot, loff_t offset)
+static void gmem_release(struct file *file)
 {
 	struct gmem_info *info = to_gmem_info(file);
-	struct kvm *old_kvm = NULL;
-	unsigned long start = offset >> PAGE_SHIFT;
-
-	if (offset < 0 || !PAGE_ALIGNED(offset) ||
-	    start + slot->npages > info->npages)
-		return -EINVAL;
 
 	/*
-	 * An mmap-capable backing hands the VMM a host mapping onto pages
-	 * that a hardware-encrypted VM (SEV, SEV-ES, SEV-SNP, TDX) will mark
-	 * private in the RMP/EPT; the mmap can only ever fault on those
-	 * pages.  Refuse rather than hand the VMM a useless (and misleading)
-	 * shared view.  SW_PROTECTED_VM has no hardware encryption and is
-	 * fine.
+	 * Every exported dma-buf holds a reference on this file, so none can
+	 * be alive here: no device and no guest_memfd still maps our frames.
 	 */
-#ifdef CONFIG_X86
-	if (info->mmap_capable &&
-	    (kvm->arch.vm_type == KVM_X86_SEV_VM ||
-	     kvm->arch.vm_type == KVM_X86_SEV_ES_VM ||
-	     kvm->arch.vm_type == KVM_X86_SNP_VM ||
-	     kvm->arch.vm_type == KVM_X86_TDX_VM))
-		return -EACCES;
-#endif
+	WARN_ON(!list_empty(&info->dmabufs));
 
-	/* Record the binding so the revoke ioctl can translate offset -> gfn. */
-	mutex_lock(&info->lock);
-	info->base_gfn = slot->base_gfn;
-	info->pgoff = start;
-	info->bound_slot = slot;
-	mutex_unlock(&info->lock);
-
-#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.
+	 * A child returns its carved range to the root.  Pages it still owned
+	 * become free again; pages it had DONATEd stay parked at the root
+	 * (still in gmem_root.donated) until RECLAIM or module exit; pages
+	 * MOVEd out belong to another child and are not ours to free.
 	 */
-	{
+	if (info->owned) {
 		unsigned long i;
-		unsigned long first_pmd_pfn = ALIGN(info->base_pfn + start,
-						    PTRS_PER_PMD);
-
-		for (i = first_pmd_pfn - (info->base_pfn + start);
-		     i + PTRS_PER_PMD <= slot->npages;
-		     i += PTRS_PER_PMD)
-			psmash(info->base_pfn + start + i);
 
-		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);
-		}
+		mutex_lock(&gmem_root.lock);
+		list_del(&info->root_link);
+		for_each_set_bit(i, info->owned, info->npages)
+			__clear_bit(info->root_index + i, gmem_root.owned);
+		mutex_unlock(&gmem_root.lock);
+		kvfree(info->owned);
 	}
-#endif
-
-	/*
-	 * Claim (or, on re-bind, transfer) VM ownership; pins the VM.
-	 * kvm_put_kvm(old_kvm) MUST run outside info->lock: if the put
-	 * drops the last ref, kvm_destroy_vm() runs inline and calls back
-	 * into our gmem_unbind() (via kvm_gmem_unbind() on each memslot),
-	 * which needs info->lock -- taking it here would self-deadlock.
-	 */
-	mutex_lock(&info->lock);
-	if (info->kvm != kvm) {
-		old_kvm = info->kvm;
-		kvm_get_kvm(kvm);
-		info->kvm = kvm;
-	}
-	mutex_unlock(&info->lock);
-	if (old_kvm)
-		kvm_put_kvm(old_kvm);
-
-	/*
-	 * Record the file on the slot (KVM's outer bind no longer does this
-	 * for us) and mark the slot gmem-only if this backing serves host
-	 * accesses through its own mmap.
-	 */
-	WRITE_ONCE(slot->gmem.file, file);
-	slot->gmem.pgoff = start;
-	if (info->mmap_capable)
-		slot->flags |= KVM_MEMSLOT_GMEM_ONLY;
-
-	return 0;
+	if (info->cma_pages)
+		free_contig_range(info->base_pfn, info->npages);
+	kvfree(info->absent);
+	kvfree(info->readonly);
+	kfree(info);
+	module_put(THIS_MODULE);
 }
 
-static void gmem_unbind(struct file *file, struct kvm *kvm,
-			struct kvm_memory_slot *slot)
+static vm_fault_t gmem_vm_fault(struct vm_fault *vmf)
 {
-	struct gmem_info *info = to_gmem_info(file);
-
-	mutex_lock(&info->lock);
-	if (info->bound_slot == slot)
-		info->bound_slot = NULL;
-	mutex_unlock(&info->lock);
-
-#if IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT)
-	{
-		unsigned long start = slot->gmem.pgoff;
-		unsigned long first_pmd_pfn = ALIGN(info->base_pfn + start,
-						    PTRS_PER_PMD);
-		unsigned long i;
-
-		/*
-		 * Symmetric with gmem_bind(): PSMASH any 2M RMP entries first
-		 * so rmp_make_shared(PG_LEVEL_4K) can succeed on SNP hosts.
-		 * Harmless on non-SNP: psmash() returns -ENODEV.
-		 */
-		for (i = first_pmd_pfn - (info->base_pfn + start);
-		     i + PTRS_PER_PMD <= slot->npages;
-		     i += PTRS_PER_PMD)
-			psmash(info->base_pfn + start + i);
+	/* The VMA's file is ours or a dma-buf's; the child rides in vm_private_data. */
+	struct gmem_info *info = vmf->vma->vm_private_data;
+	unsigned long index = vmf->pgoff;
 
-		for (i = 0; i < slot->npages; i++) {
-			unsigned long pfn = info->base_pfn + start + i;
-
-			rmp_make_shared(pfn, PG_LEVEL_4K);
-		}
-	}
-#endif
+	if (index >= info->npages || !gmem_page_present(info, index))
+		return VM_FAULT_SIGBUS;
+	return vmf_insert_pfn(vmf->vma, vmf->address, info->base_pfn + index);
 }
 
-static void gmem_release(struct file *file);
-static int gmem_mmap(struct file *file, struct vm_area_struct *vma);
-static long gmem_fd_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
-
-static const struct kvm_gmem_ops gmem_ops = {
-	.bind		= gmem_bind,
-	.unbind		= gmem_unbind,
-	.get_pfn	= gmem_get_pfn,
-	.populate	= gmem_populate,
-	.release	= gmem_release,
-	.mmap		= gmem_mmap,
-	.ioctl		= gmem_fd_ioctl,
+static const struct vm_operations_struct gmem_vm_ops = {
+	.fault = gmem_vm_fault,
 };
 
-static void gmem_release(struct file *file)
-{
-	struct gmem_info *info = to_gmem_info(file);
-	struct kvm_memory_slot *slot;
-
-	/*
-	 * If a memslot is still bound at close time, KVM has not yet had a
-	 * chance to call ops->unbind.  Zap the guest mappings for the range
-	 * and clear slot->gmem.file so the eventual unbind is a no-op.  This
-	 * matches native gmem's kvm_gmem_release() and prevents the guest
-	 * from continuing to hit backing memory after we free it below.
-	 */
-	mutex_lock(&info->lock);
-	slot = info->bound_slot;
-	if (slot && info->kvm) {
-		kvm_gmem_invalidate_range(info->kvm, slot->base_gfn,
-					  slot->base_gfn + slot->npages);
-		WRITE_ONCE(slot->gmem.file, NULL);
-		info->bound_slot = NULL;
-	}
-	mutex_unlock(&info->lock);
-
-	if (info->kvm)
-		kvm_put_kvm(info->kvm);
-	if (info->cma_pages)
-		free_contig_range(info->base_pfn, info->npages);
-	kvfree(info->absent);
-	kfree(info);
-	module_put(THIS_MODULE);
-}
-
 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);
 
-	/*
-	 * gmem_bind() refuses to bind an mmap-capable fd to a coco VM.  A fd
-	 * that was created without GMEM_PROVIDER_FLAG_MMAP_CAPABLE has no
-	 * such gate at bind time, so its mmap must not succeed at any point.
-	 */
+	/* A fd created without GMEM_PROVIDER_FLAG_MMAP_CAPABLE is never host-mappable. */
 	if (!info->mmap_capable)
 		return -EPERM;
 
 	if (vma->vm_pgoff + npages > info->npages)
 		return -EINVAL;
 
-	/* Page-less backing: map raw PFNs, not folios. */
+	/*
+	 * Page-less backing: raw PFNs, inserted on fault, never at mmap()
+	 * time, so that a window torn down on a revoke comes back by itself
+	 * once the page is the child's again.
+	 */
 	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);
+	vma->vm_private_data = info;
+	vma->vm_ops = &gmem_vm_ops;
+	return 0;
 }
 
 /*
- * Dynamic dma-buf exporter over the provider's backing.
- *
- * Follows the same shape as drivers/vfio/pci/vfio_pci_dmabuf.c: a per-dmabuf
- * priv holding a phys_vec, a revocable dynamic attach, and a "private
- * interconnect" symbol iommufd looks up to fetch phys directly (instead of
- * mapping through the DMA API).
+ * The dma-buf a child exports.
  *
- * A revoke on the provider (SET_PRESENT present=0) fans out to every exported
- * dma-buf via dma_buf_invalidate_mappings(), so iommufd (which registered a
- * revocable importer) tears down the IOMMU mapping alongside KVM's NPT zap.
+ * A child may hand out several dma-bufs over its life (one per holder of the
+ * fd who asks); each covers the whole child and pins this file until it is
+ * released. Importers must accept ranged invalidation: every change to the
+ * child's pages is sent to them, and they re-read get_phys().
  */
 struct gmem_dmabuf {
 	struct dma_buf *dmabuf;
 	struct gmem_info *info;
 	struct file *provider_file;		/* holds info alive */
 	struct list_head list;			/* info->dmabufs */
-	struct phys_vec phys;			/* single contiguous range */
-	struct kref kref;
-	struct completion comp;
-	bool revoked;
 };
 
 static int gmem_dma_buf_attach(struct dma_buf *dmabuf,
 			       struct dma_buf_attachment *attach)
 {
-	struct gmem_dmabuf *priv = dmabuf->priv;
-
-	if (!attach->peer2peer)
-		return -EOPNOTSUPP;
-	if (priv->revoked)
-		return -ENODEV;
-	if (!dma_buf_attach_revocable(attach))
+	/* Only importers that can be told to re-read may attach. */
+	if (!attach->peer2peer || !dma_buf_attach_revocable(attach))
 		return -EOPNOTSUPP;
 	return 0;
 }
 
-static void gmem_dma_buf_done(struct kref *kref)
-{
-	struct gmem_dmabuf *priv = container_of(kref, struct gmem_dmabuf, kref);
-
-	complete(&priv->comp);
-}
-
 static struct sg_table *gmem_dma_buf_map(struct dma_buf_attachment *attach,
 					 enum dma_data_direction dir)
 {
-	struct gmem_dmabuf *priv = attach->dmabuf->priv;
-	struct sg_table *sgt;
-
-	dma_resv_assert_held(priv->dmabuf->resv);
-	if (priv->revoked)
-		return ERR_PTR(-ENODEV);
-
-	/* RAM, not P2P MMIO: no p2pdma_provider. */
-	sgt = dma_buf_phys_vec_to_sgt(attach, NULL, &priv->phys, 1,
-				      priv->phys.len, dir);
-	if (IS_ERR(sgt))
-		return sgt;
-
-	kref_get(&priv->kref);
-	return sgt;
+	/* DMA-API importers are not served; use get_phys() (iommufd does). */
+	return ERR_PTR(-EOPNOTSUPP);
 }
 
 static void gmem_dma_buf_unmap(struct dma_buf_attachment *attach,
-			       struct sg_table *sgt,
-			       enum dma_data_direction dir)
+			       struct sg_table *sgt, enum dma_data_direction dir)
 {
-	struct gmem_dmabuf *priv = attach->dmabuf->priv;
+}
+
+/* A host window through the dma-buf: the same rules as a window on the child. */
+static int gmem_dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma)
+{
+	struct gmem_dmabuf *priv = dmabuf->priv;
 
-	dma_resv_assert_held(priv->dmabuf->resv);
-	dma_buf_free_sgt(attach, sgt, dir);
-	kref_put(&priv->kref, gmem_dma_buf_done);
+	return gmem_mmap(priv->provider_file, vma);
 }
 
 static void gmem_dma_buf_release(struct dma_buf *dmabuf)
 {
 	struct gmem_dmabuf *priv = dmabuf->priv;
+	struct gmem_info *info = priv->info;
 
-	if (priv->info) {
-		mutex_lock(&priv->info->dmabufs_lock);
-		list_del_init(&priv->list);
-		mutex_unlock(&priv->info->dmabufs_lock);
-	}
-	if (priv->provider_file)
-		fput(priv->provider_file);
+	mutex_lock(&info->dmabufs_lock);
+	list_del(&priv->list);
+	mutex_unlock(&info->dmabufs_lock);
+	fput(priv->provider_file);
 	kfree(priv);
 }
 
-/* Report this flat sample region through the generic dma-buf operation. */
+/* Return the first bit whose value differs from @index. */
+static unsigned long gmem_bitmap_next_change(const unsigned long *bitmap,
+					     unsigned long nbits,
+					     unsigned long index)
+{
+	if (!bitmap)
+		return nbits;
+	if (test_bit(index, bitmap))
+		return find_next_zero_bit(bitmap, nbits, index + 1);
+	return find_next_bit(bitmap, nbits, index + 1);
+}
+
+/* Find a run with one present/read-only disposition, without a per-bit scan. */
+static unsigned long gmem_disposition_end(struct gmem_info *info,
+					  unsigned long index)
+{
+	bool present = gmem_page_present(info, index);
+	bool readonly = info->readonly && test_bit(index, info->readonly);
+	unsigned long pos = index;
+
+	for (;;) {
+		unsigned long next = info->npages;
+
+		next = min(next, gmem_bitmap_next_change(info->owned,
+						   info->npages, pos));
+		next = min(next, gmem_bitmap_next_change(info->absent,
+						   info->npages, pos));
+		next = min(next, gmem_bitmap_next_change(info->readonly,
+						   info->npages, pos));
+		if (next >= info->npages ||
+		    gmem_page_present(info, next) != present ||
+		    (!!(info->readonly && test_bit(next, info->readonly))) != readonly)
+			return next;
+		pos = next;
+	}
+}
+
+/*
+ * Describe the run at @offset from the child's ownership bitmaps. A present
+ * page extends to the next page whose presence or read-only state differs,
+ * found with bitmap searches. An absent page is not backed, unless scratch
+ * mode substitutes the shared read-only scratch frame for that one page.
+ * Scratch mode covers only children of the root: SET_SCRATCH invalidates
+ * those, so a SETUP provider must never report the scratch frame.
+ */
 static int gmem_dma_buf_get_phys(struct dma_buf_attachment *attach,
 				 u64 offset, u64 len,
 				 struct phys_vec *phys, u32 *attr)
 {
 	struct gmem_dmabuf *priv = attach->dmabuf->priv;
+	struct gmem_info *info = priv->info;
+	unsigned long index = offset >> PAGE_SHIFT;
+	unsigned long end, run_end;
 
-	dma_resv_assert_held(attach->dmabuf->resv);
-	if (priv->revoked)
-		return -ENODEV;
+	if (!PAGE_ALIGNED(offset) || !PAGE_ALIGNED(len))
+		return -EINVAL;
+	end = (offset + len) >> PAGE_SHIFT;
+
+	if (!gmem_page_present(info, index)) {
+		if (!info->owned || !READ_ONCE(gmem_root.scratch_enabled))
+			return -ENOENT;
+		phys->paddr = PFN_PHYS(gmem_scratch_pfn());
+		phys->len = PAGE_SIZE;
+		*attr = DMA_BUF_PHYS_ATTR_RAM | DMA_BUF_PHYS_ATTR_READONLY;
+		return 0;
+	}
 
-	phys->paddr = priv->phys.paddr + offset;
-	phys->len = len;
+	run_end = min(gmem_disposition_end(info, index), end);
+	phys->paddr = PFN_PHYS(info->base_pfn + index);
+	phys->len = (u64)(run_end - index) << PAGE_SHIFT;
 	*attr = DMA_BUF_PHYS_ATTR_RAM;
+	if (info->readonly && test_bit(index, info->readonly))
+		*attr |= DMA_BUF_PHYS_ATTR_READONLY;
 	return 0;
 }
 
@@ -510,23 +362,9 @@ static const struct dma_buf_ops gmem_dma_buf_ops = {
 	.unmap_dma_buf	= gmem_dma_buf_unmap,
 	.release	= gmem_dma_buf_release,
 	.get_phys	= gmem_dma_buf_get_phys,
+	.mmap		= gmem_dma_buf_mmap,
 };
 
-/* 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;
-
-	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);
-	}
-}
-
 static int gmem_provider_get_dmabuf(struct file *file)
 {
 	struct gmem_info *info = to_gmem_info(file);
@@ -537,27 +375,19 @@ static int gmem_provider_get_dmabuf(struct file *file)
 	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;
-	exp_info.size = priv->phys.len;
+	exp_info.size = (u64)info->npages << PAGE_SHIFT;
 	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);
+		fput(priv->provider_file);
 		kfree(priv);
 		return fd;
 	}
-
 	mutex_lock(&info->dmabufs_lock);
 	list_add(&priv->list, &info->dmabufs);
 	mutex_unlock(&info->dmabufs_lock);
@@ -568,14 +398,132 @@ static int gmem_provider_get_dmabuf(struct file *file)
 	return fd;
 }
 
+/*
+ * Tell every importer of @info that [start, end) changed.  The caller has
+ * already updated the bitmaps and dropped info->lock: an importer re-reads
+ * get_phys() from inside this.
+ */
+static void gmem_revoke_range(struct gmem_info *info,
+			      unsigned long start, unsigned long end)
+{
+	struct gmem_dmabuf *priv;
+
+	lockdep_assert_not_held(&info->lock);
+	mutex_lock(&info->dmabufs_lock);
+	list_for_each_entry(priv, &info->dmabufs, list) {
+		dma_resv_lock(priv->dmabuf->resv, NULL);
+		dma_buf_invalidate_mappings_range(priv->dmabuf,
+						  (u64)start << PAGE_SHIFT,
+						  (u64)(end - start) << PAGE_SHIFT);
+		dma_resv_unlock(priv->dmabuf->resv);
+	}
+	mutex_unlock(&info->dmabufs_lock);
+}
+
+/*
+ * The child lost the frames behind [start, end): host windows over them go
+ * too.  Not for a read-only flip or a scratch toggle, where the VMM may be
+ * the page's writer; the VMM re-maps after a grant.
+ */
+static void gmem_unmap_host(struct gmem_info *info, unsigned long start,
+			    unsigned long end)
+{
+	loff_t off = (loff_t)start << PAGE_SHIFT, len = (loff_t)(end - start) << PAGE_SHIFT;
+	struct gmem_dmabuf *priv;
+
+	if (end <= start)
+		return;
+	unmap_mapping_range(info->mapping, off, len, 1);
+	/* Windows through a dma-buf live on the dma-buf's own file. */
+	mutex_lock(&info->dmabufs_lock);
+	list_for_each_entry(priv, &info->dmabufs, list)
+		unmap_mapping_range(priv->dmabuf->file->f_mapping, off, len, 1);
+	mutex_unlock(&info->dmabufs_lock);
+}
+
+/* Which allowlist bit gates each child-fd ioctl.  0 = not gated. */
+static u32 gmem_ioctl_allow_bit(unsigned int cmd)
+{
+	switch (cmd) {
+	case GMEM_PROVIDER_SET_PRESENT:	return GMEM_ALLOW_SET_PRESENT;
+	case GMEM_PROVIDER_SET_READONLY: return GMEM_ALLOW_SET_READONLY;
+	case GMEM_PROVIDER_GET_DMABUF:	return GMEM_ALLOW_GET_DMABUF;
+	case GMEM_PROVIDER_GET_STATS:	return GMEM_ALLOW_GET_STATS;
+	default:			return 0;
+	}
+}
+
+static long gmem_get_stats(struct gmem_info *info, void __user *uarg)
+{
+	struct gmem_provider_stats st = {};
+
+	mutex_lock(&info->lock);
+	st.region_offset = (u64)info->root_index << PAGE_SHIFT;
+	st.region_len = (u64)info->npages << PAGE_SHIFT;
+	st.owned_pages = info->owned ?
+		bitmap_weight(info->owned, info->npages) : info->npages;
+	st.absent_pages = info->absent ?
+		bitmap_weight(info->absent, info->npages) : 0;
+	st.readonly_pages = info->readonly ?
+		bitmap_weight(info->readonly, info->npages) : 0;
+	st.allow = info->allow;
+	mutex_unlock(&info->lock);
+
+	return copy_to_user(uarg, &st, sizeof(st)) ? -EFAULT : 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;
+	u32 need = gmem_ioctl_allow_bit(cmd);
+
+	/*
+	 * The allowlist is fixed by the creator at NEW_CHILD and checked here
+	 * before dispatch, so it also governs ioctls added later.  A SETUP
+	 * provider has no root and allows everything, as before.
+	 */
+	if (need && !(info->allow & need))
+		return -EPERM;
 
 	if (cmd == GMEM_PROVIDER_GET_DMABUF)
 		return gmem_provider_get_dmabuf(file);
+	if (cmd == GMEM_PROVIDER_GET_STATS)
+		return gmem_get_stats(info, (void __user *)arg);
+
+	if (cmd == GMEM_PROVIDER_SET_READONLY) {
+		struct gmem_provider_readonly r;
+
+		if (copy_from_user(&r, (void __user *)arg, sizeof(r)))
+			return -EFAULT;
+		if (!r.len || !PAGE_ALIGNED(r.offset) || !PAGE_ALIGNED(r.len) ||
+		    r.pad)
+			return -EINVAL;
+		start_index = r.offset >> PAGE_SHIFT;
+		end_index = start_index + (r.len >> PAGE_SHIFT);
+		if (end_index > info->npages || end_index < start_index)
+			return -EINVAL;
+
+		/*
+		 * Flip the bits, then invalidate the range so importers drop
+		 * their mappings and the next access re-reads get_phys() with
+		 * the new permission.  Making a range read-only must
+		 * tear down writable mappings; making it writable again is
+		 * also invalidated so a stale read-only mapping does not keep
+		 * exiting.
+		 */
+		mutex_lock(&info->lock);
+		if (r.readonly)
+			bitmap_set(info->readonly, start_index,
+				   end_index - start_index);
+		else
+			bitmap_clear(info->readonly, start_index,
+				     end_index - start_index);
+		mutex_unlock(&info->lock);
+		gmem_revoke_range(info, start_index, end_index);
+		return 0;
+	}
 
 	if (cmd != GMEM_PROVIDER_SET_PRESENT)
 		return -ENOTTY;
@@ -589,152 +537,495 @@ static long gmem_fd_ioctl(struct file *file, unsigned int cmd, unsigned long arg
 	if (end_index > info->npages || end_index < start_index)
 		return -EINVAL;
 
-	if (p.present) {
-		/* Restore: next guest fault calls get_pfn() and re-maps. */
-		mutex_lock(&info->lock);
+	mutex_lock(&info->lock);
+	if (p.present)
 		bitmap_clear(info->absent, start_index, end_index - start_index);
-		mutex_unlock(&info->lock);
-	} else {
-		unsigned long clamped_start;
-
-		/* Revoke: mark absent, then zap the guest NPT/EPT for the range. */
-		mutex_lock(&info->lock);
+	else
 		bitmap_set(info->absent, start_index, end_index - start_index);
+	/*
+	 * Both directions invalidate: on revoke so the guest and devices stop
+	 * using the pages, on restore so importers that were shown a hole or
+	 * the scratch frame re-read and map the real frames again.
+	 */
+	mutex_unlock(&info->lock);
+	gmem_revoke_range(info, start_index, end_index);
+	if (!p.present)
+		gmem_unmap_host(info, start_index, end_index);
+	return 0;
+}
 
-		/*
-		 * Translate provider offset -> guest gfn.  Skip any part of
-		 * the range that falls outside the currently bound slot; a
-		 * naive subtraction would underflow.
-		 */
-		clamped_start = max_t(unsigned long, start_index, info->pgoff);
-		if (info->kvm && end_index > clamped_start)
-			kvm_gmem_invalidate_range(info->kvm,
-				info->base_gfn + clamped_start - info->pgoff,
-				info->base_gfn + end_index - info->pgoff);
-		mutex_unlock(&info->lock);
-
-		/*
-		 * Fan out to iommufd (and any other dma-buf importer): mark the
-		 * exported dma-buf(s) revoked and invalidate any active mappings.
-		 * The provider stays ignorant of scratch-page policy; that lives
-		 * in the importer.
-		 */
-		mutex_lock(&info->dmabufs_lock);
-		gmem_dma_buf_revoke_all(info);
-		mutex_unlock(&info->dmabufs_lock);
-	}
+static int gmem_fops_release(struct inode *inode, struct file *file)
+{
+	gmem_release(file);
 	return 0;
 }
 
-static long gmem_ctl_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
+/* A child file owns its controls, host windows and dma-buf exports. */
+static const struct file_operations gmem_provider_fops = {
+	.owner		= THIS_MODULE,
+	.release	= gmem_fops_release,
+	.mmap		= gmem_mmap,
+	.unlocked_ioctl	= gmem_fd_ioctl,
+	.compat_ioctl	= gmem_fd_ioctl,
+};
+
+/*
+ * Allocate a child over [base_pfn, +npages) and return its fd. Shared by
+ * SETUP (standalone region) and NEW_CHILD (a root sub-range). The fd owns the
+ * module pin on success.
+ */
+static int gmem_new_provider_fd(unsigned long base_pfn,
+				unsigned long npages, struct page *cma_pages,
+				u32 flags, unsigned long root_index,
+				unsigned long *owned, u32 allow,
+				struct gmem_info **out)
 {
-	struct gmem_provider_setup setup;
+	struct file *file;
 	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;
+	info = kzalloc_obj(*info);
+	if (!info)
+		return -ENOMEM;
+	info->base_pfn = base_pfn;
+	info->npages = npages;
+	info->cma_pages = cma_pages;
+	info->root_index = root_index;
+	info->owned = owned;
+	info->allow = allow;
+	info->absent = kvzalloc_objs(unsigned long, BITS_TO_LONGS(npages));
+	info->readonly = kvzalloc_objs(unsigned long, BITS_TO_LONGS(npages));
+	if (!info->absent || !info->readonly) {
+		ret = -ENOMEM;
+		goto err_free;
+	}
+	INIT_LIST_HEAD(&info->dmabufs);
+	INIT_LIST_HEAD(&info->root_link);
+	mutex_init(&info->dmabufs_lock);
+	mutex_init(&info->lock);
 
-	if (copy_from_user(&setup, (void __user *)arg, sizeof(setup)))
-		return -EFAULT;
-	if (setup.flags & ~GMEM_PROVIDER_FLAG_MMAP_CAPABLE)
-		return -EINVAL;
+	/* Pin THIS_MODULE while the provider fd is alive (release drops it). */
+	if (!try_module_get(THIS_MODULE)) {
+		ret = -ENODEV;
+		goto err_free;
+	}
+	info->mmap_capable = !!(flags & GMEM_PROVIDER_FLAG_MMAP_CAPABLE);
 
-	kvm_file = fget(setup.kvm_fd);
-	if (!kvm_file)
-		return -EBADF;
-	if (!file_is_kvm(kvm_file)) {
-		fput(kvm_file);
-		return -EINVAL;
+	/*
+	 * A private inode, not the shared anon one: host windows are torn
+	 * down by file range on revoke, which must not touch other files.
+	 */
+	fd = get_unused_fd_flags(O_CLOEXEC);
+	if (fd < 0) {
+		ret = fd;
+		module_put(THIS_MODULE);
+		goto err_free;
 	}
-	kvm = kvm_file->private_data;
-	if (!kvm) {
-		fput(kvm_file);
-		return -EINVAL;
+	file = anon_inode_create_getfile("[gmem-provider]", &gmem_provider_fops,
+					 info, O_RDWR, NULL);
+	if (IS_ERR(file)) {
+		put_unused_fd(fd);
+		ret = PTR_ERR(file);
+		module_put(THIS_MODULE);
+		goto err_free;
 	}
-	kvm_get_kvm(kvm);
-	fput(kvm_file);
+	info->mapping = file->f_mapping;
+	if (owned)
+		list_add(&info->root_link, &gmem_root.children);
+	fd_install(fd, file);
+	if (out)
+		*out = info;
+	return fd;
 
-	info = kzalloc(sizeof(*info), GFP_KERNEL);
-	if (!info) {
-		ret = -ENOMEM;
-		goto err_put_kvm;
-	}
+err_free:
+	kvfree(info->absent);
+	kvfree(info->readonly);
+	kfree(info);
+	return ret;
+}
+
+static long gmem_ctl_setup(void __user *uarg)
+{
+	struct gmem_provider_setup setup;
+	struct page *pages = NULL;
+	unsigned long base_pfn, npages;
+	int fd;
+
+	if (copy_from_user(&setup, uarg, sizeof(setup)))
+		return -EFAULT;
+	if (setup.flags & ~GMEM_PROVIDER_FLAG_MMAP_CAPABLE)
+		return -EINVAL;
+	/* kvm_fd is legacy and ignored: binding happens in KVM_CREATE_GUEST_MEMFD. */
 
 	if (addr && len) {
 		/* External page-less range from module params. */
-		info->base_pfn = addr >> PAGE_SHIFT;
-		info->npages = len >> PAGE_SHIFT;
+		base_pfn = addr >> PAGE_SHIFT;
+		npages = len >> PAGE_SHIFT;
 	} else {
 		/* CMA fallback: allocate a contiguous, page-backed region. */
-		if (!setup.size || !PAGE_ALIGNED(setup.size)) {
-			ret = -EINVAL;
-			goto err_free_info;
-		}
+		if (!setup.size || !PAGE_ALIGNED(setup.size))
+			return -EINVAL;
 		npages = setup.size >> PAGE_SHIFT;
 		pages = alloc_contig_pages(npages, GFP_KERNEL, numa_node_id(), NULL);
-		if (!pages) {
-			ret = -ENOMEM;
-			goto err_free_info;
-		}
+		if (!pages)
+			return -ENOMEM;
 		/* Provider path skips KVM's folio-clear; zero to avoid data leak. */
 		memset(page_to_virt(pages), 0, (size_t)npages << PAGE_SHIFT);
-		info->base_pfn = page_to_pfn(pages);
-		info->npages = npages;
-		info->cma_pages = pages;
+		base_pfn = page_to_pfn(pages);
 	}
 
-	info->absent = kvzalloc(BITS_TO_LONGS(info->npages) * sizeof(unsigned long),
-				GFP_KERNEL);
-	if (!info->absent) {
-		ret = -ENOMEM;
-		goto err_free_pages;
+	fd = gmem_new_provider_fd(base_pfn, npages, pages, setup.flags, 0,
+				  NULL, GMEM_ALLOW_ALL, NULL);
+	if (fd < 0 && pages)
+		free_contig_range(page_to_pfn(pages), npages);
+	return fd;
+}
+
+/*
+ * Lazily create the root region on first NEW_CHILD.  Uses the module params
+ * if given (page-less), else a CMA region of @size bytes.  Idempotent once
+ * created; a later different @size is ignored.
+ */
+static int gmem_root_ensure(u64 size)
+{
+	unsigned long npages;
+	struct page *pages = NULL;
+
+	lockdep_assert_held(&gmem_root.lock);
+	if (gmem_root.npages)
+		return 0;
+
+	if (addr && len) {
+		gmem_root.base_pfn = addr >> PAGE_SHIFT;
+		npages = len >> PAGE_SHIFT;
+	} else {
+		if (!size || !PAGE_ALIGNED(size))
+			return -EINVAL;
+		npages = size >> PAGE_SHIFT;
+		pages = alloc_contig_pages(npages, GFP_KERNEL, numa_node_id(), NULL);
+		if (!pages)
+			return -ENOMEM;
+		memset(page_to_virt(pages), 0, (size_t)npages << PAGE_SHIFT);
+		gmem_root.base_pfn = page_to_pfn(pages);
 	}
+	gmem_root.owned = kvzalloc_objs(unsigned long, BITS_TO_LONGS(npages));
+	gmem_root.donated = kvzalloc_objs(unsigned long, BITS_TO_LONGS(npages));
+	if (!gmem_root.owned || !gmem_root.donated) {
+		kvfree(gmem_root.owned);
+		kvfree(gmem_root.donated);
+		gmem_root.owned = NULL;
+		gmem_root.donated = NULL;
+		if (pages)
+			free_contig_range(page_to_pfn(pages), npages);
+		return -ENOMEM;
+	}
+	gmem_root.cma_pages = pages;
+	gmem_root.npages = npages;
+	return 0;
+}
 
-	INIT_LIST_HEAD(&info->dmabufs);
-	mutex_init(&info->dmabufs_lock);
-	mutex_init(&info->lock);
+static void gmem_root_teardown(void)
+{
+	if (!gmem_root.npages)
+		return;
+	WARN_ON(!list_empty(&gmem_root.children));
+	if (gmem_root.cma_pages)
+		free_contig_range(gmem_root.base_pfn, gmem_root.npages);
+	kvfree(gmem_root.owned);
+	kvfree(gmem_root.donated);
+	memset(&gmem_root, 0, sizeof(gmem_root));
+	mutex_init(&gmem_root.lock);
+	INIT_LIST_HEAD(&gmem_root.children);
+}
+
+/* Validate a page-aligned [offset, +len) against the root; return page bounds. */
+static int gmem_root_range(u64 offset, u64 length,
+			   unsigned long *first, unsigned long *last)
+{
+	if (!length || !PAGE_ALIGNED(offset) || !PAGE_ALIGNED(length))
+		return -EINVAL;
+	*first = offset >> PAGE_SHIFT;
+	*last = *first + (length >> PAGE_SHIFT);		/* exclusive */
+	if (*last <= *first || *last > gmem_root.npages)
+		return -EINVAL;
+	return 0;
+}
+
+/* Resolve a child fd created by NEW_CHILD; returns a referenced file. */
+static struct file *gmem_get_child(int fd, struct gmem_info **infop)
+{
+	struct file *f = fget(fd);
+	struct gmem_info *info;
+
+	if (!f)
+		return ERR_PTR(-EBADF);
+	if (f->f_op != &gmem_provider_fops) {
+		fput(f);
+		return ERR_PTR(-EINVAL);
+	}
+	info = to_gmem_info(f);
+	if (!info->owned) {
+		fput(f);
+		return ERR_PTR(-EINVAL);
+	}
+	*infop = info;
+	return f;
+}
 
+static long gmem_ctl_new_child(void __user *uarg)
+{
+	struct gmem_provider_new_child nc;
+	struct gmem_info *info;
+	unsigned long first, last;
+	unsigned long *owned;
+	int fd, ret;
+
+	if (copy_from_user(&nc, uarg, sizeof(nc)))
+		return -EFAULT;
+	if ((nc.flags & ~GMEM_PROVIDER_FLAG_MMAP_CAPABLE) || nc.pad ||
+	    (nc.allow & ~GMEM_ALLOW_ALL))
+		return -EINVAL;
+
+	/* nc.kvm_fd is legacy and ignored: binding happens in KVM_CREATE_GUEST_MEMFD. */
+
+	mutex_lock(&gmem_root.lock);
+	ret = gmem_root_ensure(nc.offset + nc.len);
+	if (ret)
+		goto out_unlock;
+	ret = gmem_root_range(nc.offset, nc.len, &first, &last);
+	if (ret)
+		goto out_unlock;
 	/*
-	 * Pin THIS_MODULE while the provider fd is alive.  The fd is created
-	 * with kvm_gmem_fops (owned by kvm.ko), which does not pin us, so
-	 * rmmod of gmem_provider is otherwise free to run behind our ops.
+	 * A carve is the range this child may ever hold; it is the VM's whole
+	 * view of memory and becomes its memslot.  Carves may overlap: that is
+	 * how a range can later MOVE from one VM to another.  Ownership is
+	 * per page and exclusive.  The new child is granted every page of its
+	 * carve that no other child owns and the root has not parked; the
+	 * rest it can only receive by MOVE or RECLAIM.  A carve with nothing
+	 * to grant is refused as a likely mistake.
 	 */
-	if (!try_module_get(THIS_MODULE)) {
-		ret = -ENODEV;
-		goto err_free_pages;
+	if (find_next_zero_bit(gmem_root.owned, last, first) >= last) {
+		ret = -EBUSY;
+		goto out_unlock;
 	}
 
-	info->backing.ops = &gmem_ops;
-	info->kvm = kvm;
-	info->mmap_capable = !!(setup.flags & GMEM_PROVIDER_FLAG_MMAP_CAPABLE);
+	/*
+	 * Allocate the ownership bitmap before the fd exists, so a failure
+	 * here has nothing to unwind.  It is handed to the new info below.
+	 */
+	owned = kvzalloc_objs(unsigned long, BITS_TO_LONGS(last - first));
+	if (!owned) {
+		ret = -ENOMEM;
+		goto out_unlock;
+	}
+	/* Establish the grant before publishing the fd. */
+	{
+		unsigned long i;
 
-	fd = anon_inode_getfd("[gmem-provider]", &kvm_gmem_fops,
-			      &info->backing, O_RDWR | O_CLOEXEC);
+		for (i = first; i < last; i++) {
+			if (test_bit(i, gmem_root.owned) ||
+			    test_bit(i, gmem_root.donated))
+				continue;
+			__set_bit(i - first, owned);
+			__set_bit(i, gmem_root.owned);
+		}
+	}
+	fd = gmem_new_provider_fd(gmem_root.base_pfn + first,
+				  last - first, NULL, nc.flags, first,
+				  owned, nc.allow, &info);
 	if (fd < 0) {
+		unsigned long i;
+
+		for_each_set_bit(i, owned, last - first)
+			__clear_bit(first + i, gmem_root.owned);
+		kvfree(owned);
 		ret = fd;
-		goto err_module_put;
+		goto out_unlock;
 	}
+	mutex_unlock(&gmem_root.lock);
 	return fd;
 
-err_module_put:
-	module_put(THIS_MODULE);
+out_unlock:
+	mutex_unlock(&gmem_root.lock);
+	return ret;
+}
 
-err_free_pages:
-	if (pages)
-		free_contig_range(page_to_pfn(pages), npages);
-err_free_info:
-	kvfree(info->absent);
-	kfree(info);
-err_put_kvm:
-	kvm_put_kvm(kvm);
+/*
+ * Take [first, last) away from @info: clear ownership, then revoke from both
+ * of its importers.  Ownership is cleared before the revoke so a racing fault
+ * that slips in re-reads "not owned" and gets the scratch frame or fails.
+ * Caller holds gmem_root.lock; we take info->lock inside it.
+ */
+static void gmem_child_lose(struct gmem_info *info,
+			    unsigned long first, unsigned long last)
+{
+	unsigned long s = first - info->root_index, e = last - info->root_index;
+
+	mutex_lock(&info->lock);
+	bitmap_clear(info->owned, s, e - s);
+	mutex_unlock(&info->lock);
+	gmem_revoke_range(info, s, e);
+	gmem_unmap_host(info, s, e);
+	bitmap_clear(gmem_root.owned, first, last - first);
+}
+
+/* Give [first, last) to @info and invalidate so its importers pick it up. */
+static void gmem_child_gain(struct gmem_info *info,
+			    unsigned long first, unsigned long last)
+{
+	unsigned long s = first - info->root_index, e = last - info->root_index;
+
+	mutex_lock(&info->lock);
+	bitmap_set(info->owned, s, e - s);
+	mutex_unlock(&info->lock);
+	gmem_revoke_range(info, s, e);
+	bitmap_set(gmem_root.owned, first, last - first);
+}
+
+/* Does child @info's carved range contain [first, last)? */
+static bool gmem_child_covers(struct gmem_info *info,
+			      unsigned long first, unsigned long last)
+{
+	return first >= info->root_index &&
+	       last <= info->root_index + info->npages;
+}
+
+/* Does child @info currently own every page of [first, last)? */
+static bool gmem_child_owns(struct gmem_info *info,
+			    unsigned long first, unsigned long last)
+{
+	unsigned long s = first - info->root_index, e = last - info->root_index;
+
+	return gmem_child_covers(info, first, last) &&
+	       find_next_zero_bit(info->owned, e, s) >= e;
+}
+
+static long gmem_ctl_move(void __user *uarg)
+{
+	struct gmem_provider_move mv;
+	struct gmem_info *src, *dst;
+	struct file *sf, *df;
+	unsigned long first, last;
+	long ret;
+
+	if (copy_from_user(&mv, uarg, sizeof(mv)))
+		return -EFAULT;
+	sf = gmem_get_child(mv.src_fd, &src);
+	if (IS_ERR(sf))
+		return PTR_ERR(sf);
+	df = gmem_get_child(mv.dst_fd, &dst);
+	if (IS_ERR(df)) {
+		fput(sf);
+		return PTR_ERR(df);
+	}
+
+	mutex_lock(&gmem_root.lock);
+	ret = gmem_root_range(mv.offset, mv.len, &first, &last);
+	if (ret)
+		goto out;
+	if (src == dst || !gmem_child_owns(src, first, last) ||
+	    !gmem_child_covers(dst, first, last)) {
+		ret = -EINVAL;
+		goto out;
+	}
+	/*
+	 * Revoke on the source first, grant on the destination second.  No two
+	 * importers hold the range at once.  Both children's info->lock are
+	 * taken in turn under gmem_root.lock, never nested with each other.
+	 */
+	gmem_child_lose(src, first, last);
+	gmem_child_gain(dst, first, last);
+	ret = 0;
+out:
+	mutex_unlock(&gmem_root.lock);
+	fput(df);
+	fput(sf);
+	return ret;
+}
+
+static long gmem_ctl_donate(void __user *uarg, bool reclaim)
+{
+	struct gmem_provider_donate d;
+	struct gmem_info *info;
+	struct file *f;
+	unsigned long first, last;
+	long ret;
+
+	if (copy_from_user(&d, uarg, sizeof(d)))
+		return -EFAULT;
+	if (d.pad)
+		return -EINVAL;
+	f = gmem_get_child(d.fd, &info);
+	if (IS_ERR(f))
+		return PTR_ERR(f);
+
+	mutex_lock(&gmem_root.lock);
+	ret = gmem_root_range(d.offset, d.len, &first, &last);
+	if (ret)
+		goto out;
+	if (!reclaim) {
+		/* DONATE: the child must own it; park it at the root. */
+		if (!gmem_child_owns(info, first, last)) {
+			ret = -EINVAL;
+			goto out;
+		}
+		gmem_child_lose(info, first, last);
+		bitmap_set(gmem_root.donated, first, last - first);
+	} else {
+		/* RECLAIM: must be donated and inside this child's range. */
+		if (!gmem_child_covers(info, first, last) ||
+		    find_next_zero_bit(gmem_root.donated, last, first) < last) {
+			ret = -EINVAL;
+			goto out;
+		}
+		bitmap_clear(gmem_root.donated, first, last - first);
+		gmem_child_gain(info, first, last);
+	}
+	ret = 0;
+out:
+	mutex_unlock(&gmem_root.lock);
+	fput(f);
 	return ret;
 }
 
+static long gmem_ctl_set_scratch(void __user *uarg)
+{
+	struct gmem_provider_scratch sc;
+	struct gmem_info *info;
+
+	if (copy_from_user(&sc, uarg, sizeof(sc)))
+		return -EFAULT;
+	if (sc.pad || sc.enable > 1)
+		return -EINVAL;
+
+	/*
+	 * Flipping the mode changes what every revoked page reports, so every
+	 * child is re-invalidated in full: cheap for a PoC, and it guarantees
+	 * no importer keeps a stale hole or a stale scratch mapping.
+	 */
+	mutex_lock(&gmem_root.lock);
+	WRITE_ONCE(gmem_root.scratch_enabled, !!sc.enable);
+	list_for_each_entry(info, &gmem_root.children, root_link)
+		gmem_revoke_range(info, 0, info->npages);
+	mutex_unlock(&gmem_root.lock);
+	return 0;
+}
+
+static long gmem_ctl_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
+{
+	void __user *uarg = (void __user *)arg;
+
+	switch (cmd) {
+	case GMEM_PROVIDER_SETUP:	return gmem_ctl_setup(uarg);
+	case GMEM_PROVIDER_NEW_CHILD:	return gmem_ctl_new_child(uarg);
+	case GMEM_PROVIDER_MOVE:	return gmem_ctl_move(uarg);
+	case GMEM_PROVIDER_DONATE:	return gmem_ctl_donate(uarg, false);
+	case GMEM_PROVIDER_RECLAIM:	return gmem_ctl_donate(uarg, true);
+	case GMEM_PROVIDER_SET_SCRATCH:	return gmem_ctl_set_scratch(uarg);
+	default:			return -ENOTTY;
+	}
+}
+
 static const struct file_operations gmem_ctl_fops = {
 	.owner		= THIS_MODULE,
 	.unlocked_ioctl	= gmem_ctl_ioctl,
@@ -749,20 +1040,34 @@ static struct miscdevice gmem_dev = {
 
 static int __init gmem_provider_init(void)
 {
+	int ret;
+
 	if ((addr || len) &&
 	    (!addr || !len || !PAGE_ALIGNED(addr) || !PAGE_ALIGNED(len))) {
 		pr_err("gmem_provider: addr= and len= must both be set and page aligned\n");
 		return -EINVAL;
 	}
-	return misc_register(&gmem_dev);
+	gmem_scratch_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
+	if (!gmem_scratch_page)
+		return -ENOMEM;
+	mutex_init(&gmem_root.lock);
+	INIT_LIST_HEAD(&gmem_root.children);
+
+	ret = misc_register(&gmem_dev);
+	if (ret)
+		__free_page(gmem_scratch_page);
+	return ret;
 }
 module_init(gmem_provider_init);
 
 static void __exit gmem_provider_exit(void)
 {
 	misc_deregister(&gmem_dev);
+	gmem_root_teardown();
+	__free_page(gmem_scratch_page);
 }
 module_exit(gmem_provider_exit);
 
 MODULE_LICENSE("GPL");
+MODULE_IMPORT_NS("DMA_BUF");
 MODULE_DESCRIPTION("Sample guest_memfd provider (external page-less range or CMA fallback)");
samples/kvm/gmem_provider.h +132 -12

173 lines not on this page · raw message

tools/testing/selftests/kvm/Makefile.kvm +2 -1
index 12004a487c32..6accbc56ae69 100644
@@ -78,11 +78,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_readonly_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_poc_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 +20 -8
index 665b19028e13..b5ef6b9b1385 100644
@@ -35,8 +35,8 @@ struct gmem_provider_setup {
 	__u64 size;
 };
 #define GMEM_PROVIDER_SETUP		_IOW('G', 1, struct gmem_provider_setup)
-#define GMEM_PROVIDER_FLAG_MMAP_CAPABLE	(1u << 0)
 #define GMEM_PROVIDER_GET_DMABUF	_IO('G', 3)
+#define GMEM_PROVIDER_FLAG_MMAP_CAPABLE	(1u << 0)
 
 struct gmem_provider_present {
 	__u64 offset;
@@ -94,7 +94,7 @@ int main(void)
 	struct vfio_device_attach_iommufd_pt att = {};
 	struct vfio_region_info reg = {};
 	const char *cdev_path;
-	int gmem_ctl, gmem_fd, dmabuf_fd, iommufd_fd, vfio_fd;
+	int gmem_ctl, gmem_fd, dmabuf_fd, prov_fd, vm_fd = -1, iommufd_fd, vfio_fd;
 	void *provider_hva, *sq_buf, *cq_buf, *bar;
 	uint16_t pci_cmd;
 	uint16_t expected_vid;
@@ -120,22 +120,34 @@ int main(void)
 		vm = ioctl(kvm, KVM_CREATE_VM, 0);
 		TEST_ASSERT(vm >= 0, "KVM_CREATE_VM errno=%d", errno);
 		setup.kvm_fd = vm;
+		vm_fd = vm;
 		close(kvm);
 	}
 	setup.size = PROVIDER_SIZE;
-	gmem_fd = ioctl(gmem_ctl, GMEM_PROVIDER_SETUP, &setup);
-	TEST_ASSERT(gmem_fd >= 0, "SETUP errno=%d", errno);
+	prov_fd = ioctl(gmem_ctl, GMEM_PROVIDER_SETUP, &setup);
+	TEST_ASSERT(prov_fd >= 0, "SETUP errno=%d", errno);
+
+	/* Export once; KVM and iommufd import the same dma-buf. */
+	dmabuf_fd = ioctl(prov_fd, GMEM_PROVIDER_GET_DMABUF);
+	TEST_ASSERT(dmabuf_fd >= 0, "GET_DMABUF errno=%d", errno);
+	{
+		struct kvm_create_guest_memfd cgm = {
+			.size = PROVIDER_SIZE,
+			.flags = GUEST_MEMFD_FLAG_MMAP | GUEST_MEMFD_FLAG_USE_DMABUF,
+			.dmabuf_fd = dmabuf_fd,
+		};
+		gmem_fd = ioctl(vm_fd, KVM_CREATE_GUEST_MEMFD, &cgm);
+		TEST_ASSERT(gmem_fd >= 0, "KVM_CREATE_GUEST_MEMFD(dmabuf) errno=%d", errno);
+	}
 
 	provider_hva = mmap(NULL, PROVIDER_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED,
 			    gmem_fd, 0);
 	TEST_ASSERT(provider_hva != MAP_FAILED, "provider mmap errno=%d", errno);
 	memset(provider_hva, 0xcc, 0x1000);	/* poison first page */
 
-	/* IOAS + provider dma-buf. */
+	/* IOAS + the same dma-buf KVM imported. */
 	alloc.size = sizeof(alloc);
 	TEST_ASSERT(!ioctl(iommufd_fd, IOMMU_IOAS_ALLOC, &alloc), "IOAS_ALLOC");
-	dmabuf_fd = ioctl(gmem_fd, GMEM_PROVIDER_GET_DMABUF);
-	TEST_ASSERT(dmabuf_fd >= 0, "GET_DMABUF");
 	mapf.size = sizeof(mapf);
 	mapf.flags = IOMMU_IOAS_MAP_FIXED_IOVA | IOMMU_IOAS_MAP_READABLE |
 		     IOMMU_IOAS_MAP_WRITEABLE;
@@ -367,10 +379,10 @@ int main(void)
 
 	munmap(bar, reg.size);
 	close(vfio_fd);
-	close(dmabuf_fd);
 	close(iommufd_fd);
 	munmap(provider_hva, PROVIDER_SIZE);
 	close(gmem_fd);
+	close(dmabuf_fd);
 	close(gmem_ctl);
 	return 0;
 }
tools/testing/selftests/kvm/include/kvm_util.h +23 -2
index 04a910164a29..c168c0880ebf 100644
@@ -664,17 +664,38 @@ static inline bool is_smt_on(void)
 
 void vm_create_irqchip(struct kvm_vm *vm);
 
-static inline int __vm_create_guest_memfd(struct kvm_vm *vm, u64 size,
-					  u64 flags)
+static inline int __vm_create_guest_memfd_dmabuf(struct kvm_vm *vm,
+						 u64 size, u64 flags,
+						 int dmabuf_fd)
 {
 	struct kvm_create_guest_memfd guest_memfd = {
 		.size = size,
 		.flags = flags,
+		.dmabuf_fd = dmabuf_fd,
 	};
 
 	return __vm_ioctl(vm, KVM_CREATE_GUEST_MEMFD, &guest_memfd);
 }
 
+static inline int __vm_create_guest_memfd(struct kvm_vm *vm, u64 size,
+					  u64 flags)
+{
+	return __vm_create_guest_memfd_dmabuf(vm, size, flags, 0);
+}
+
+/* A guest_memfd that imports the dma-buf @dmabuf_fd for its memory. */
+static inline int vm_create_guest_memfd_dmabuf(struct kvm_vm *vm,
+					       u64 size, u64 flags,
+					       int dmabuf_fd)
+{
+	int fd = __vm_create_guest_memfd_dmabuf(vm, size,
+						  flags | GUEST_MEMFD_FLAG_USE_DMABUF,
+						  dmabuf_fd);
+
+	TEST_ASSERT(fd >= 0, KVM_IOCTL_ERROR(KVM_CREATE_GUEST_MEMFD, fd));
+	return fd;
+}
+
 static inline int vm_create_guest_memfd(struct kvm_vm *vm, u64 size,
 					u64 flags)
 {
tools/testing/selftests/kvm/x86/gmem_poc_test.c new file +824 -0

824 lines not on this page · raw message

tools/testing/selftests/kvm/x86/gmem_provider_hugepage_test.c +26 -4
index fbbef9761e64..9c3bcfbe2cae 100644
@@ -36,8 +36,18 @@ struct gmem_provider_setup {
 	__u64 size;
 };
 #define GMEM_PROVIDER_SETUP _IOW('G', 1, struct gmem_provider_setup)
+#define GMEM_PROVIDER_GET_DMABUF	_IO('G', 3)
 #define GMEM_PROVIDER_FLAG_MMAP_CAPABLE (1u << 0)
 
+/* The dma-buf for a sample-provider child: what KVM and iommufd both import. */
+static int child_dmabuf(int child_fd)
+{
+	int fd = ioctl(child_fd, GMEM_PROVIDER_GET_DMABUF);
+
+	TEST_ASSERT(fd >= 0, "GMEM_PROVIDER_GET_DMABUF errno=%d", errno);
+	return fd;
+}
+
 #define DATA_SLOT	10
 #define DATA_GPA	(1ULL << 32)		/* 4G: 1G-aligned */
 #define DATA_SIZE	((uint64_t)SZ_1G + SZ_2M)
@@ -59,7 +69,8 @@ int main(void)
 	struct kvm_vcpu *vcpu;
 	struct kvm_vm *vm;
 	struct ucall uc;
-	int gmem_ctl, gmem_fd, r;
+	int gmem_ctl, gmem_fd, dmabuf_fd, r;
+	int prov_fd;
 	void *resv, *hva;
 	uint64_t p4k, p2m, p1g;
 
@@ -73,8 +84,17 @@ int main(void)
 
 	setup.kvm_fd = vm->fd;
 	setup.size = DATA_SIZE;
-	gmem_fd = ioctl(gmem_ctl, GMEM_PROVIDER_SETUP, &setup);
-	TEST_ASSERT(gmem_fd >= 0, "GMEM_PROVIDER_SETUP failed, errno %d", errno);
+	prov_fd = ioctl(gmem_ctl, GMEM_PROVIDER_SETUP, &setup);
+	TEST_ASSERT(prov_fd >= 0, "GMEM_PROVIDER_SETUP failed, errno %d", errno);
+
+	/*
+	 * The provider fd is not a guest_memfd; it is the provider fd.  The
+	 * guest_memfd KVM returns is what the memslot binds, what the host
+	 * mmaps (through the provider's mmap), and what iommufd would map.
+	 */
+	dmabuf_fd = child_dmabuf(prov_fd);
+	gmem_fd = vm_create_guest_memfd_dmabuf(vm, DATA_SIZE,
+					       GUEST_MEMFD_FLAG_MMAP, dmabuf_fd);
 
 	/*
 	 * Map the provider at a 1G-aligned host VA so the slot's userspace_addr
@@ -86,7 +106,7 @@ int main(void)
 	TEST_ASSERT(resv != MAP_FAILED, "reserve VA failed, errno %d", errno);
 	hva = (void *)(((uintptr_t)resv + SZ_1G - 1) & ~((uintptr_t)SZ_1G - 1));
 	hva = mmap(hva, DATA_SIZE, PROT_READ | PROT_WRITE,
-		   MAP_SHARED | MAP_FIXED, gmem_fd, 0);
+		   MAP_SHARED | MAP_FIXED, prov_fd, 0);
 	TEST_ASSERT(hva != MAP_FAILED,
 		    "mmap(provider) failed, errno %d", errno);
 
@@ -125,6 +145,8 @@ int main(void)
 	kvm_vm_free(vm);
 	munmap(hva, DATA_SIZE);
 	close(gmem_fd);
+	close(dmabuf_fd);
+	close(prov_fd);
 	close(gmem_ctl);
 	return 0;
 }
tools/testing/selftests/kvm/x86/gmem_provider_iommufd_test.c +31 -11

95 lines not on this page · raw message

tools/testing/selftests/kvm/x86/gmem_provider_readonly_test.c new file +172 -0

172 lines not on this page · raw message

tools/testing/selftests/kvm/x86/gmem_provider_revoke_test.c +28 -6
index 415972aa8a7e..df2e9fbd91d8 100644
@@ -38,9 +38,19 @@ struct gmem_provider_present {
 	__u32 pad;
 };
 #define GMEM_PROVIDER_SETUP		_IOW('G', 1, struct gmem_provider_setup)
+#define GMEM_PROVIDER_GET_DMABUF	_IO('G', 3)
 #define GMEM_PROVIDER_FLAG_MMAP_CAPABLE	(1u << 0)
 #define GMEM_PROVIDER_SET_PRESENT	_IOW('G', 2, struct gmem_provider_present)
 
+/* The dma-buf for a sample-provider child: what KVM and iommufd both import. */
+static int child_dmabuf(int child_fd)
+{
+	int fd = ioctl(child_fd, GMEM_PROVIDER_GET_DMABUF);
+
+	TEST_ASSERT(fd >= 0, "GMEM_PROVIDER_GET_DMABUF errno=%d", errno);
+	return fd;
+}
+
 #define DATA_SLOT	10
 #define DATA_GPA	(1ULL << 32)
 #define DATA_SIZE	0x200000ULL		/* 2 MiB region */
@@ -64,7 +74,8 @@ int main(void)
 	struct kvm_vcpu *vcpu;
 	struct kvm_vm *vm;
 	struct ucall uc;
-	int gmem_ctl, gmem_fd, r;
+	int gmem_ctl, gmem_fd, dmabuf_fd, r;
+	int prov_fd;
 	void *hva;
 
 	TEST_REQUIRE(kvm_check_cap(KVM_CAP_VM_TYPES) & BIT(KVM_X86_SW_PROTECTED_VM));

Lines of this file are not shown. View the raw message.

tools/testing/selftests/kvm/x86/gmem_provider_test.c +3 -187

190 lines not on this page · raw message

tools/testing/selftests/kvm/x86/gmem_provider_vfio_test.c +34 -11

45 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.47.3

Part of the diff is not shown here. View the raw message.

#30 lore raw

cover mm: Memory providers for guest_memfd and iommufd

In reply to David Woodhouse

From: Fred Griffoul <[email protected]>

Some drivers manage RAM outside the page allocator: a carve-out, device memory, or memory that a host component moves between VMs while they run. This memory often has no struct page. The driver wants to lend pages to a VM and to its devices, and to take any of them back later.

David Woodhouse's series "KVM: Allow alternative providers of guest_memfd backed by PFNMAP memory" lets such a driver back a guest_memfd through struct kvm_gmem_ops:

https://lore.kernel.org/kvm/[email protected]/

That covers the guest, but not the VM's devices, which his cover letter left as an open question. This series adds a small interface in
mm: the driver that owns the memory becomes a provider, and the code that maps it attaches as a consumer. There are two consumers, a guest_memfd backend and IOMMU_IOAS_MAP_FILE in iommufd.

The series is on top of David's v2 (base 0e35b9b6ec0f). Patch 1 was part of the earlier dma-buf RFC. The provider backend depends on it, so this series carries it.

Why not dma-buf
===============

The earlier RFC shared the memory as a dma-buf. Christian König rejected that: an importer must not build its own page tables from a dma-buf, and the use case should stay out of drivers/dma-buf. I acknowledged that and dropped it; this series does not touch dma-buf.

Why a new interface
===================

kvm_gmem_ops gives KVM a way in. For devices, the only option today is a dma-buf plus a private call that iommufd looks up with symbol_get(), which is how vfio-pci works. Each new owner would need another such lookup, and iommufd would end up knowing each owner by name. With a common interface, a provider module only calls into mm, and nothing needs symbol_get().

It also means the provider revokes a range once. The VMM hands the same file to KVM and to iommufd; on a revoke the core forwards it to every consumer, so KVM clears the range from stage-2, iommufd from the IOMMU page tables, and guest_memfd from the VMM's own mapping, all before the revoke returns.

The contract
============

For a page of a provider file, get_page() returns the frame, its type (RAM or MMIO, read-only or not), and the largest aligned block of frames of the same type, so that consumers can use large mappings. A page without a frame is a hole.

Consumers take no references. A frame stays valid until the revoke that removes it returns. To guarantee that, a consumer either holds a lock across get_page() and the mapping that its revoke callback also takes, or detects a racing revoke and retries.

The interface does not deal with folios. The native guest_memfd backend and memfd pinning in iommufd handle pages from the page allocator, and pages that can move or swap would need references. A backend that needs full control over the file can still write its own kvm_gmem_ops.

Backends
========

The motivating user is a host-side memory manager. It reserves a region of host RAM, lends parts of it to VMs and their devices, moves pages between VMs, and has to survive a live update of the host kernel. The sample module in this series models it.

Device-DAX could also be a provider: its range never moves, get_page() is short, and it only revokes on unbind. iommufd can map MMIO, but KVM takes only RAM, because it picks the guest memory type itself.

Neither consumer keeps state about the provider's frames, which helps with live update. guest_memfd has nothing to save across kexec, since KVM refills stage-2 on faults. The provider saves its frames and who owns them. Devices cannot fault, so their mappings stay part of the existing iommufd live update work, and the provider only has to give back the same frames.

Confidential VMs
================

This series does not support them yet. For now only x86 VMs of type KVM_X86_DEFAULT_VM can use a provider.

I don't think a provider should back private pages. Revoking a private page loses its contents, and only guest_memfd knows which pages are private. The interface could still be useful there later, with guest_memfd acting as a provider for its own files so that iommufd only maps shared pages. I left that for a later series.

Patches
=======

Patch 1 lets a kvm_gmem_ops backend map a page read-only for the guest. get_pfn() gets a writable output, and a guest write to such a page exits with KVM_EXIT_MEMORY_FAULT. KVM_MEM_READONLY can't be used for this, because guest_memfd slots don't allow it.

Patch 2 adds the interface and the core, and the FOP_MEM_PROVIDER flag in struct file_operations.

Patch 3 adds the provider backend to guest_memfd, with the GUEST_MEMFD_FLAG_USE_PROVIDER flag and a provider_fd field. guest_memfd also handles the userspace mapping of the file, if the provider allows it, so providers don't each have to get the fault and revoke handling right.

Patch 4 prepares iommufd for tracking pages it does not pin. No functional change.

Patch 5 lets IOMMU_IOAS_MAP_FILE take a provider file. iommufd maps one PAGE_SIZE entry per page and pins nothing. It leaves holes unmapped and honours read-only and MMIO pages. On a revoke, it unmaps the range and maps whatever the provider backs now.

The PAGE_SIZE entries are deliberate for now: a partial revoke then never has to split a large IOMMU page. Using the block size the provider reports would be better, and needs the revoke to unmap and remap whole blocks. A device that accesses the range between the unmap and the map faults; replacing the entries in place would avoid that, but needs new support in the IOMMU drivers. Both are left for later.

Patches 6 and 7 add iommufd selftests: two mock-domain queries and a mock provider.

Patch 8 adds a sample provider. It gives each VM a child file, can move, donate and reclaim pages, and supports read-only pages. A child file is read-only to its holder; the owner changes it through the control device. It only uses the mm interface.

Patch 9 adds a KVM selftest with one provider and two VMMs. After each change it checks what the guest, the device and the VMM's mapping see.

Testing
=======

x86_64, in QEMU with KASAN, PROVE_LOCKING and DEBUG_ATOMIC_SLEEP, with two ranges hidden from the host with memmap=, one for each sample. No KASAN report, lockdep splat or warning in any run.

- mem_provider_test, the selftest in patch 9: pass.
- guest_memfd_test, including the USE_PROVIDER flag check: pass.
- iommufd_selftest, iommufd_ioas: the 12 provider tests pass in all four variants. The 4 failures are access_domain_destory, which the series does not touch: it needs hugetlb pages, which this VM has none of.
- David's gmem_provider tests, which this series does not change:
hugepage, revoke, iommufd and readonly pass; the SNP and vfio-pci tests skip for lack of hardware.

Not tested: arm64, where guest_memfd refuses providers; a real IOMMU, since only the mock domain was used.

I wrote most of this series with AI help, and I am posting it as an RFC to get feedback on the interface.

Fred Griffoul (9):
KVM: guest_memfd: Add a writable result to get_pfn()
mm: Add memory providers
KVM: guest_memfd: Add a memory provider backing
iommufd: Track the domains of pages that are not pinned
iommufd: Map memory provider files
iommufd/selftest: Add mock-domain IOVA queries iommufd/selftest: Add a mock memory provider samples/kvm: Add a memory provider sample
KVM: selftests: Test a memory provider shared by KVM and iommufd

 Documentation/virt/kvm/api.rst                |  45 +-
 MAINTAINERS                                   |   8 +
 arch/arm64/kvm/mmu.c                          |  13 +-
 arch/arm64/kvm/nested.c                       |  16 +-
 arch/x86/kvm/mmu/mmu.c                        |  18 +-
 arch/x86/kvm/svm/sev.c                        |  13 +-
 arch/x86/kvm/x86.c                            |  10 +
 drivers/iommu/iommufd/Kconfig                 |   1 +
 drivers/iommu/iommufd/io_pagetable.c          |  37 +-
 drivers/iommu/iommufd/io_pagetable.h          |  54 +-
 drivers/iommu/iommufd/iommufd_test.h          |  36 +
 drivers/iommu/iommufd/pages.c                 | 340 ++++++-
 drivers/iommu/iommufd/selftest.c              | 286 ++++++
 include/linux/fs.h                            |   2 +
 include/linux/kvm_host.h                      |  20 +-
 include/linux/mem_provider.h                  | 211 +++++
 include/uapi/linux/iommufd.h                  |  11 +-
 include/uapi/linux/kvm.h                      |  11 +-
 mm/Kconfig                                    |   7 +
 mm/Makefile                                   |   1 +
 mm/mem_provider.c                             | 177 ++++
 samples/Kconfig                               |  17 +
 samples/Makefile                              |   1 +
 samples/kvm/Makefile                          |   1 +
 samples/kvm/gmem_provider.c                   |  67 +-
 samples/kvm/gmem_provider.h                   |  17 +
 samples/kvm/mem_provider_sample.c             | 855 ++++++++++++++++++
 samples/kvm/mem_provider_sample.h             | 135 +++
 tools/include/uapi/linux/kvm.h                |  11 +-
 tools/testing/selftests/iommu/iommufd.c       | 119 +++
 tools/testing/selftests/iommu/iommufd_utils.h |  64 ++
 tools/testing/selftests/kvm/Makefile.kvm      |   2 +
 .../testing/selftests/kvm/guest_memfd_test.c  |   6 +
 .../kvm/x86/gmem_provider_readonly_test.c     | 150 +++
 .../selftests/kvm/x86/mem_provider_test.c     | 582 ++++++++++++
 virt/kvm/Kconfig                              |   1 +
 virt/kvm/guest_memfd.c                        | 286 +++++-
 37 files changed, 3531 insertions(+), 100 deletions(-)
 create mode 100644 include/linux/mem_provider.h
 create mode 100644 mm/mem_provider.c
 create mode 100644 samples/kvm/mem_provider_sample.c
 create mode 100644 samples/kvm/mem_provider_sample.h
 create mode 100644 tools/testing/selftests/kvm/x86/gmem_provider_readonly_test.c
 create mode 100644 tools/testing/selftests/kvm/x86/mem_provider_test.c

base-commit: 0e35b9b6ec0ffcc5e23cbdec09f5c622ad532b53
prerequisite-patch-id: 2a0016e90f0690baef841a8c34c07b96e3f1b941
prerequisite-patch-id: c497c1ff1e9de8e9c470c58b163ccbfce4827ae7
prerequisite-patch-id: a16b61afd172662bde725e5c12805758f76b89fa
prerequisite-patch-id: 0ddee6c1b48fa853e6a94f2746340e525477d287
prerequisite-patch-id: 4dc9a395a2eb73283b20b75e2ba763ec72b2e22d
prerequisite-patch-id: a9758d7f8f6959dae6ad154902fa1269234dbc3c
prerequisite-patch-id: 0537bcc3ca5e3bb9b86fe7c99a245a9ff9d67831
prerequisite-patch-id: d5feb18b6630c99973259804418243d856c37ce7
prerequisite-patch-id: 2a08a105b6b5d46240a69f5bbf646211d44f8412
prerequisite-patch-id: 760b34834d5d8dcdf1ae1a09cc6aae267dd7760c
prerequisite-patch-id: dd94ecc7ae9472c2bf005c9cb1c483994eacd163

Signature · 1 line
2.47.3
#31 lore raw

PATCH 1/9 KVM: guest_memfd: Add a writable result to get_pfn()

From: Fred Griffoul <[email protected]>

A guest_memfd backing cannot map a page read-only for the guest:
get_pfn() returns only a frame, and KVM_MEM_READONLY is refused on guest_memfd slots. A hypervisor therefore cannot give a guest a page it may read but not write.

Let get_pfn() clear a writable result. The x86 and arm64 fault paths then map the page without write permission, and a guest write exits with KVM_EXIT_MEMORY_FAULT. The result covers the whole block that max_order allows.

Callers that hand the page to something that writes it must refuse a read-only page: the arm64 VNCR page and the SEV-SNP VMSA. populate() has no writable result, so a backing cannot report read-only state through it. The result does not cover KVM's own writes through the slot's host address.

David's gmem_provider sample gains a read-only ioctl, and a selftest checks that a guest write to such a page exits and lands once the page is writable again.

---
 arch/arm64/kvm/mmu.c                          |  13 +-
 arch/arm64/kvm/nested.c                       |  16 +-
 arch/x86/kvm/mmu/mmu.c                        |  18 ++-
 arch/x86/kvm/svm/sev.c                        |  13 +-
 include/linux/kvm_host.h                      |  16 +-
 samples/kvm/gmem_provider.c                   |  67 +++++++-
 samples/kvm/gmem_provider.h                   |  17 ++
 tools/testing/selftests/kvm/Makefile.kvm      |   1 +
 .../kvm/x86/gmem_provider_readonly_test.c     | 150 ++++++++++++++++++
 virt/kvm/guest_memfd.c                        |  21 ++-
 10 files changed, 309 insertions(+), 23 deletions(-)
 create mode 100644 tools/testing/selftests/kvm/x86/gmem_provider_readonly_test.c
arch/arm64/kvm/mmu.c +8 -5
index 6c941aaa10c6..32e591edc69d 100644
@@ -1607,7 +1607,7 @@ struct kvm_s2_fault_desc {
 
 static int gmem_abort(const struct kvm_s2_fault_desc *s2fd)
 {
-	bool write_fault, exec_fault;
+	bool write_fault, exec_fault, writable;
 	bool perm_fault = kvm_vcpu_trap_is_permission_fault(s2fd->vcpu);
 	enum kvm_pgtable_walk_flags flags = KVM_PGTABLE_WALK_SHARED;
 	enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_R;
@@ -1641,14 +1641,17 @@ static int gmem_abort(const struct kvm_s2_fault_desc *s2fd)
 	/* Pairs with the smp_wmb() in kvm_mmu_invalidate_end(). */
 	smp_rmb();
 
-	ret = kvm_gmem_get_pfn(kvm, s2fd->memslot, gfn, &pfn, &page, NULL);
-	if (ret) {
+	ret = kvm_gmem_get_pfn(kvm, s2fd->memslot, gfn, &pfn, &page, NULL,
+			       &writable);
+	if (ret || (write_fault && !writable)) {
 		kvm_prepare_memory_fault_exit(s2fd->vcpu, s2fd->fault_ipa, PAGE_SIZE,
 					      write_fault, exec_fault, false);
-		return ret;
+		if (!ret)
+			kvm_release_faultin_page(kvm, page, true, false);
+		return ret ?: -EFAULT;
 	}
 
-	if (!(s2fd->memslot->flags & KVM_MEM_READONLY))
+	if (!(s2fd->memslot->flags & KVM_MEM_READONLY) && writable)
 		prot |= KVM_PGTABLE_PROT_W;
 
 	if (s2fd->nested)
arch/arm64/kvm/nested.c +12 -4
index fb54f6dad995..fa86705df949 100644
@@ -1411,11 +1411,19 @@ static int kvm_translate_vncr(struct kvm_vcpu *vcpu, bool *is_gmem)
 		if (is_error_noslot_pfn(pfn) || (write_fault && !writable))
 			return -EFAULT;
 	} else {
-		ret = kvm_gmem_get_pfn(vcpu->kvm, memslot, gfn, &pfn, &page, NULL);
-		if (ret) {
+		ret = kvm_gmem_get_pfn(vcpu->kvm, memslot, gfn, &pfn, &page, NULL,
+				       &writable);
+		/*
+		 * The VNCR page is always written, so a read-only page cannot
+		 * back it.  Exit on the first access, even a read, rather than
+		 * map it read-only and fault on the next write.
+		 */
+		if (ret || !writable) {
 			kvm_prepare_memory_fault_exit(vcpu, vt->wr.pa, PAGE_SIZE,
-					      write_fault, false, false);
-			return ret;
+					      true, false, false);
+			if (!ret)
+				kvm_release_faultin_page(vcpu->kvm, page, true, false);
+			return ret ?: -EFAULT;
 		}
 	}
 
arch/x86/kvm/mmu/mmu.c +16 -2
index 234d0a95abf5..f689ef5c2b46 100644
@@ -4612,6 +4612,7 @@ static void kvm_mmu_finish_page_fault(struct kvm_vcpu *vcpu,
 static int kvm_mmu_faultin_pfn_gmem(struct kvm_vcpu *vcpu,
 				    struct kvm_page_fault *fault)
 {
+	bool writable;
 	int max_order, r;
 
 	if (!kvm_slot_has_gmem(fault->slot)) {
@@ -4620,13 +4621,26 @@ static int kvm_mmu_faultin_pfn_gmem(struct kvm_vcpu *vcpu,
 	}
 
 	r = kvm_gmem_get_pfn(vcpu->kvm, fault->slot, fault->gfn, &fault->pfn,
-			     &fault->refcounted_page, &max_order);
+			     &fault->refcounted_page, &max_order, &writable);
 	if (r) {
 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
 		return r;
 	}
 
-	fault->map_writable = !(fault->slot->flags & KVM_MEM_READONLY);
+	/*
+	 * get_pfn() may clear writable, on top of the memslot's read-only flag:
+	 * a read-only page is mapped read-only, and a guest write to it exits to
+	 * userspace rather than being installed.
+	 */
+	fault->map_writable = !(fault->slot->flags & KVM_MEM_READONLY) &&
+			      writable;
+	if (fault->write && !fault->map_writable) {
+		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
+		kvm_release_faultin_page(vcpu->kvm, fault->refcounted_page,
+				 true, false);
+		fault->refcounted_page = NULL;
+		return -EFAULT;
+	}
 	fault->max_level = kvm_max_level_for_order(max_order);
 
 	return RET_PF_CONTINUE;
arch/x86/kvm/svm/sev.c +11 -2
index 125779c82bc4..f4f944c7da10 100644
@@ -4026,6 +4026,7 @@ static void sev_snp_init_protected_guest_state(struct kvm_vcpu *vcpu)
 	struct vcpu_svm *svm = to_svm(vcpu);
 	struct kvm_memory_slot *slot;
 	struct page *page;
+	bool writable;
 	kvm_pfn_t pfn;
 	gfn_t gfn;
 
@@ -4063,9 +4064,17 @@ static void sev_snp_init_protected_guest_state(struct kvm_vcpu *vcpu)
 	 * The new VMSA will be private memory guest memory, so retrieve the
 	 * PFN from the gmem backend.
 	 */
-	if (kvm_gmem_get_pfn(vcpu->kvm, slot, gfn, &pfn, &page, NULL))
+	if (kvm_gmem_get_pfn(vcpu->kvm, slot, gfn, &pfn, &page, NULL,
+			     &writable))
 		return;
 
+	/* The CPU writes the VMSA on every VMRUN: a read-only page cannot be one. */
+	if (!writable) {
+		if (page)
+			kvm_release_page_clean(page);
+		return;
+	}
+
 	/*
 	 * From this point forward, the VMSA will always be a guest-mapped page
 	 * rather than the initial one allocated by KVM in svm->sev_es.vmsa. In
@@ -4996,7 +5005,7 @@ void sev_handle_rmp_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code)
 		return;
 	}
 
-	ret = kvm_gmem_get_pfn(kvm, slot, gfn, &pfn, &page, &order);
+	ret = kvm_gmem_get_pfn(kvm, slot, gfn, &pfn, &page, &order, NULL);
 	if (ret) {
 		pr_warn_ratelimited("SEV: Unexpected RMP fault, no backing page for private GPA 0x%llx\n",
 				    gpa);
include/linux/kvm_host.h +13 -3
index 04fa0cb126f6..7281d0e94121 100644
@@ -649,6 +649,15 @@ static inline bool kvm_slot_has_gmem(const struct kvm_memory_slot *slot)
  *    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().
+ *  - *writable, when the caller passes it, is true on entry.  Clear it to
+ *    have KVM map the page read-only; a guest write then exits as a memory
+ *    fault.  It covers the whole block that *max_order allows, so that block
+ *    must be all writable or all read-only.  It applies to stage-2 mappings
+ *    only, not to KVM's own writes through the memslot's host address.  A
+ *    caller that hands the page to hardware that writes it passes @writable
+ *    and refuses a read-only page.  Only a caller that never writes the page
+ *    itself passes NULL.  populate() has no writable result, so KVM cannot
+ *    learn read-only state through it; it is used only to fill a page.
  *
  * 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
@@ -662,7 +671,8 @@ struct kvm_gmem_ops {
 		       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);
+		       kvm_pfn_t *pfn, struct page **page, int *max_order,
+		       bool *writable);
 	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);
@@ -2651,12 +2661,12 @@ static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)
 #ifdef CONFIG_KVM_GUEST_MEMFD
 int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 		     gfn_t gfn, kvm_pfn_t *pfn, struct page **page,
-		     int *max_order);
+		     int *max_order, bool *writable);
 #else
 static inline int kvm_gmem_get_pfn(struct kvm *kvm,
 				   struct kvm_memory_slot *slot, gfn_t gfn,
 				   kvm_pfn_t *pfn, struct page **page,
-				   int *max_order)
+				   int *max_order, bool *writable)
 {
 	KVM_BUG_ON(1, kvm);
 	return -EIO;
samples/kvm/gmem_provider.c +65 -2

115 lines not on this page · raw message

samples/kvm/gmem_provider.h +17 -0
index 45f1b8257f60..51b49ef9a3c5 100644
@@ -41,6 +41,23 @@ struct gmem_provider_present {
 
 #define GMEM_PROVIDER_SET_PRESENT	_IOW(GMEM_PROVIDER_IOCTL_BASE, 2, struct gmem_provider_present)
 
+/*
+ * ioctl on a provider fd: make a byte range read-only for the guest, or
+ * writable again.  KVM maps a read-only page without write permission and a
+ * guest write to it exits to userspace with KVM_EXIT_MEMORY_FAULT.  Existing
+ * mappings of the range are dropped so the change takes effect on the next
+ * access.
+ */
+struct gmem_provider_readonly {
+	__u64 offset;	/* byte offset into the provider region, page aligned */
+	__u64 len;	/* byte length, page aligned */
+	__u32 readonly;	/* 1 = guest may not write, 0 = guest may write */
+	__u32 pad;
+};
+
+#define GMEM_PROVIDER_SET_READONLY \
+	_IOW(GMEM_PROVIDER_IOCTL_BASE, 4, struct gmem_provider_readonly)
+
 /*
  * ioctl on a provider fd (returned by SETUP): export the backing region as a
  * dynamic dma-buf and return an fd for it, suitable for
tools/testing/selftests/kvm/Makefile.kvm +1 -0
index 12004a487c32..4d7082448cea 100644
@@ -81,6 +81,7 @@ 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_readonly_test
 TEST_GEN_PROGS_x86 += x86/gmem_provider_iommufd_test
 TEST_GEN_PROGS_x86 += x86/gmem_provider_vfio_test
 TEST_GEN_PROGS_x86 += x86/hwcr_msr_test
tools/testing/selftests/kvm/x86/gmem_provider_readonly_test.c new file +150 -0

150 lines not on this page · raw message

virt/kvm/guest_memfd.c +16 -5
index d284bb70fe05..a509f1a96c0b 100644
@@ -624,7 +624,7 @@ static void kvm_gmem_native_unbind(struct file *slot_file, struct kvm *kvm,
 static int  kvm_gmem_native_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 *max_order, bool *writable);
 static void kvm_gmem_native_release(struct file *file);
 static int  kvm_gmem_native_mmap(struct file *file,
 				 struct vm_area_struct *vma);
@@ -988,7 +988,7 @@ static struct folio *__kvm_gmem_get_pfn(struct file *file,
 static int kvm_gmem_native_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 *max_order, bool *writable)
 {
 	pgoff_t index = kvm_gmem_get_index(slot, gfn);
 	struct folio *folio;
@@ -1016,7 +1016,7 @@ static int kvm_gmem_native_get_pfn(struct file *file, struct kvm *kvm,
 
 int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 		     gfn_t gfn, kvm_pfn_t *pfn, struct page **page,
-		     int *max_order)
+		     int *max_order, bool *writable)
 {
 	const struct kvm_gmem_ops *ops;
 
@@ -1029,7 +1029,10 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 		return -EFAULT;
 
 	*page = NULL;
-	return ops->get_pfn(file, kvm, slot, gfn, pfn, page, max_order);
+	if (writable)
+		*writable = true;
+	return ops->get_pfn(file, kvm, slot, gfn, pfn, page, max_order,
+			    writable);
 }
 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_gmem_get_pfn);
 
@@ -1080,6 +1083,7 @@ static int kvm_gmem_populate_one(const struct kvm_gmem_ops *ops,
 				      void *opaque)
 {
 	struct page *ignored_page = NULL;
+	bool writable = true;
 	kvm_pfn_t pfn;
 	int ret;
 
@@ -1093,10 +1097,17 @@ static int kvm_gmem_populate_one(const struct kvm_gmem_ops *ops,
 				    src_page, 0);
 	else
 		ret = ops->get_pfn(file, kvm, slot, gfn, &pfn,
-				   &ignored_page, NULL);
+				   &ignored_page, NULL, &writable);
 	if (ret)
 		return ret;
 
+	/* post_populate() writes the page, so it cannot be read-only. */
+	if (!writable) {
+		if (ignored_page)
+			put_page(ignored_page);
+		return -EPERM;
+	}
+
 	ret = post_populate(kvm, gfn, pfn, src_page, opaque);
 
 	/*
#32 lore raw

PATCH 2/9 mm: Add memory providers

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

A driver that owns memory outside the page allocator, often without struct page, has no common way to lend it to the code that maps it. guest_memfd and iommufd each need their own hooks, and the owner must keep them consistent when it takes memory back.

Add an interface between such an owner, the provider, and its consumers. A consumer attaches to a provider file, asks for the frame and attributes behind each page, and makes every mapping itself. When the provider changes a range, it revokes it, and every consumer of the file removes its mappings before the revoke returns.

A frame is therefore valid until its revoke returns, and consumers hold no references. A revoke reaches every consumer of the file, so a provider cannot take a frame from one consumer while another still maps it.

A provider is found from its file: its file_operations sit in a struct mem_provider_fops with the provider's operations, and FOP_MEM_PROVIDER is set. Each provider file embeds a struct mem_provider_file that holds its consumers, and the provider revokes through it. The core has no registry and no global state, and struct file_operations does not grow.

The provider also owns the host memory type of its frames. Memory that is not System RAM must have its type reserved, or PAT makes it uncached on x86.

---
 MAINTAINERS                  |   7 ++
 include/linux/fs.h           |   2 +
 include/linux/mem_provider.h | 211 +++++++++++++++++++++++++++++++++++
 mm/Kconfig                   |   7 ++
 mm/Makefile                  |   1 +
 mm/mem_provider.c            | 177 +++++++++++++++++++++++++++++
 6 files changed, 405 insertions(+)
 create mode 100644 include/linux/mem_provider.h
 create mode 100644 mm/mem_provider.c
MAINTAINERS +7 -0
index f37a81950e25..6cab075a3ff7 100644
@@ -17360,6 +17360,13 @@ T:	git git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
 F:	include/uapi/asm-generic/mman-common.h
 F:	mm/madvise.c
 
+MEMORY PROVIDERS
+M:	Fred Griffoul <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	include/linux/mem_provider.h
+F:	mm/mem_provider.c
+
 MEMORY TECHNOLOGY DEVICES (MTD)
 M:	Miquel Raynal <[email protected]>
 M:	Richard Weinberger <[email protected]>
include/linux/fs.h +2 -0
index 50ce731a2b78..f459f0e34ca5 100644
@@ -1980,6 +1980,8 @@ struct file_operations {
 #define FOP_ASYNC_LOCK		((__force fop_flags_t)(1 << 6))
 /* File system supports uncached read/write buffered IO */
 #define FOP_DONTCACHE		((__force fop_flags_t)(1 << 7))
+/* Lends memory to consumers: embedded in a struct mem_provider_fops */
+#define FOP_MEM_PROVIDER	((__force fop_flags_t)(1 << 8))
 
 /* Wrap a directory iterator that needs exclusive inode access */
 int wrap_directory_iterator(struct file *, struct dir_context *,
include/linux/mem_provider.h new file +211 -0

211 lines not on this page · raw message

mm/Kconfig +7 -0
index 9e0ca4824905..7085bf6666e5 100644
@@ -774,6 +774,13 @@ config DEFAULT_MMAP_MIN_ADDR
 config ARCH_SUPPORTS_MEMORY_FAILURE
 	bool
 
+config MEM_PROVIDER
+	bool
+	help
+	  An interface that lets a driver lend memory that the page allocator
+	  does not manage to consumers such as guest_memfd and iommufd, and
+	  take it back.  See include/linux/mem_provider.h.
+
 config MEMORY_FAILURE
 	depends on MMU
 	depends on ARCH_SUPPORTS_MEMORY_FAILURE
mm/Makefile +1 -0
index eff9f9e7e061..35420b587f89 100644
@@ -110,6 +110,7 @@ obj-$(CONFIG_CGROUP_HUGETLB) += hugetlb_cgroup.o
 obj-$(CONFIG_GUP_TEST) += gup_test.o
 obj-$(CONFIG_DMAPOOL_TEST) += dmapool_test.o
 obj-$(CONFIG_MEMORY_FAILURE) += memory-failure.o
+obj-$(CONFIG_MEM_PROVIDER) += mem_provider.o
 obj-$(CONFIG_HWPOISON_INJECT) += hwpoison-inject.o
 obj-$(CONFIG_DEBUG_KMEMLEAK) += kmemleak.o
 obj-$(CONFIG_DEBUG_RODATA_TEST) += rodata_test.o
mm/mem_provider.c new file +177 -0

177 lines not on this page · raw message

#33 lore raw

PATCH 3/9 KVM: guest_memfd: Add a memory provider backing

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

A driver can back a guest_memfd today only by implementing kvm_gmem_ops itself, and must then keep any device mapping of the same memory consistent on its own.

Add GUEST_MEMFD_FLAG_USE_PROVIDER. KVM_CREATE_GUEST_MEMFD then takes a memory provider file in provider_fd, which uses the first reserved word and must be zero without the flag. Guest faults ask the provider for each frame, and a revoke removes the range from the guest and from the VMM's mapping. A page that is not backed, or that is not RAM, exits with KVM_EXIT_MEMORY_FAULT. Read-only pages are mapped read only, and fallocate() is not supported.

guest_memfd maps itself into userspace from the same frames, so that a provider needs no fault handler. Pages marked NO_USER_MAP raise SIGBUS there.

USE_PROVIDER requires GUEST_MEMFD_FLAG_MMAP, so that the memory slot is gmem-only. An architecture opts in; x86 does so for VMs without private or encrypted memory, and other architectures refuse the flag for now. Native guest_memfd files now take the invalidate lock when a file is added and when a closing file is unbound.

---
 Documentation/virt/kvm/api.rst                |  45 ++-
 arch/x86/kvm/x86.c                            |  10 +
 include/linux/kvm_host.h                      |   4 +
 include/uapi/linux/kvm.h                      |  11 +-
 tools/include/uapi/linux/kvm.h                |  11 +-
 .../testing/selftests/kvm/guest_memfd_test.c  |   6 +
 virt/kvm/Kconfig                              |   1 +
 virt/kvm/guest_memfd.c                        | 265 +++++++++++++++++-
 8 files changed, 338 insertions(+), 15 deletions(-)
Documentation/virt/kvm/api.rst +35 -10
index a5f9ee92f43e..d9aaf8a76b59 100644
@@ -6431,7 +6431,9 @@ and cannot be resized  (guest_memfd files do however support PUNCH_HOLE).
   struct kvm_create_guest_memfd {
 	__u64 size;
 	__u64 flags;
-	__u64 reserved[6];
+	__s32 provider_fd;
+	__u32 pad;
+	__u64 reserved[5];
   };
 
 Conceptually, the inode backing a guest_memfd file represents physical memory,
@@ -6453,15 +6455,38 @@ a single guest_memfd file, but the bound ranges must not overlap).
 The capability KVM_CAP_GUEST_MEMFD_FLAGS enumerates the `flags` that can be
 specified via KVM_CREATE_GUEST_MEMFD.  Currently defined flags:
 
-  ============================ ================================================
-  GUEST_MEMFD_FLAG_MMAP        Enable using mmap() on the guest_memfd file
-                               descriptor.
-  GUEST_MEMFD_FLAG_INIT_SHARED Make all memory in the file shared during
-                               KVM_CREATE_GUEST_MEMFD (memory files created
-                               without INIT_SHARED will be marked private).
-                               Shared memory can be faulted into host userspace
-                               page tables. Private memory cannot.
-  ============================ ================================================
+  ============================= ================================================
+  GUEST_MEMFD_FLAG_MMAP         Enable using mmap() on the guest_memfd file
+                                descriptor.
+  GUEST_MEMFD_FLAG_INIT_SHARED  Make all memory in the file shared during
+                                KVM_CREATE_GUEST_MEMFD (memory files created
+                                without INIT_SHARED will be marked private).
+                                Shared memory can be faulted into host userspace
+                                page tables. Private memory cannot.
+  GUEST_MEMFD_FLAG_USE_PROVIDER Take the memory of the file from the memory
+                                provider behind `provider_fd`, instead of
+                                allocating it.  Requires
+                                GUEST_MEMFD_FLAG_MMAP.  Not supported for VMs
+                                with private or encrypted memory.
+  ============================= ================================================
+
+`pad` must be zero.  With GUEST_MEMFD_FLAG_USE_PROVIDER, `provider_fd` is a file
+handed out by a memory provider (see include/linux/mem_provider.h); without it,
+`provider_fd` must be zero.
+The provider decides which pages exist and what backs them, and can change
+this at any time.  The guest and any host mapping of the guest_memfd follow
+the change.  A guest access to a page that the provider does not back exits
+to userspace with KVM_EXIT_MEMORY_FAULT, and so does an access to a page that
+is not RAM.  A page that the provider marks read only is mapped read only for
+the guest.  fallocate() is not supported.  Only x86 VMs of type
+KVM_X86_DEFAULT_VM support GUEST_MEMFD_FLAG_USE_PROVIDER.
+
+mmap() of the guest_memfd maps the provider's pages into userspace on fault.
+An access raises SIGBUS if the provider does not back the page, if the page is
+not RAM, if the provider marks it as not to be mapped into userspace, or if it
+is a write to a read-only page.
+KVM's own accesses through the memslot's userspace address fail in the same
+cases.
 
 When the KVM MMU performs a PFN lookup to service a guest fault and the backing
 guest_memfd has the GUEST_MEMFD_FLAG_MMAP set, then the fault will always be
arch/x86/kvm/x86.c +10 -0
index afcac1042947..3669316f5712 100644
@@ -14124,6 +14124,16 @@ bool kvm_arch_supports_gmem_init_shared(struct kvm *kvm)
 	return !kvm_arch_has_private_mem(kvm);
 }
 
+/*
+ * Only VMs without encrypted memory: SEV and SEV-ES guests have no private
+ * memory in KVM's sense, but their memory would need reclaiming when a
+ * provider takes it back.
+ */
+bool kvm_arch_gmem_supports_provider(struct kvm *kvm)
+{
+	return !kvm || kvm->arch.vm_type == KVM_X86_DEFAULT_VM;
+}
+
 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_PREPARE
 int kvm_arch_gmem_prepare(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int max_order)
 {
include/linux/kvm_host.h +4 -0
index 7281d0e94121..3ea591642542 100644
@@ -832,11 +832,15 @@ static inline bool kvm_arch_has_private_mem(struct kvm *kvm)
 
 #ifdef CONFIG_KVM_GUEST_MEMFD
 bool kvm_arch_supports_gmem_init_shared(struct kvm *kvm);
+bool kvm_arch_gmem_supports_provider(struct kvm *kvm);
 
 static inline u64 kvm_gmem_get_supported_flags(struct kvm *kvm)
 {
 	u64 flags = GUEST_MEMFD_FLAG_MMAP;
 
+	if (kvm_arch_gmem_supports_provider(kvm))
+		flags |= GUEST_MEMFD_FLAG_USE_PROVIDER;
+
 	if (!kvm || kvm_arch_supports_gmem_init_shared(kvm))
 		flags |= GUEST_MEMFD_FLAG_INIT_SHARED;
 
include/uapi/linux/kvm.h +10 -1
index 419011097fa8..820448f82e22 100644
@@ -1654,11 +1654,20 @@ struct kvm_memory_attributes {
 #define KVM_CREATE_GUEST_MEMFD	_IOWR(KVMIO,  0xd4, struct kvm_create_guest_memfd)
 #define GUEST_MEMFD_FLAG_MMAP		(1ULL << 0)
 #define GUEST_MEMFD_FLAG_INIT_SHARED	(1ULL << 1)
+#define GUEST_MEMFD_FLAG_USE_PROVIDER	(1ULL << 2)
 
 struct kvm_create_guest_memfd {
 	__u64 size;
 	__u64 flags;
-	__u64 reserved[6];
+	/*
+	 * With GUEST_MEMFD_FLAG_USE_PROVIDER: a memory provider file whose
+	 * pages back this guest_memfd.  The provider may take
+	 * any range back at any time; the guest and every host mapping of
+	 * this guest_memfd follow.  Must be 0 otherwise.
+	 */
+	__s32 provider_fd;
+	__u32 pad;
+	__u64 reserved[5];
 };
 
 #define KVM_PRE_FAULT_MEMORY	_IOWR(KVMIO, 0xd5, struct kvm_pre_fault_memory)
tools/include/uapi/linux/kvm.h +10 -1
index d0c0c8605976..0f4d1dd0e931 100644
@@ -1644,11 +1644,20 @@ struct kvm_memory_attributes {
 #define KVM_CREATE_GUEST_MEMFD	_IOWR(KVMIO,  0xd4, struct kvm_create_guest_memfd)
 #define GUEST_MEMFD_FLAG_MMAP		(1ULL << 0)
 #define GUEST_MEMFD_FLAG_INIT_SHARED	(1ULL << 1)
+#define GUEST_MEMFD_FLAG_USE_PROVIDER	(1ULL << 2)
 
 struct kvm_create_guest_memfd {
 	__u64 size;
 	__u64 flags;
-	__u64 reserved[6];
+	/*
+	 * With GUEST_MEMFD_FLAG_USE_PROVIDER: a memory provider file whose
+	 * pages back this guest_memfd.  The provider may take
+	 * any range back at any time; the guest and every host mapping of
+	 * this guest_memfd follow.  Must be 0 otherwise.
+	 */
+	__s32 provider_fd;
+	__u32 pad;
+	__u64 reserved[5];
 };
 
 #define KVM_PRE_FAULT_MEMORY	_IOWR(KVMIO, 0xd5, struct kvm_pre_fault_memory)
tools/testing/selftests/kvm/guest_memfd_test.c +6 -0
index 2233d871a38f..91ff10ac6274 100644
@@ -405,6 +405,12 @@ static void test_guest_memfd_flags(struct kvm_vm *vm)
 
 	for (flag = BIT(0); flag; flag <<= 1) {
 		fd = __vm_create_guest_memfd(vm, page_size, flag);
+		/* USE_PROVIDER also needs MMAP and a provider file. */
+		if (flag == GUEST_MEMFD_FLAG_USE_PROVIDER && (flag & valid_flags)) {
+			TEST_ASSERT(fd < 0 && errno == EINVAL,
+				    "guest_memfd() with USE_PROVIDER alone should fail with EINVAL");
+			continue;
+		}
 		if (flag & valid_flags) {
 			TEST_ASSERT(fd >= 0,
 				    "guest_memfd() with flag '0x%lx' should succeed",
virt/kvm/Kconfig +1 -0
index 794976b88c6f..cfb6c4e51128 100644
@@ -105,6 +105,7 @@ config KVM_GENERIC_MEMORY_ATTRIBUTES
 
 config KVM_GUEST_MEMFD
        select XARRAY_MULTI
+       select MEM_PROVIDER
        bool
 
 config HAVE_KVM_ARCH_GMEM_PREPARE
virt/kvm/guest_memfd.c +262 -3

331 lines not on this page · raw message

#34 lore raw

PATCH 4/9 iommufd: Track the domains of pages that are not pinned

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

Memory provider pages, added in the next patch, are not pinned and can change under the domains that map them, as a dma-buf can. They need the same list of (area, domain) pairs that the dma-buf revoke uses.

Move that list from struct iopt_pages_dmabuf to struct iopt_pages.

No functional change.

---
 drivers/iommu/iommufd/io_pagetable.c | 24 +++++-----
 drivers/iommu/iommufd/io_pagetable.h | 33 +++++++++-----
 drivers/iommu/iommufd/pages.c        | 67 ++++++++++++++--------------
 3 files changed, 67 insertions(+), 57 deletions(-)
drivers/iommu/iommufd/io_pagetable.c +12 -12
index 24d4917105d9..bcd531acc9dd 100644
@@ -1008,14 +1008,14 @@ static void iopt_unfill_domain(struct io_pagetable *iopt,
 				WARN_ON(!area->storage_domain);
 			if (area->storage_domain == domain)
 				area->storage_domain = storage_domain;
-			if (iopt_is_dmabuf(pages)) {
+			if (iopt_pages_tracked(pages)) {
 				if (!iopt_dmabuf_revoked(pages))
 					iopt_area_unmap_domain(area, domain);
-				iopt_dmabuf_untrack_domain(pages, area, domain);
+				iopt_pages_untrack_domain(pages, area, domain);
 			}
 			mutex_unlock(&pages->mutex);
 
-			if (!iopt_is_dmabuf(pages))
+			if (!iopt_pages_tracked(pages))
 				iopt_area_unmap_domain(area, domain);
 		}
 		return;
@@ -1033,8 +1033,8 @@ static void iopt_unfill_domain(struct io_pagetable *iopt,
 		WARN_ON(area->storage_domain != domain);
 		area->storage_domain = NULL;
 		iopt_area_unfill_domain(area, pages, domain);
-		if (iopt_is_dmabuf(pages))
-			iopt_dmabuf_untrack_domain(pages, area, domain);
+		if (iopt_pages_tracked(pages))
+			iopt_pages_untrack_domain(pages, area, domain);
 		mutex_unlock(&pages->mutex);
 	}
 }
@@ -1065,15 +1065,15 @@ static int iopt_fill_domain(struct io_pagetable *iopt,
 			continue;
 
 		guard(mutex)(&pages->mutex);
-		if (iopt_is_dmabuf(pages)) {
-			rc = iopt_dmabuf_track_domain(pages, area, domain);
+		if (iopt_pages_tracked(pages)) {
+			rc = iopt_pages_track_domain(pages, area, domain);
 			if (rc)
 				goto out_unfill;
 		}
 		rc = iopt_area_fill_domain(area, domain);
 		if (rc) {
-			if (iopt_is_dmabuf(pages))
-				iopt_dmabuf_untrack_domain(pages, area, domain);
+			if (iopt_pages_tracked(pages))
+				iopt_pages_untrack_domain(pages, area, domain);
 			goto out_unfill;
 		}
 		if (!area->storage_domain) {
@@ -1102,8 +1102,8 @@ static int iopt_fill_domain(struct io_pagetable *iopt,
 			area->storage_domain = NULL;
 		}
 		iopt_area_unfill_domain(area, pages, domain);
-		if (iopt_is_dmabuf(pages))
-			iopt_dmabuf_untrack_domain(pages, area, domain);
+		if (iopt_pages_tracked(pages))
+			iopt_pages_untrack_domain(pages, area, domain);
 		mutex_unlock(&pages->mutex);
 	}
 	return rc;
@@ -1315,7 +1315,7 @@ static int iopt_area_split(struct iopt_area *area, unsigned long iova)
 		return -EBUSY;
 
 	/* Maintaining the domains_itree below is a bit complicated */
-	if (iopt_is_dmabuf(pages))
+	if (iopt_pages_tracked(pages))
 		return -EOPNOTSUPP;
 
 	if (new_start & (alignment - 1) ||
drivers/iommu/iommufd/io_pagetable.h +22 -11
index 887ed94474c7..5389227eb6ff 100644
@@ -70,15 +70,14 @@ void iopt_area_unfill_domain(struct iopt_area *area, struct iopt_pages *pages,
 void iopt_area_unmap_domain(struct iopt_area *area,
 			    struct iommu_domain *domain);
 
-int iopt_dmabuf_track_domain(struct iopt_pages *pages, struct iopt_area *area,
-			     struct iommu_domain *domain);
-void iopt_dmabuf_untrack_domain(struct iopt_pages *pages,
-				struct iopt_area *area,
-				struct iommu_domain *domain);
-int iopt_dmabuf_track_all_domains(struct iopt_area *area,
-				  struct iopt_pages *pages);
-void iopt_dmabuf_untrack_all_domains(struct iopt_area *area,
-				     struct iopt_pages *pages);
+int iopt_pages_track_domain(struct iopt_pages *pages, struct iopt_area *area,
+			    struct iommu_domain *domain);
+void iopt_pages_untrack_domain(struct iopt_pages *pages, struct iopt_area *area,
+			       struct iommu_domain *domain);
+int iopt_pages_track_all_domains(struct iopt_area *area,
+				 struct iopt_pages *pages);
+void iopt_pages_untrack_all_domains(struct iopt_area *area,
+				    struct iopt_pages *pages);
 
 static inline unsigned long iopt_area_index(struct iopt_area *area)
 {
@@ -194,7 +193,8 @@ enum iopt_address_type {
 	IOPT_ADDRESS_DMABUF,
 };
 
-struct iopt_pages_dmabuf_track {
+/* An area of the pages mapped into a domain, for pages that are not pinned. */
+struct iopt_pages_track {
 	struct iommu_domain *domain;
 	struct iopt_area *area;
 	struct list_head elm;
@@ -205,7 +205,6 @@ struct iopt_pages_dmabuf {
 	struct phys_vec phys;
 	/* 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
@@ -253,6 +252,12 @@ struct iopt_pages {
 	struct rb_root_cached access_itree;
 	/* Of iopt_area::pages_node */
 	struct rb_root_cached domains_itree;
+	/*
+	 * Of iopt_pages_track::elm.  Pages that are not pinned can change
+	 * under the domains that map them, so every (area, domain) that maps
+	 * them is listed here.  See iopt_pages_tracked().
+	 */
+	struct list_head tracker;
 };
 
 static inline bool iopt_is_dmabuf(struct iopt_pages *pages)
@@ -262,6 +267,12 @@ static inline bool iopt_is_dmabuf(struct iopt_pages *pages)
 	return pages->type == IOPT_ADDRESS_DMABUF;
 }
 
+/* The pages are not pinned, so their domains are tracked in pages->tracker. */
+static inline bool iopt_pages_tracked(struct iopt_pages *pages)
+{
+	return iopt_is_dmabuf(pages);
+}
+
 static inline bool iopt_dmabuf_revoked(struct iopt_pages *pages)
 {
 	lockdep_assert_held(&pages->mutex);
drivers/iommu/iommufd/pages.c +33 -34

176 lines not on this page · raw message

#35 lore raw

PATCH 5/9 iommufd: Map memory provider files

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

IOMMU_IOAS_MAP_FILE pins the pages it maps, which cannot work for a memory provider file: the frames may have no struct page, and the provider can take any of them back at any time.

Accept a provider file. iommufd neither pins nor accounts its pages. It asks the provider for each frame when it fills a domain, and on a revoke it unmaps the range in every domain and maps what the provider backs now. A device that accesses the range in between faults.

Each frame gets a PAGE_SIZE entry, so a partial revoke never splits a large IOMMU page. Holes stay unmapped, read-only pages are mapped without IOMMU_WRITE, and MMIO pages with IOMMU_MMIO. A provider that returns frame 0 makes the map fail with -EINVAL.

A revoke would race a dirty bitmap read and lose the dirty bits of the range, so provider pages and a dirty tracking domain cannot share an
IOAS: whichever comes second fails with -EOPNOTSUPP. A provider mapping cannot be split by a partial unmap, and in-kernel accesses to it are refused.

---
 drivers/iommu/iommufd/Kconfig        |   1 +
 drivers/iommu/iommufd/io_pagetable.c |  13 +-
 drivers/iommu/iommufd/io_pagetable.h |  23 ++-
 drivers/iommu/iommufd/pages.c        | 273 ++++++++++++++++++++++++++-
 include/uapi/linux/iommufd.h         |  11 +-
 5 files changed, 315 insertions(+), 6 deletions(-)
drivers/iommu/iommufd/Kconfig +1 -0
index 455bac0351f2..65d71e28c12b 100644
@@ -8,6 +8,7 @@ config IOMMUFD
 	select INTERVAL_TREE
 	select INTERVAL_TREE_SPAN_ITER
 	select IOMMU_API
+	select MEM_PROVIDER
 	default n
 	help
 	  Provides /dev/iommu, the user API to control the IOMMU subsystem as
drivers/iommu/iommufd/io_pagetable.c +11 -2
index bcd531acc9dd..3eca7f4f83d3 100644
@@ -217,6 +217,7 @@ static int iopt_insert_area(struct io_pagetable *iopt, struct iopt_area *area,
 		return -EPERM;
 
 	area->iommu_prot = iommu_prot;
+	area->provider = iopt_is_provider(pages);
 	area->page_offset = start_byte % PAGE_SIZE;
 	if (area->page_offset & (iopt->iova_alignment - 1))
 		return -EINVAL;
@@ -289,6 +290,9 @@ static int iopt_alloc_area_pages(struct io_pagetable *iopt,
 		case IOPT_ADDRESS_DMABUF:
 			start = elm->start_byte + elm->pages->dmabuf.start;
 			break;
+		case IOPT_ADDRESS_PROVIDER:
+			start = elm->start_byte + elm->pages->provider.start;
+			break;
 		}
 		rc = iopt_alloc_iova(iopt, dst_iova, start, length);
 		if (rc)
@@ -515,8 +519,13 @@ int iopt_map_file_pages(struct iommufd_ctx *ictx, struct io_pagetable *iopt,
 		if (!file)
 			return -EBADF;
 
-		pages = iopt_alloc_file_pages(file, start_byte, start, length,
-					      iommu_prot & IOMMU_WRITE);
+		/* A memory provider file, or else a memfd. */
+		pages = iopt_alloc_provider_pages(file, start, length,
+						  iommu_prot & IOMMU_WRITE);
+		if (PTR_ERR(pages) == -ENODEV)
+			pages = iopt_alloc_file_pages(file, start_byte, start,
+						      length,
+						      iommu_prot & IOMMU_WRITE);
 		fput(file);
 		if (IS_ERR(pages))
 			return PTR_ERR(pages);
drivers/iommu/iommufd/io_pagetable.h +22 -1
index 5389227eb6ff..3f65380e91d2 100644
@@ -8,6 +8,7 @@
 #include <linux/dma-buf.h>
 #include <linux/interval_tree.h>
 #include <linux/kref.h>
+#include <linux/mem_provider.h>
 #include <linux/mutex.h>
 #include <linux/xarray.h>
 
@@ -48,6 +49,8 @@ struct iopt_area {
 	/* IOMMU_READ, IOMMU_WRITE, etc */
 	int iommu_prot;
 	bool prevent_access : 1;
+	/* The pages come from a memory provider and may have holes */
+	bool provider : 1;
 	unsigned int num_accesses;
 	unsigned int num_locks;
 };
@@ -191,6 +194,7 @@ enum iopt_address_type {
 	IOPT_ADDRESS_USER = 0,
 	IOPT_ADDRESS_FILE,
 	IOPT_ADDRESS_DMABUF,
+	IOPT_ADDRESS_PROVIDER,
 };
 
 /* An area of the pages mapped into a domain, for pages that are not pinned. */
@@ -214,6 +218,12 @@ struct iopt_pages_dmabuf {
 	bool is_cpu_ram;
 };
 
+struct iopt_pages_provider {
+	struct mem_provider_attachment att;
+	/* Byte offset in the provider file, always PAGE_SIZE aligned */
+	unsigned long start;
+};
+
 /*
  * This holds a pinned page list for multiple areas of IO address space. The
  * pages always originate from a linear chunk of userspace VA. Multiple
@@ -243,6 +253,8 @@ struct iopt_pages {
 		};
 		/* IOPT_ADDRESS_DMABUF */
 		struct iopt_pages_dmabuf dmabuf;
+		/* IOPT_ADDRESS_PROVIDER */
+		struct iopt_pages_provider provider;
 	};
 	bool writable:1;
 	u8 account_mode;
@@ -267,10 +279,15 @@ static inline bool iopt_is_dmabuf(struct iopt_pages *pages)
 	return pages->type == IOPT_ADDRESS_DMABUF;
 }
 
+static inline bool iopt_is_provider(struct iopt_pages *pages)
+{
+	return pages->type == IOPT_ADDRESS_PROVIDER;
+}
+
 /* The pages are not pinned, so their domains are tracked in pages->tracker. */
 static inline bool iopt_pages_tracked(struct iopt_pages *pages)
 {
-	return iopt_is_dmabuf(pages);
+	return iopt_is_dmabuf(pages) || iopt_is_provider(pages);
 }
 
 static inline bool iopt_dmabuf_revoked(struct iopt_pages *pages)
@@ -292,6 +309,10 @@ struct iopt_pages *iopt_alloc_dmabuf_pages(struct iommufd_ctx *ictx,
 					   unsigned long start_byte,
 					   unsigned long start,
 					   unsigned long length, bool writable);
+struct iopt_pages *iopt_alloc_provider_pages(struct file *file,
+					     unsigned long start,
+					     unsigned long length,
+					     bool writable);
 void iopt_release_pages(struct kref *kref);
 static inline void iopt_put_pages(struct iopt_pages *pages)
 {
drivers/iommu/iommufd/pages.c +271 -2

339 lines not on this page · raw message

include/uapi/linux/iommufd.h +10 -1
index 0425d452d41e..b4500fc21368 100644
@@ -224,7 +224,7 @@ struct iommu_ioas_map {
  * @size: sizeof(struct iommu_ioas_map_file)
  * @flags: same as for iommu_ioas_map
  * @ioas_id: same as for iommu_ioas_map
- * @fd: the memfd or supported dma-buf file to map
+ * @fd: the memfd, memory provider file or supported dma-buf file to map
  * @start: byte offset from start of the file to map from
  * @length: same as for iommu_ioas_map
  * @iova: same as for iommu_ioas_map
@@ -235,6 +235,15 @@ struct iommu_ioas_map {
  * VFIO PCI dma-bufs exported through VFIO_DEVICE_FEATURE_DMA_BUF, and
  * other dma-bufs may be rejected. All other arguments and semantics match
  * those of IOMMU_IOAS_MAP.
+ *
+ * A file from a memory provider is also accepted; @start must then be
+ * page aligned. Its pages are not pinned. The provider may change the memory
+ * behind any range at any time, and the mapping follows: pages that the
+ * provider does not back are left unmapped, read-only pages are mapped
+ * without write permission, and device memory is mapped as MMIO. A device
+ * access to a page that is being changed, or that is not backed, faults. Such
+ * a mapping cannot be split by a partial unmap, and in-kernel accesses to it
+ * are refused. It is not supported in an IOAS with a dirty tracking domain.
  */
 struct iommu_ioas_map_file {
 	__u32 size;
#36 lore raw

PATCH 6/9 iommufd/selftest: Add mock-domain IOVA queries

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

A test of memory that can be taken back or replaced does not know in advance which frame a device reaches. IOMMU_TEST_OP_MD_CHECK_MAP only compares against a known buffer.

Add MD_CHECK_MAPPED, which checks that a range is fully mapped or fully unmapped, and MD_IOVA_TO_PHYS, which returns the frame behind an IOVA, or 0 if it is unmapped. Both refuse an IOVA outside the domain's aperture.

Both hold domains_rwsem for writing so that a userspace unmap cannot free a page-table level during the walk.

---
 drivers/iommu/iommufd/iommufd_test.h |  16 ++++
 drivers/iommu/iommufd/selftest.c     | 109 +++++++++++++++++++++++++++
 2 files changed, 125 insertions(+)
drivers/iommu/iommufd/iommufd_test.h +16 -0
index 52b78cbcc920..28fd9c43edc4 100644
@@ -31,6 +31,8 @@ enum {
 	IOMMU_TEST_OP_PASID_CHECK_HWPT,
 	IOMMU_TEST_OP_DMABUF_GET,
 	IOMMU_TEST_OP_DMABUF_REVOKE,
+	IOMMU_TEST_OP_MD_CHECK_MAPPED,
+	IOMMU_TEST_OP_MD_IOVA_TO_PHYS,
 };
 
 enum {
@@ -193,6 +195,20 @@ struct iommu_test_cmd {
 			__s32 dmabuf_fd;
 			__u32 revoked;
 		} dmabuf_revoke;
+		struct {
+			/*
+			 * 1: every page in [iova, iova+length) must be mapped;
+			 * 0: none of them may be. Mixed is an error.
+			 */
+			__u32 mapped;
+			__u32 __reserved;
+			__aligned_u64 iova;
+			__aligned_u64 length;
+		} check_mapped;
+		struct {
+			__aligned_u64 iova;
+			__aligned_u64 out_phys;	/* 0 if unmapped */
+		} iova_to_phys;
 	};
 	__u32 last;
 };
drivers/iommu/iommufd/selftest.c +109 -0

121 lines not on this page · raw message

#37 lore raw

PATCH 7/9 iommufd/selftest: Add a mock memory provider

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

The provider path of IOMMU_IOAS_MAP_FILE needs a provider to test against.

Add a mock provider whose pages can be made holes, read only, MMIO or another shared frame, with a revoke after each change. Test that holes stay unmapped, that a revoke changes only its range, that new domains see the current state, and that provider pages and dirty tracking domains cannot share an IOAS.

---
 drivers/iommu/iommufd/iommufd_test.h          |  20 ++
 drivers/iommu/iommufd/selftest.c              | 177 ++++++++++++++++++
 tools/testing/selftests/iommu/iommufd.c       | 119 ++++++++++++
 tools/testing/selftests/iommu/iommufd_utils.h |  64 +++++++
 4 files changed, 380 insertions(+)
drivers/iommu/iommufd/iommufd_test.h +20 -0
index 28fd9c43edc4..5e5023dc8070 100644
@@ -33,6 +33,17 @@ enum {
 	IOMMU_TEST_OP_DMABUF_REVOKE,
 	IOMMU_TEST_OP_MD_CHECK_MAPPED,
 	IOMMU_TEST_OP_MD_IOVA_TO_PHYS,
+	IOMMU_TEST_OP_PROVIDER_GET,
+	IOMMU_TEST_OP_PROVIDER_SET,
+};
+
+/* Page states of the mock memory provider, IOMMU_TEST_OP_PROVIDER_SET */
+enum {
+	MOCK_PROVIDER_BACKED = 0,
+	MOCK_PROVIDER_HOLE,
+	MOCK_PROVIDER_READONLY,
+	MOCK_PROVIDER_OTHER,
+	MOCK_PROVIDER_MMIO,
 };
 
 enum {
@@ -209,6 +220,15 @@ struct iommu_test_cmd {
 			__aligned_u64 iova;
 			__aligned_u64 out_phys;	/* 0 if unmapped */
 		} iova_to_phys;
+		struct {
+			__u32 length;
+		} provider_get;
+		struct {
+			__s32 fd;
+			__u32 state;
+			__aligned_u64 offset;
+			__aligned_u64 length;
+		} provider_set;
 	};
 	__u32 last;
 };
drivers/iommu/iommufd/selftest.c +177 -0

195 lines not on this page · raw message

tools/testing/selftests/iommu/iommufd.c +119 -0

125 lines not on this page · raw message

tools/testing/selftests/iommu/iommufd_utils.h +64 -0

70 lines not on this page · raw message

#38 lore raw

PATCH 8/9 samples/kvm: Add a memory provider sample

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

The memory provider interface has no in-tree provider that a VMM can use.

Add mem_provider_sample. It lends a region, either a fixed range given with addr= and len= or memory from alloc_contig_pages(), as child files that a VMM passes to both guest_memfd and iommufd. A control device moves pages between children, takes them back and makes them read only, and every change revokes the range. It uses no KVM, dma-buf or iommufd symbol.

The fixed range is not System RAM, so the sample keeps a write-back memremap() of it while a file over it may be mapped into userspace. Without it, PAT would make the range uncached on x86, and the VMM's mapping would be uncached while the guest's is write-back. The sample is x86 only, as guest_memfd accepts providers only there.

David's gmem_provider sample is unchanged.

---
 MAINTAINERS                       |   1 +
 samples/Kconfig                   |  17 +
 samples/Makefile                  |   1 +
 samples/kvm/Makefile              |   1 +
 samples/kvm/mem_provider_sample.c | 855 ++++++++++++++++++++++++++++++
 samples/kvm/mem_provider_sample.h | 135 +++++
 6 files changed, 1010 insertions(+)
 create mode 100644 samples/kvm/mem_provider_sample.c
 create mode 100644 samples/kvm/mem_provider_sample.h
MAINTAINERS +1 -0
index 6cab075a3ff7..b6b47e132e16 100644
@@ -17366,6 +17366,7 @@ L:	[email protected]
 S:	Maintained
 F:	include/linux/mem_provider.h
 F:	mm/mem_provider.c
+F:	samples/kvm/mem_provider_sample.*
 
 MEMORY TECHNOLOGY DEVICES (MTD)
 M:	Miquel Raynal <[email protected]>
samples/Kconfig +17 -0
index d26a03dea072..e4c4aface3ab 100644
@@ -344,6 +344,23 @@ config SAMPLE_KVM_GMEM_PROVIDER
 
 	  If unsure, say N.
 
+config SAMPLE_KVM_MEM_PROVIDER
+	tristate "Build sample memory provider -- loadable module only"
+	depends on MEM_PROVIDER && CONTIG_ALLOC && X86_64 && m
+	help
+	  This builds a sample memory provider (include/linux/mem_provider.h).
+	  Its files can back a guest_memfd and be mapped by iommufd.  Loaded
+	  with addr= and len=, it lends a fixed physical range that has no
+	  struct page, for example memory hidden with memmap= on the command
+	  line.  Without them, it allocates a contiguous region with
+	  alloc_contig_pages().
+
+	  It shows how a memory owner moves pages between VMs, takes them
+	  back or makes them read only, and how guest_memfd and iommufd
+	  follow each change.
+
+	  If unsure, say N.
+
 endif # SAMPLES
 
 config HAVE_SAMPLE_FTRACE_DIRECT
samples/Makefile +1 -0
index e85397e5e34f..0565141d1f45 100644
@@ -38,6 +38,7 @@ 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_KVM_MEM_PROVIDER)	+= kvm/
 obj-$(CONFIG_SAMPLE_CORESIGHT_SYSCFG)	+= coresight/
 obj-$(CONFIG_SAMPLE_FPROBE)		+= fprobe/
 obj-$(CONFIG_SAMPLES_RUST)		+= rust/
samples/kvm/Makefile +1 -0
index dcad6e53ea78..a885b5313804 100644
@@ -1,2 +1,3 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_SAMPLE_KVM_GMEM_PROVIDER) += gmem_provider.o
+obj-$(CONFIG_SAMPLE_KVM_MEM_PROVIDER) += mem_provider_sample.o
samples/kvm/mem_provider_sample.c new file +855 -0

855 lines not on this page · raw message

samples/kvm/mem_provider_sample.h new file +135 -0

135 lines not on this page · raw message

#39 lore raw

PATCH 9/9 KVM: selftests: Test a memory provider shared by KVM and iommufd

In reply to Fred Griffoul

From: Fred Griffoul <[email protected]>

Test that guest, host and device mappings of one provider file follow the provider's changes.

Two VMs get child files of the sample provider, each passed to guest_memfd and to an iommufd mock domain. The test moves a range between them, donates and reclaims pages, and makes a page read only. After each change it checks the guest, a host mapping and the device mapping. Pages are mapped on the host before a change, so the test checks that the revoke zaps them.

---
 tools/testing/selftests/kvm/Makefile.kvm      |   1 +
 .../selftests/kvm/x86/mem_provider_test.c     | 582 ++++++++++++++++++
 2 files changed, 583 insertions(+)
 create mode 100644 tools/testing/selftests/kvm/x86/mem_provider_test.c
tools/testing/selftests/kvm/Makefile.kvm +1 -0
index 4d7082448cea..ccee373b4c13 100644
@@ -84,6 +84,7 @@ TEST_GEN_PROGS_x86 += x86/gmem_provider_revoke_test
 TEST_GEN_PROGS_x86 += x86/gmem_provider_readonly_test
 TEST_GEN_PROGS_x86 += x86/gmem_provider_iommufd_test
 TEST_GEN_PROGS_x86 += x86/gmem_provider_vfio_test
+TEST_GEN_PROGS_x86 += x86/mem_provider_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/x86/mem_provider_test.c new file +582 -0

582 lines not on this page · raw message

#40 lore raw

Re: [RFC PATCH 0/9] mm: Memory providers for guest_memfd and iommufd

In reply to Fred Griffoul
Quoted 19 lines · Fred Griffoul

From: Fred Griffoul <[email protected]>

Some drivers manage RAM outside the page allocator: a carve-out, device memory, or memory that a host component moves between VMs while they run. This memory often has no struct page. The driver wants to lend pages to a VM and to its devices, and to take any of them back later.

David Woodhouse's series "KVM: Allow alternative providers of guest_memfd backed by PFNMAP memory" lets such a driver back a guest_memfd through struct kvm_gmem_ops:

https://lore.kernel.org/kvm/[email protected]/

That covers the guest, but not the VM's devices, which his cover letter left as an open question. This series adds a small interface in
mm: the driver that owns the memory becomes a provider, and the code that maps it attaches as a consumer. There are two consumers, a guest_memfd backend and IOMMU_IOAS_MAP_FILE in iommufd.

Quoted 4 lines

The series is on top of David's v2 (base 0e35b9b6ec0f). Patch 1 was part of the earlier dma-buf RFC. The provider backend depends on it, so this series carries it.

I have been working on something similar for confidential computing use cases. There is likely some overlap between this series and what I posted at [1].

I have not reviewed this series in detail yet, but I will compare the two approaches and identify what can be shared between the use cases. Please let me know how you would like to proceed.

[1] https://lore.kernel.org/all/[email protected]/

-aneesh

#41 lore raw

Re: [RFC PATCH 0/9] mm: Memory providers for guest_memfd and iommufd

Quoted 9 lines · Aneesh Kumar K.V

I have been working on something similar for confidential computing use cases. There is likely some overlap between this series and what I posted at [1].

I have not reviewed this series in detail yet, but I will compare the two approaches and identify what can be shared between the use cases. Please let me know how you would like to proceed.

[1] https://lore.kernel.org/all/[email protected]/

Thanks for the pointer. I read your series, and Ackerley's resource fd RFC that it builds on. The use cases differ, but the interfaces overlap, and it would be good to agree on the common parts.

All three series add a flag and an fd to KVM_CREATE_GUEST_MEMFD. I think one resource_fd is enough, with guest_memfd picking the backend from the kind of file it gets. I am happy to drop provider_fd for Ackerley's flag and field. We also find the provider from the file in three different ways; I would like us to pick one, preferably without a registry.

The main constraint on our side is that the provider stays the authority on which frame backs which page: it moves pages between VMs and has to survive a live update. What would not work for us is guest_memfd becoming the primary manager of PFN memory, as Ackerley suggests. Your get_pfn() leaves VFIO as the authority for the BAR, so I think we agree there.

You refuse dma-buf exports while guest_memfd is attached. That is roughly what the memory provider interface is for: one owner, several users, and one revoke that reaches all of them. A BAR exposed as a provider file could be mapped by both guest_memfd and iommufd.

I plan to change the revoke anyway, because iommufd must not leave the device with a hole: it should replace mappings in place instead of unmapping and remapping. Would that fit your case? I suspect it depends on locking, for example whether you have to revoke while holding memory_lock.

Shared/private state and the conversion hooks would stay in guest_memfd and the arch code, as in your series.

Does that sound reasonable? Ackerley, David, any thoughts?

Thanks,
Fred

#42 lore raw

Re: [RFC PATCH 0/9] mm: Memory providers for guest_memfd and iommufd

Quoted 6 lines · Fred Griffoul

I plan to change the revoke anyway, because iommufd must not leave the device with a hole: it should replace mappings in place instead of unmapping and remapping. Would that fit your case? I suspect it depends on locking, for example whether you have to revoke while holding memory_lock.

I was keeping that hack *entirely* separate from the guest_memfd work.

That's a quirk on the IOAS in iommufd: "whenever you unmap, put *this* page in its place instead". It doesn't belong anywhere near what we're doing here, ideally.

I even talked to Jason about it about it at LPC, and he didn't hurt me. If we implement a hitless¹ REPLACE operation then the scratch-page ends up being a fairly trivial thing to redirect UNMAP to REPLACE (the tricksy detail being that it uses the *same* scratch page for every IOVA in the range).

¹ why do we call it that? Shouldn't it be 'missless'?

#43 lore raw

Re: [RFC PATCH 0/9] mm: Memory providers for guest_memfd and iommufd

In reply to Fred Griffoul
Quoted 15 lines · Fred Griffoul
Quoted 9 lines · Aneesh Kumar K.V

I have been working on something similar for confidential computing use cases. There is likely some overlap between this series and what I posted at [1].

I have not reviewed this series in detail yet, but I will compare the two approaches and identify what can be shared between the use cases. Please let me know how you would like to proceed.

[1] https://lore.kernel.org/all/[email protected]/

Thanks for the pointer. I read your series, and Ackerley's resource fd RFC that it builds on. The use cases differ, but the interfaces overlap, and it would be good to agree on the common parts.

Quoted 7 lines

All three series add a flag and an fd to KVM_CREATE_GUEST_MEMFD. I think one resource_fd is enough, with guest_memfd picking the backend from the kind of file it gets. I am happy to drop provider_fd for Ackerley's flag and field. We also find the provider from the file in three different ways; I would like us to pick one, preferably without a registry.

David brought up many good points at the LPC discussion, I need to wrap my head around your model. I'll look closely at Fred and David's versions this week.

These thoughts are just from reading this email, hope to get more clarification :)

Quoted 2 lines

The main constraint on our side is that the provider stays the authority on which frame backs which page:

Wait, is there some magic done to make struct pages represent different frames, as in PFNs? In your model, the struct page <=> PFN mapping doesn't stay constant?

Quoted 1 line

it moves pages between VMs

Do multiple VMs map the same physical memory at the same time, or is it a move like below?

I'm thinking that if guest_memfd wraps your provider, then your provider can issue a revocation to guest_memfd (ctrl-f for kvm_gmem_provider_revoke in [1]) on the move source guest_memfd inode, then wait for an allocation request from the move target guest_memfd inode.

[1] https://lpc.events/event/20/contributions/2551/attachments/2047/4693/lpc-2026-gmem-other-backends.pdf

Quoted 2 lines

and has to
survive a live update.

guest_memfd is going to support preservation [2]. Tarun's series just preserves memory from guest_memfd's default provider (buddy allocator) now. For your provider, I imagine the preservation flow would preserve whatever metadata in guest_memfd (like the attributes in the maple tree) and then go on to notify the provider to preserve some range of PFNs (or folios). Your provider would then basically do nothing, since those PFNs already survive a live update.

[2] https://lore.kernel.org/all/[email protected]/

Quoted 10 lines

What would not work for us is guest_memfd
becoming the primary manager of PFN memory, as Ackerley suggests. Your get_pfn() leaves VFIO as the authority for the BAR, so I think we agree there.

You refuse dma-buf exports while guest_memfd is attached. That is roughly what the memory provider interface is for: one owner, several users, and one revoke that reaches all of them. A BAR exposed as a provider file could be mapped by both guest_memfd and iommufd.

Will read the rest of this series and reply again :)

Quoted 13 lines

I plan to change the revoke anyway, because iommufd must not leave the device with a hole: it should replace mappings in place instead of unmapping and remapping. Would that fit your case? I suspect it depends on locking, for example whether you have to revoke while holding memory_lock.

Shared/private state and the conversion hooks would stay in guest_memfd and the arch code, as in your series.

Does that sound reasonable? Ackerley, David, any thoughts?

Thanks,
Fred

#44 lore raw

Re: [RFC PATCH 0/9] mm: Memory providers for guest_memfd and iommufd

Quoted 3 lines · Ackerley Tng

Wait, is there some magic done to make struct pages represent different frames, as in PFNs? In your model, the struct page <=> PFN mapping doesn't stay constant?

No, our memory has no struct page: it is a carve-out hidden from the host with memmap=. I meant the mapping from guest_memfd file offset to PFN. The PFNs never change, only which file and offset they back.

Quoted 2 lines

Do multiple VMs map the same physical memory at the same time, or is it a move like below?

Mostly moves: a page has one owner at a time. There is also a share, where a parent keeps a range and gives a child a view of it, so two VMs can map the same frames for a while.

Quoted 5 lines

I'm thinking that if guest_memfd wraps your provider, then your provider can issue a revocation to guest_memfd (ctrl-f for kvm_gmem_provider_revoke in [1]) on the move source guest_memfd inode, then wait for an allocation request from the move target guest_memfd inode.

For the guest, this series works the same way: the provider revokes the range on the source, and the target's next guest fault asks the provider for the frame. Devices are different, because a device may not support faults. So the provider also revokes the range on the target once it owns the frames, and iommufd maps them right away. In other words, a revoke means that the frames behind a range changed, whether they went away or arrived.

Quoted 7 lines

guest_memfd is going to support preservation [2]. Tarun's series just preserves memory from guest_memfd's default provider (buddy allocator) now. For your provider, I imagine the preservation flow would preserve whatever metadata in guest_memfd (like the attributes in the maple tree) and then go on to notify the provider to preserve some range of PFNs (or folios). Your provider would then basically do nothing, since those PFNs already survive a live update.

Yes, that would work for us, as long as guest_memfd does not also have to save the offset to PFN layout: the provider keeps it across the update, and guest_memfd can ask again afterwards.

Thanks,
Fred

#45 lore raw

Re: [RFC PATCH 0/9] mm: Memory providers for guest_memfd and iommufd

Quoted 5 lines · Fred Griffoul

 Devices are different, because a device may not support faults. So the provider also revokes the range on the target once it owns the frames, and iommufd maps them right away. In other words, a revoke means that the frames behind a range changed, whether they went away or arrived.

That would map to the IOMMUFD 'REPLACE' operation that hitlessly replaces a PTE, but does anyone actually need that?

As I said, assume that the "crappy devices can't take faults and need a scratch patch" issue is dealt with *elsewhere* and not relevant to the guest_memfd/memprovider work. That's purely a quirk on a given IOAS within iommufd.

#46 lore raw

Re: [RFC PATCH 0/9] mm: Memory providers for guest_memfd and iommufd

Quoted 9 lines · David Woodhouse
Quoted 5 lines · Fred Griffoul

Devices are different, because a device may not support
faults. So the provider also revokes the range on the target once it owns the frames, and iommufd maps them right away. In other words, a revoke means that the frames behind a range changed, whether they went away or arrived.

That would map to the IOMMUFD 'REPLACE' operation that hitlessly replaces a PTE, but does anyone actually need that?

No, not on the target. Before the move the child has nothing mapped in that range, so when the frames arrive iommufd just maps them. That is a plain map, not a REPLACE.

Quoted 4 lines

As I said, assume that the "crappy devices can't take faults and need a scratch patch" issue is dealt with *elsewhere* and not relevant to the guest_memfd/memprovider work. That's purely a quirk on a given IOAS within iommufd.

Agreed. The replace is only needed on the source, where the frames go away and a device that cannot fault must see the scratch page instead. With that quirk on the IOAS, iommufd does it, and the provider does not need to know about it.

Thanks,
Fred

#47 lore raw

Re: [RFC PATCH 0/9] mm: Memory providers for guest_memfd and iommufd

In reply to Fred Griffoul

Hey David/Fred,

I took some time to read the patches, hope I got everything :) The biggest difference between your approach and mine is who (provider or guest_memfd) manages the zapping across all the users.

The memory users here are

1. [KVM] The guest (KVM manages the stage 2 page tables)
2. [IOMMU] The IOMMU (iommufd manages the stage 2 page tables)
3. [USERSPACE] Host userspace (guest_memfd handles faults, I guess you could say core mm manages host userspace page tables)
4. [DIRECTMAP] Kernel direct map. Your provider already provides PFNs that are presumably not in the direct map. For other providers, the direct map is another mapping that may need to be zapped on private/shared conversions. (Listing this here for completeness, I think this should be tackled separately.)

I'll use [LABEL] to illustrate the way notifications flow in your approach vs mine.

When the provider wants to revoke the page, the notifications/function calls flow this way, the last [ENTITY] in the chain actually does the zapping.

+ [PROVIDER] -> [KVM]
+ [PROVIDER] -> [DMABUF] -> [IOMMU]
+ [PROVIDER] -> [GUEST_MEMFD] -> [USERSPACE] (AFAICT this was not implemented in the RFC.)

That's when the provider wants to revoke the page. IIUC guest_memfd conversions was not illustrated in the RFC: what happens on a shared -> private conversion?

+ [KVM]: Zap only shared pages, keep private pages mapped.
+ [IOMMU]:
+ Before Confidential IO: so far, IOMMU mappings are mapped indirectly via [USERSPACE] mappings. guest_memfd zaps [USERSPACE] mappings, then checks refcounts to ensure no other mappings (which includes IOMMU). See __kvm_gmem_set_attributes() on kvm-x86/coco [2].
+ With Confidential IO: shared IOMMU mapping need to be zapped, keep mappings of private pages.
+ [USERSPACE]: Zap all mappings on shared->private conversions.
+ [DIRECTMAP]: Can zap these mappings (not implemented yet, but discussed in the context of Direct Map Removal support for guest_memfd [3])

To have the conversions work, in your model, we'd need to do

+ [GUEST_MEMFD] -> [PROVIDER] -> [KVM] (zap only shared pages)
+ [GUEST_MEMFD] -> [PROVIDER] -> [DMABUF] -> [IOMMU] (zap only shared pages)
+ [GUEST_MEMFD] -> [USERSPACE] (IIUC the provider doesn't directly allow mapping to userspace, also in your approach the provider pretty much replaces all the innards of guest_memfd anyway, hence I'm showing this as gmem going direct to zap userspace)

With my proposal [1], we could do

+ [GUEST_MEMFD] -> [KVM] (zap only shared pages, implemented in [2])
+ [GUEST_MEMFD] -> [IOMMU] (zap only shared pages)
+ [GUEST_MEMFD] -> [USERSPACE] (implemented in [2])
+ [GUEST_MEMFD] -> [DIRECTMAP] (future)

In my proposal, I agree with you completely that the provider must be allowed to revoke memory. Using the sample in this RFC, gmem_fd_ioctl() called with !GMEM_PROVIDER_SET_PRESENT is where the provider wants to revoke memory, and the revocation in my model would look like

[PROVIDER] -> [GUEST_MEMFD]

and [GUEST_MEMFD] would then fan it out to [KVM], [IOMMU], [USERSPACE] and [DIRECTMAP].

The [GUEST_MEMFD] -> [IOMMU] is missing from my proposal because I was seeing that as a separate patch series. I think what we want is to have IOMMU_IOAS_MAP_FILE be able to accept a guest_memfd file. Currently, during the mapping process(), memfd_pin_folios() is used, which has this check

	if (!shmem_file(memfd) && !is_file_hugepages(memfd))
		return -EINVAL;

that disqualifies guest_memfd. Refcounting won't work for guest_memfd() folios because of conversions (see kvm_gmem_has_outstanding_references at [4]). The implementation I have in mind is to have the the iommufd instance be tracked in guest_memfd during the pinning process, and that's the pointer guest_memfd will use to get iommufd to zap during [GUEST_MEMFD] -> [IOMMU]. This [GUEST_MEMFD] -> [IOMMU] zapping was previously also proposed in the context of Confidential IO [5].

[1] https://lore.kernel.org/all/[email protected]/
[2] https://github.com/kvm-x86/linux/blob/a6270ed4bec0caa25913082e71ce22254e9cd3ed/virt/kvm/guest_memfd.c#L685
[3] https://lore.kernel.org/all/[email protected]/
[4] https://github.com/kvm-x86/linux/blob/a6270ed4bec0caa25913082e71ce22254e9cd3ed/virt/kvm/guest_memfd.c#L722
[5] https://lore.kernel.org/all/[email protected]/

I'm intentionally avoiding the "primary manager" terminology since that's overly broad and doesn't really explain what processes exactly are being managed. It's really just which entity tells which other entity to zap pages, and since shared/private-ness of memory is core to guest_memfd, I think guest_memfd is in the best position to tell all the other entities to zap, and what (shared/private to zap).

Does your provider need to know if some memory was transitioned between shared/private states? The provider can be notified too, if necessary. If not, then isn't guest_memfd doing all the coordination better than going via the provider?

Does the revocation model work for you? If it helps, I can rebuild the sample provider to illustrate how the revocation can be done. Let me know what else is missing from my model [1]. :)

#48 lore raw

Re: [RFC PATCH 0/9] mm: Memory providers for guest_memfd and iommufd

Quoted 9 lines

In my proposal, I agree with you completely that the provider must be allowed to revoke memory. Using the sample in this RFC, gmem_fd_ioctl() called with !GMEM_PROVIDER_SET_PRESENT is where the provider wants to revoke memory, and the revocation in my model would look like

[PROVIDER] -> [GUEST_MEMFD]

and [GUEST_MEMFD] would then fan it out to [KVM], [IOMMU], [USERSPACE] and [DIRECTMAP].

(Fred is the one with his head in this space right now; I mostly wanted to get the ball rolling from our side. So if he contradicts me, take his word for it and don't necessarily wait for me to concede.)

Your model above works for me, I think. I just don't *like* it very much.

I had a nice clean (in my head) model where the memory provider is the owner of that memory, responsible for who owns what and whether it's read-only/shared/private/revoked, and for persisting it across live update.

Anyone who wants a piece of it can come and ask, and it interfaced directly to KVM, IOMMU and anything else.

And it was then theoretically usable for other things, too. Fred has already been working on ways for a guest to donate memory to the host for caches to support more efficient nesting, for example, and that could have used a memory provider (which, on the back end, has had its pages donated from the guest).

The model of pushing it all into gmemfd probably works... but kind of makes my skin itch in ways I can't fully express.

It does absolutely need to support PFN-based operation though.

And one of the main design points is that we want to support the memory provider being the *trusted* arbiter of who owns what. The provider will be the part that gets the most careful review, that some people will be suggesting that we write in Rust because it magically fixes all bugs. Where in some platforms we have EL2 literally *enforcing* the fact that a rogue Linux kernel *cannot* access the wrong guests' memory, the model we want to support here is the next best thing, where a small and trusted piece of code provides and revokes those PFNs.

As long as that's preserved, I guess it's probably OK to push more of the coordination into gmemfd than I had originally imagined.

Quoted 4 lines

Does your provider need to know if some memory was transitioned between shared/private states? The provider can be notified too, if necessary. If not, then isn't guest_memfd doing all the coordination better than going via the provider?

I think it at least needs to know, doesn't it? If a guest page is being taken away (donated to another guest, or something like Fred's nested cache), then we do kind of have opinions on whether it's back in 'shared' mode or whether it's still allegedly private to the guest which claimed to donate it.

#49 lore raw

Re: [RFC PATCH 0/9] mm: Memory providers for guest_memfd and iommufd

In reply to Ackerley Tng
Quoted 8 lines · Ackerley Tng

When the provider wants to revoke the page, the notifications/function calls flow this way, the last [ENTITY] in the chain actually does the zapping.

+ [PROVIDER] -> [KVM]
+ [PROVIDER] -> [DMABUF] -> [IOMMU]
+ [PROVIDER] -> [GUEST_MEMFD] -> [USERSPACE] (AFAICT this was not implemented in the RFC.)

Thanks for going through it. I have just posted v2:

https://lore.kernel.org/all/[email protected]/

It changes two of these chains. dma-buf is gone: iommufd attaches to the provider file itself, through a small interface in mm. And guest_memfd now maps the file into userspace from the provider's frames, so a revoke also zaps the VMM's mapping:

[PROVIDER] -> [GUEST_MEMFD] -> [KVM], [USERSPACE] [PROVIDER] -> [IOMMU]

Quoted 2 lines

IIUC guest_memfd conversions was not illustrated in the RFC: what happens on a shared -> private conversion?

There are none yet. Only VMs of type KVM_X86_DEFAULT_VM can use a provider, so all their memory is shared.

Quoted 4 lines

Does your provider need to know if some memory was transitioned between shared/private states? The provider can be notified too, if necessary. If not, then isn't guest_memfd doing all the coordination better than going via the provider?

Our provider does not need to know, and I agree: once there is private memory, guest_memfd converts the pages, so it should tell the others what to zap.

I think the two models meet there, and the v2 cover letter now says so. The iommufd side of v2 does not pin and keeps no references: it asks for the frame behind each page, treats a page with no frame as a hole, and maps again on a revoke. guest_memfd can offer that for its own file:
shared pages return their frames, private pages are holes, and guest_memfd revokes a range whenever it converts it, in either direction. That is your [GUEST_MEMFD] -> [IOMMU], and it should work for folio-backed guest_memfd without memfd_pin_folios() or refcounts, as long as guest_memfd also revokes a range before it frees its folios.

The one difference is that v2 also lets iommufd map a provider file directly. Going through guest_memfd would add nothing without private
memory: it would only pass each revoke on. And memory that only devices use, such as MMIO, does not go through guest_memfd at all. Both paths would use the same iommufd code.

Quoted 2 lines

Does the revocation model work for you? If it helps, I can rebuild the sample provider to illustrate how the revocation can be done.

Yes, the revocation model works for us. v2 replaces David's sample with one that moves, donates and makes pages read-only, and a selftest that checks the guest, the device and the VMM's mapping after each change. It may be a good base if you want to try guest_memfd as the provider for iommufd on top of it.

Quoted 1 line

4. [DIRECTMAP] Kernel direct map.

Agreed, that is separate. The memory we have in mind is a range hidden from the host with memmap=, so it is not in the direct map.

Thanks,
Fred

#50 lore raw

Re: [RFC PATCH 0/9] mm: Memory providers for guest_memfd and iommufd

Quoted 15 lines · Fred Griffoul
Quoted 8 lines · Ackerley Tng

When the provider wants to revoke the page, the notifications/function calls flow this way, the last [ENTITY] in the chain actually does the zapping.

+ [PROVIDER] -> [KVM]
+ [PROVIDER] -> [DMABUF] -> [IOMMU]
+ [PROVIDER] -> [GUEST_MEMFD] -> [USERSPACE] (AFAICT this was not implemented in the RFC.)

Thanks for going through it. I have just posted v2:

https://lore.kernel.org/all/[email protected]/

Quoted 8 lines

It changes two of these chains. dma-buf is gone: iommufd attaches to the provider file itself, through a small interface in mm. And guest_memfd now maps the file into userspace from the provider's frames, so a revoke also zaps the VMM's mapping:

[PROVIDER] -> [GUEST_MEMFD] -> [KVM], [USERSPACE] [PROVIDER] -> [IOMMU]

Thanks :)

Quoted 6 lines
Quoted 2 lines

IIUC guest_memfd conversions was not illustrated in the RFC: what happens on a shared -> private conversion?

There are none yet. Only VMs of type KVM_X86_DEFAULT_VM can use a provider, so all their memory is shared.

To borrow David's words, the part about this that makes me itch is conversion. We have to support conversions. Even if it doesn't merge in the first patch series, we have to have line of sight to how conversions would work.

Conversion requests originate from the guest and then the host handles the guest request by making calling an ioctl on guest_memfd. Hopefully this part doesn't change with alternative provider support.

Suppose guest_memfd still gets the conversion request first, in RFCv2, to reach all the mappings in various page tables, it would have to be

+ [GUEST_MEMFD] -> [KVM], [USERSPACE]
+ [GUEST_MEMFD] -> [PROVIDER] -> [IOMMU]

since guest_memfd must ensure no IOMMU mappings to guest private pages? There's that extra step through the [PROVIDER]...

Quoted 9 lines
Quoted 4 lines

Does your provider need to know if some memory was transitioned between shared/private states? The provider can be notified too, if necessary. If not, then isn't guest_memfd doing all the coordination better than going via the provider?

Our provider does not need to know, and I agree: once there is private memory, guest_memfd converts the pages, so it should tell the others what to zap.

Quoted 10 lines

I think the two models meet there, and the v2 cover letter now says so. The iommufd side of v2 does not pin and keeps no references: it asks for the frame behind each page, treats a page with no frame as a hole, and maps again on a revoke. guest_memfd can offer that for its own file:
shared pages return their frames, private pages are holes, and guest_memfd revokes a range whenever it converts it, in either direction. That is your [GUEST_MEMFD] -> [IOMMU], and it should work for folio-backed guest_memfd without memfd_pin_folios() or refcounts, as long as guest_memfd also revokes a range before it frees its folios.

This part makes sense, if I'm understanding you correctly.

Quoted 6 lines

The one difference is that v2 also lets iommufd map a provider file directly. Going through guest_memfd would add nothing without private
memory: it would only pass each revoke on. And memory that only devices use, such as MMIO, does not go through guest_memfd at all. Both paths would use the same iommufd code.

Quoted 9 lines
Quoted 2 lines

Does the revocation model work for you? If it helps, I can rebuild the sample provider to illustrate how the revocation can be done.

Yes, the revocation model works for us. v2 replaces David's sample with one that moves, donates and makes pages read-only, and a selftest that checks the guest, the device and the VMM's mapping after each change. It may be a good base if you want to try guest_memfd as the provider for iommufd on top of it.

Thanks, I will prototype what I have in mind too to make sure things work as I think they will :)

Quoted 7 lines
Quoted 1 line

4. [DIRECTMAP] Kernel direct map.

Agreed, that is separate. The memory we have in mind is a range hidden from the host with memmap=, so it is not in the direct map.

Thanks,
Fred

#51 lore raw

Re: [RFC PATCH 0/9] mm: Memory providers for guest_memfd and iommufd

Quoted 8 lines · Ackerley Tng

To borrow David's words, the part about this that makes me itch is conversion. We have to support conversions. Even if it doesn't merge in the first patch series, we have to have line of sight to how conversions would work.

Conversion requests originate from the guest and then the host handles the guest request by making calling an ioctl on guest_memfd. Hopefully this part doesn't change with alternative provider support.

Agreed, and it doesn't change. Conversions still go through guest_memfd. It is the only one that knows which pages are private.

Quoted 8 lines

Suppose guest_memfd still gets the conversion request first, in RFCv2, to reach all the mappings in various page tables, it would have to be

+ [GUEST_MEMFD] -> [KVM], [USERSPACE]
+ [GUEST_MEMFD] -> [PROVIDER] -> [IOMMU]

since guest_memfd must ensure no IOMMU mappings to guest private pages? There's that extra step through the [PROVIDER]...

Right, there is a step through [PROVIDER]. But it can be a step through the mem_provider code in mm, which every provider shares, rather than through each provider driver. Then guest_memfd doesn't need to know who else maps the frames, and providers don't have to get it right one by one.

Here is the idea, on top of your in-place conversion. The VMM gives the same provider file to guest_memfd and to iommufd, as in v2. When guest_memfd converts a range to private, it claims the range:

int mem_provider_claim(struct mem_provider_attachment *att,

                         loff_t offset, loff_t len);
  void mem_provider_unclaim(struct mem_provider_attachment *att,
                            loff_t offset, loff_t len);

The claim revokes the range for every other consumer of the file. After that, get_page() returns a hole to them. So iommufd unmaps the pages and can't map them again, and nothing changes on the iommufd side. guest_memfd zaps its own mappings, as it does today.

Going back to shared is the reverse. guest_memfd returns the frames to the host first, then unclaims the range. The other consumers then map the frames again. So a conversion looks like:

[GUEST_MEMFD] -> [KVM], [USERSPACE]
[GUEST_MEMFD] -> [PROVIDER] -> [IOMMU]

That is your second chain, but the [PROVIDER] step is the common code in mm/mem_provider.c. It does the revokes and hands out the holes. The provider driver itself only gets one callback, and it can refuse a claim. For example, it would refuse if it also lends those frames through another file. Conversions can already fail, so this fits. If a later step fails, guest_memfd just unclaims the range.

This also answers your earlier question. The provider doesn't need to know what is shared or private. It only needs to know which ranges are claimed, so that it doesn't move or share them, and only takes them back once the guest has given them up.

I haven't implemented this yet. My plan is to rebase on kvm-x86 next, which has your conversion code. Then I'd demo it with a KVM_X86_SW_PROTECTED_VM and the sample provider. A device sees a shared page, loses it when the page becomes private, and sees the same frame again when it goes back to shared.

Does that match what you have in mind?

Quoted 2 lines

Thanks, I will prototype what I have in mind too to make sure things work as I think they will :)

Thanks, that would really help. The sample provider and the KVM selftest in the series could be a starting point.

Thanks,
Fred