mm: Memory providers for guest_memfd and iommufd
Subsystems (13)
v2 cover mm: Memory providers for guest_memfd and iommufd
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.
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. That type also covers legacy SEV and SEV-ES guests set up with KVM_SEV_INIT: for them, a revoke and the closing of the file write back the guest's caches, so that no stale encrypted line reaches the frames once the provider reuses them.
For VMs with private memory, guest_memfd converts pages between shared and private, so it should tell the other users what to zap. Only guest_memfd knows which pages are private, and revoking a private page loses its contents, so a provider should not take part in conversions.
The interface fits that model too. guest_memfd can be a provider for its own file: it returns the frames of shared pages, reports private pages as holes, and revokes a range that it converts to private. iommufd then maps only shared pages, without pinning them, whether guest_memfd allocates folios or takes its memory from a provider. In the second case, guest_memfd forwards the provider's revokes. I left that for a later series.
Patches
=======
Patch 1 is David's: guest_memfd gets a per-file struct kvm_gmem_ops, and the native backend becomes one implementation of it.
Patch 2 lets a kvm_gmem_ops backend map a page read-only for the guest. get_pfn() gets a writable output that it may clear, 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 3 adds the interface and the core, and the FOP_MEM_PROVIDER flag in struct file_operations.
Patch 4 adds the provider backend to guest_memfd, behind GUEST_MEMFD_FLAG_USE_RESOURCE. 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 5 prepares iommufd for tracking pages it does not pin. No functional change.
Patch 6 lets IOMMU_IOAS_MAP_FILE take a provider file. iommufd pins nothing and maps only what the provider backs; a revoke unmaps the range and maps it again. A scratch page for devices that cannot fault is left for a later IOAS quirk, as David suggested.
Patch 7 maps each block the provider reports with large IOMMU pages where the IOVA and the frames are aligned alike, one call per page so that a revoke never splits a map call. A large IOMMU page can only be unmapped whole, so a revoke that cuts one unmaps and remaps all of it.
Patches 8 and 9 add iommufd selftests: two mock-domain queries and a mock provider.
Patch 10 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 11 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. A third VM checks that KVM maps an aligned block with a 2 MiB page, and drops it when a page inside goes away.
Testing
=======
On x86_64 in QEMU, with KASAN and lockdep: mem_provider_test, guest_memfd_test and the iommufd provider selftests pass, with the mock IOMMU domain only. Each patch builds with KVM built in, as a module, and with SEV. arm64 is not tested.
Changes since v1
================
v1: https://lore.kernel.org/all/[email protected]/
- Sit on David's kvm_gmem_ops patch alone instead of his whole series; its revoke, iommufd exporter lookups, sample and selftests are replaced by this series.
- Take the provider file through Ackerley Tng's GUEST_MEMFD_FLAG_USE_RESOURCE and resource_fd [1], as discussed with Aneesh and Ackerley. A file that is not from a provider fails with -EOPNOTSUPP.
- Map the blocks the provider reports, so the IOMMU can use large pages, and flush the IOTLB once per revoke (patch 7).
[1] https://lore.kernel.org/all/[email protected]/
David Woodhouse (1):
KVM: guest_memfd: Introduce guest memory ops and route native gmem
through them
Fred Griffoul (10):
KVM: guest_memfd: Let get_pfn() report read-only pages
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: Use large IOMMU pages for provider mappings 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 | 46 +- MAINTAINERS | 8 + arch/arm64/kvm/mmu.c | 13 +- arch/arm64/kvm/nested.c | 16 +- arch/x86/kvm/Makefile | 5 +- arch/x86/kvm/mmu/mmu.c | 18 +- arch/x86/kvm/svm/sev.c | 13 +- arch/x86/kvm/x86.c | 9 + drivers/iommu/iommufd/Kconfig | 1 + drivers/iommu/iommufd/io_pagetable.c | 37 +- drivers/iommu/iommufd/io_pagetable.h | 58 +- drivers/iommu/iommufd/iommufd_test.h | 40 + drivers/iommu/iommufd/pages.c | 435 ++++++++- drivers/iommu/iommufd/selftest.c | 325 +++++++ include/linux/fs.h | 2 + include/linux/kvm_host.h | 100 +- include/linux/mem_provider.h | 211 +++++ include/uapi/linux/iommufd.h | 16 +- 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 | 2 + 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 | 185 ++++ tools/testing/selftests/iommu/iommufd_utils.h | 69 ++ tools/testing/selftests/kvm/Makefile.kvm | 1 + .../testing/selftests/kvm/guest_memfd_test.c | 15 + .../selftests/kvm/x86/mem_provider_test.c | 653 +++++++++++++ virt/kvm/Kconfig | 1 + virt/kvm/guest_memfd.c | 645 +++++++++++-- virt/kvm/kvm_main.c | 8 +- virt/kvm/kvm_mm.h | 4 +- 37 files changed, 3987 insertions(+), 164 deletions(-) create mode 100644 include/linux/mem_provider.h create mode 100644 mm/mem_provider.c create mode 100644 samples/kvm/Makefile 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/mem_provider_test.c
base-commit: 0e35b9b6ec0ffcc5e23cbdec09f5c622ad532b53
Signature · 1 line
2.47.3
RFC PATCH v2 1/11 KVM: guest_memfd: Introduce guest memory ops and route native gmem through them
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
@@ -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
@@ -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
@@ -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.47.3
[email protected]
AI reviewRe: [RFC PATCH v2 01/11] KVM: guest_memfd: Introduce guest memory ops and route native gmem through them
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] kvm: ignored xa_store_range failure in kvm_gmem_native_bind allows memory access to freed host…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] kvm: ignored xa_store_range failure in kvm_gmem_native_bind allows memory access to freed host pages --
commit ab5f37736d076d164ccad403ab4a50bd2032eb9b
Author: David Woodhouse <[email protected]>
KVM: guest_memfd: Introduce guest memory ops and route native gmem through them
This commit introduces a vtable (struct kvm_gmem_ops) to allow alternate subsystems to supply guest memory backing. The built-in guest_memfd implementation is refactored to route its memory-side and file-level callbacks through this new shared dispatch mechanism.
Quoted 4 lines
virt/kvm/guest_memfd.c +0
-0
[ ... ]
Quoted 3 lines
virt/kvm/guest_memfd.c +3
-0+static int kvm_gmem_native_bind (struct file *file,struct kvm *kvm, +struct kvm_memory_slot *slot,loff_t offset) +{
[ ... ]
virt/kvm/guest_memfd.c
Quoted 12 lines
virt/kvm/guest_memfd.c +12
-0+/* +* memslots of flag KVM_MEM_GUEST_MEMFD are immutable, so bind must +* occur on a new memslot. Because the memslot is not visible yet, +* kvm_gmem_get_pfn() is guaranteed to see the file. +*/ +WRITE_ONCE (slot->gmem.file, file); + slot->gmem.pgoff = start; +if (kvm_gmem_supports_mmap (inode)) + slot->flags |=KVM_MEMSLOT_GMEM_ONLY ; + +xa_store_range (&f->bindings, start, end -1 , slot,GFP_KERNEL ); + r =0 ;
[Severity: High]
Does this code handle potential memory allocation failures from xa_store_range()?
xa_store_range() can fail with -ENOMEM when allocating internal nodes for the XArray. Because the return value is ignored and the path unconditionally returns 0, the memslot is successfully bound from KVM's perspective, but is missing from the f->bindings tracking structure.
During operations like fallocate (hole punch) or file release, KVM iterates over f->bindings to find and zap the guest mappings. If the slot is missing from the XArray, the guest mappings will not be zapped, which could allow the guest to retain read/write access to physical memory that has been returned to the host allocator.
Quoted 4 lines
virt/kvm/guest_memfd.c +4
-0+out: +filemap_invalidate_unlock (inode->i_mapping); +return r; +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
RFC PATCH v2 2/11 KVM: guest_memfd: Let get_pfn() report read-only pages
In reply to Fred GriffoulFrom: 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. So a hypervisor cannot give a guest a page it may read but not write.
get_pfn() gets a writable output, which it may clear. The x86 and arm64 fault paths then map the page without write permission, and a guest write exits with KVM_EXIT_MEMORY_FAULT. A read-only answer applies to 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 output, so a backing cannot report read-only state through it. The output does not cover KVM's own writes through the slot's host address.
The memory provider backing, later in this series, is the first user.
--- 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 +++++++++++++--- virt/kvm/guest_memfd.c | 21 ++++++++++++++++----- 6 files changed, 76 insertions(+), 21 deletions(-)
arch/arm64/kvm/mmu.c +8 -5
@@ -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
@@ -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
@@ -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
@@ -3988,6 +3988,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;
@@ -4025,9 +4026,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
@@ -4958,7 +4967,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
@@ -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);
@@ -2642,12 +2652,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 ;
virt/kvm/guest_memfd.c +16 -5
@@ -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);
@@ -936,7 +936,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;
@@ -964,7 +964,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;
@@ -977,7 +977,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);
@@ -1028,6 +1031,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;
@@ -1041,10 +1045,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);/*
Signature · 1 line
2.47.3
RFC PATCH v2 3/11 mm: Add memory providers
In reply to Fred GriffoulFrom: 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
@@ -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
@@ -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
@@ -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
@@ -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
Signature · 1 line
2.47.3
RFC PATCH v2 4/11 KVM: guest_memfd: Add a memory provider backing
In reply to Fred GriffoulFrom: 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_RESOURCE and resource_fd, as defined in Ackerley Tng's resource pool RFC [1], so that both series share one flag and one field. resource_fd uses the first reserved word and must be zero without the flag. guest_memfd picks the backing from the kind of file: for now only memory provider files are accepted, and any other file fails with -EOPNOTSUPP.
Guest faults ask the provider for each frame, and a revoke removes the range from the guest and from the VMM's mapping. A guest access to a page that is not backed, or 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_RESOURCE requires GUEST_MEMFD_FLAG_MMAP, so that the memory slot is gmem-only. An architecture opts in; x86 does so for VMs of the default type, which have no private memory, and other architectures refuse the flag for now.
A legacy SEV or SEV-ES guest, set up with KVM_SEV_INIT, is also a VM of the default type. Its writes can leave encrypted dirty cache lines for the frames it used, and their later write-back would corrupt a frame that the provider has given to another owner. A revoke therefore writes back the guest's caches before it returns, as the mmu notifiers do when they zap guest memory. Closing the file does the same, while a revoke can still find the file: the VMM may close it before deleting the memory slot, and a later revoke would then find no file to flush.
Native guest_memfd files now take the invalidate lock when a file is added and when a closing file is unbound, because a revoke walks the file list and the bindings under it.
[1] https://lore.kernel.org/all/[email protected]/
--- Documentation/virt/kvm/api.rst | 46 ++- arch/x86/kvm/x86.c | 9 + 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 | 15 + virt/kvm/Kconfig | 1 + virt/kvm/guest_memfd.c | 299 +++++++++++++++++- 8 files changed, 380 insertions(+), 16 deletions(-)
Documentation/virt/kvm/api.rst +36 -10
@@ -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 resource_fd; + __u32 pad; + __u64 reserved[5]; }; Conceptually, the inode backing a guest_memfd file represents physical memory,
@@ -6453,15 +6455,39 @@ 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_RESOURCE Take the memory of the file from the resource + behind `resource_fd`, instead of allocating + it. Requires GUEST_MEMFD_FLAG_MMAP. Not + supported for VMs with private memory. + ============================= ================================================ + +`pad` must be zero. Without GUEST_MEMFD_FLAG_USE_RESOURCE, `resource_fd` must +be zero. With it, `resource_fd` is the file whose memory backs the guest_memfd. +The only kind of resource supported so far is a file handed out by a memory +provider (see include/linux/mem_provider.h); any other file fails with +EOPNOTSUPP. +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_RESOURCE. + +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 +9 -0
@@ -14124,6 +14124,15 @@ bool kvm_arch_supports_gmem_init_shared(struct kvm *kvm)return !kvm_arch_has_private_mem (kvm); } +/* +* Only VMs of the default type, which have no private memory. A legacy SEV +* guest is one of them; a revoke, and closing the file, write back its caches. +*/ +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
@@ -823,11 +823,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_RESOURCE ; +if (!kvm ||kvm_arch_supports_gmem_init_shared (kvm)) flags |=GUEST_MEMFD_FLAG_INIT_SHARED ;
include/uapi/linux/kvm.h +10 -1
@@ -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_RESOURCE (1ULL << 2)struct kvm_create_guest_memfd {__u64 size;__u64 flags; -__u64 reserved[6 ]; +/* +* With GUEST_MEMFD_FLAG_USE_RESOURCE: the file whose memory backs +* this guest_memfd, for now a memory provider file. 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 resource_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
@@ -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_RESOURCE (1ULL << 2)struct kvm_create_guest_memfd {__u64 size;__u64 flags; -__u64 reserved[6 ]; +/* +* With GUEST_MEMFD_FLAG_USE_RESOURCE: the file whose memory backs +* this guest_memfd, for now a memory provider file. 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 resource_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 +15 -0
@@ -405,6 +405,21 @@ 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_RESOURCE also needs MMAP and a provider file. */ +if (flag ==GUEST_MEMFD_FLAG_USE_RESOURCE && (flag & valid_flags)) { +struct kvm_create_guest_memfd args = { + .size = page_size, + .flags =GUEST_MEMFD_FLAG_MMAP | flag, + .resource_fd = vm->fd, + }; + +TEST_ASSERT (fd <0 && errno ==EINVAL , +"guest_memfd() with USE_RESOURCE alone should fail with EINVAL" ); + fd =__vm_ioctl (vm,KVM_CREATE_GUEST_MEMFD , &args); +TEST_ASSERT (fd <0 && errno ==EOPNOTSUPP , +"guest_memfd() with a resource that is not a provider should fail with EOPNOTSUPP" ); +continue ; + }if (flag & valid_flags) { TEST_ASSERT(fd >= 0, "guest_memfd() with flag '0x%lx' should succeed",
virt/kvm/Kconfig +1 -0
@@ -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 +295 -4
383 lines not on this page · raw message
Signature · 1 line
2.47.3
RFC PATCH v2 5/11 iommufd: Track the domains of pages that are not pinned
In reply to Fred GriffoulFrom: 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
@@ -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
@@ -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; };/*
@@ -246,6 +245,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)
@@ -255,6 +260,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
Signature · 1 line
2.47.3
RFC PATCH v2 6/11 iommufd: Map memory provider files
In reply to Fred GriffoulFrom: 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. A revoke charges the page tables it allocates to the memory cgroup that mapped the file, not to the task that revoked.
Each frame gets a PAGE_SIZE entry, so a partial revoke never splits a large IOMMU page. The next patch maps larger blocks. Holes stay unmapped, read-only pages are mapped without IOMMU_WRITE, and MMIO pages with IOMMU_MMIO. Frame 0 is refused with -EINVAL: iova_to_phys() returns 0 for an IOVA that is not mapped, so a revoke would take that page for a hole and leave it mapped.
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 | 27 ++- drivers/iommu/iommufd/pages.c | 288 ++++++++++++++++++++++++++- include/uapi/linux/iommufd.h | 11 +- 5 files changed, 334 insertions(+), 6 deletions(-)
drivers/iommu/iommufd/Kconfig +1 -0
@@ -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
@@ -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 +26 -1
@@ -8,11 +8,14 @@#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> #include "iommufd_private.h" +struct mem_cgroup ; +struct iommu_domain ;/*
@@ -48,6 +51,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 +196,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. */
@@ -207,6 +213,14 @@ struct iopt_pages_dmabuf {unsigned long start; }; +struct iopt_pages_provider { +struct mem_provider_attachment att; +/* Byte offset in the provider file, always PAGE_SIZE aligned */ +unsigned long start; +/* Charged for the page tables that a revoke allocates */ +struct mem_cgroup *memcg; +}; +/* * 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
@@ -236,6 +250,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;
@@ -260,10 +276,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)
@@ -285,6 +306,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 +286 -2
354 lines not on this page · raw message
include/uapi/linux/iommufd.h +10 -1
@@ -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;
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [RFC PATCH v2 06/11] iommufd: Map memory provider files
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] iommufd: 32-bit truncation of file offset breaks provider revokes - [Medium] iommufd: missing…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] iommufd: 32-bit truncation of file offset breaks provider revokes
- [Medium] iommufd: missing cond_resched() in large IOVA mapping/unmapping loops --
commit b6da636b8b49032486fd2a6044789fc9bf757f2b
Author: Fred Griffoul <[email protected]>
iommufd: Map memory provider files
This patch adds support for mapping memory provider files into iommufd domains. It bypasses pinning and accounting, and allows the provider to dynamically back or revoke memory ranges while keeping mappings in sync.
drivers/iommu/iommufd/io_pagetable.h struct iopt_pages_dmabuf { · line 219
Quoted 12 lines
drivers/iommu/iommufd/io_pagetable.h +4
-0@@ -207,6 +213,14 @@ struct iopt_pages_dmabuf {unsigned long start; }; +struct iopt_pages_provider { +struct mem_provider_attachment att; +/* Byte offset in the provider file, always PAGE_SIZE aligned */ +unsigned long start;
[Severity: High]
The UAPI structure iommu_ioas_map_file defines the file start offset as a 64-bit __aligned_u64, but it is stored here as an unsigned long. On 32-bit systems, does this silently truncate offsets larger than 4GB?
Quoted 7 lines
drivers/iommu/iommufd/io_pagetable.h +4
-0+/* Charged for the page tables that a revoke allocates */ +struct mem_cgroup *memcg; +}; +/* * 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
[ ... ]
Quoted 18 lines
drivers/iommu/iommufd/pages.c +10
-0@@ -238,6 +240,35 @@ static void iommu_unmap_nofail(struct iommu_domain *domain, unsigned long iova,WARN_ON (ret != size); } +/* +* Provider pages are mapped with PAGE_SIZE entries, and may have holes. Some +* IOMMU drivers warn when asked to unmap an IOVA that is not mapped, so find +* the runs that are mapped and unmap each one, without touching the holes. +* iopt_provider_map() refuses frame 0, which iova_to_phys() reports for +* an IOVA that is not mapped. +*/ +static void iopt_provider_unmap(struct iopt_area *area, + struct iommu_domain *domain, + unsigned long start_index,
drivers/iommu/iommufd/pages.c static void iommu_unmap_nofail(struct iommu_domain *domain, unsigned long iova, · line 262
Quoted 10 lines
drivers/iommu/iommufd/pages.c +10
-0+ unsigned long last_index) +{ +unsigned long iova =iopt_area_index_to_iova (area, start_index); +size_t left = (last_index - start_index +1 ) *PAGE_SIZE ; + +while (left) { +size_t len =0 ; + +while (len < left &&iommu_iova_to_phys (domain, iova + len)) + len +=PAGE_SIZE ;
[Severity: Medium]
Memory provider files can be extremely large. Since this loop unmaps the entire range in a single pass without explicitly yielding the CPU, could this cause soft lockups on kernels without forced preemption? Would it be better to add a cond_resched() here?
Quoted 8 lines
drivers/iommu/iommufd/pages.c +8
-0+if (len) +iommu_unmap_nofail (domain, iova, len); +/* Step over the run and the hole page that ended it. */ + len =min (len +PAGE_SIZE , left); + iova += len; + left -= len; + } +}
[ ... ]
Quoted 43 lines
drivers/iommu/iommufd/pages.c +39
-0@@ -1647,6 +1687,228 @@ void iopt_pages_untrack_all_domains(struct iopt_area *area, } } +static int iopt_provider_prot (struct iopt_area *area,u32 attrs) +{ +int prot = area->iommu_prot; + +if (attrs &MEM_PROVIDER_ATTR_READONLY ) + prot &= ~IOMMU_WRITE ; +if (mem_provider_type (attrs) !=MEM_PROVIDER_TYPE_RAM ) { + prot &= ~IOMMU_CACHE ; + prot |=IOMMU_MMIO ; + } +return prot; +} + +/* +* Map what the provider backs in [start_index, last_index] of the area into +* @domain, and leave the holes unmapped. Each frame is mapped with a +* PAGE_SIZE entry, so that a revoke of part of a large block never has to +* split a larger IOMMU page. On failure nothing in the range is mapped. +*/ +static int iopt_provider_map (struct iopt_area *area,struct iopt_pages *pages, +struct iommu_domain *domain, +unsigned long start_index, +unsigned long last_index) +{ +unsigned long base = pages->provider.start >>PAGE_SHIFT ; +unsigned long index = start_index; +int rc; + +lockdep_assert_held (&pages->mutex); + +if ((1UL <<__ffs (domain->pgsize_bitmap)) >PAGE_SIZE ) +return -EOPNOTSUPP ; + +/* +* A revoke unmaps under pages->mutex only, so it would race with a +* dirty bitmap read, and lose the dirty bits of what it unmaps. +* Provider pages are not mapped in a domain with dirty tracking. +*/ +if (domain->dirty_ops)
drivers/iommu/iommufd/pages.c void iopt_pages_untrack_all_domains(struct iopt_area *area, · line 1738
Quoted 10 lines
drivers/iommu/iommufd/pages.c +10
-0+return -EOPNOTSUPP ; + +while (index <= last_index) { +unsigned long pfn, iova, block_end, nr, i; +int order =PUD_ORDER ; +u32 attrs; +int prot; + + rc =mem_provider_get_page (&pages->provider.att, base + index, + &pfn, &order, &attrs);
[Severity: Medium]
Similarly, mapping a very large provider file could translate to processing millions of frames in one go. Should this loop also yield the CPU to prevent soft lockups?
Quoted 4 lines
drivers/iommu/iommufd/pages.c +4
-0+if (rc == -EFAULT ) { + index++; +continue ; + }
[ ... ]
Quoted 9 lines
drivers/iommu/iommufd/pages.c +9
-0+/* +* The provider changed the frames behind [offset, offset + len). In every +* domain, unmap the range and map what the provider backs now. A device that +* accesses the range in between faults. +*/ +static void iopt_provider_revoke (struct mem_provider_attachment *att, +loff_t offset,loff_t len) +{ + struct iopt_pages *pages =
drivers/iommu/iommufd/pages.c void iopt_pages_untrack_all_domains(struct iopt_area *area, · line 1825
Quoted 10 lines
drivers/iommu/iommufd/pages.c +10
-0+ container_of(att, struct iopt_pages, provider.att); +u64 start = pages->provider.start; +u64 end = start + (u64 )pages->npages *PAGE_SIZE ; +struct iopt_pages_track *track; +struct mem_cgroup *old_memcg; +unsigned long first, last; +int rc; + +if (offset <0 || len <=0 || offset >= end || offset + len <= start) +return ;
[Severity: High]
Because pages->provider.start is stored as an unsigned long, it will wrap on 32-bit systems for offsets larger than 4GB.
When the provider later calls iopt_provider_revoke() with a 64-bit loff_t offset, this bounds check will compare the correct 64-bit offset against the wrapped 32-bit start/end values.
Will this cause the bounds check to evaluate to true (e.g. offset >= end) and abort early, bypassing the unmap and leaving the device with access to revoked memory?
Quoted 2 lines
drivers/iommu/iommufd/pages.c +2
-0+ first = (max_t (u64, offset, start) - start) >>PAGE_SHIFT ; + last = (min_t (u64, offset + len, end) - start -1 ) >>PAGE_SHIFT ;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
kernel test robot
build botRe: [RFC PATCH v2 06/11] iommufd: Map memory provider files
In reply to Fred Griffoulkernel test robot noticed the following build errors:
Hi Fred,
[This is a private test report for your RFC patch.] kernel test robot noticed the following build errors:
[auto build test ERROR on 0e35b9b6ec0ffcc5e23cbdec09f5c622ad532b53]
url: https://github.com/intel-lab-lkp/linux/commits/Fred-Griffoul/KVM-guest_memfd-Introduce-guest-memory-ops-and-route-native-gmem-through-them/20261014-093723 base: 0e35b9b6ec0ffcc5e23cbdec09f5c622ad532b53 patch link: https://lore.kernel.org/r/20261014093733.90312-7-griffoul%40gmail.com patch subject: [RFC PATCH v2 06/11] iommufd: Map memory provider files config: loongarch-allmodconfig (https://download.01.org/0day-ci/archive/20261018/[email protected]/config) compiler: clang version 19.1.7 (https://github.com/llvm/llvm-project cd708029e0b2869e80abe31ddb175f7c35361f90) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261018/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>, old ones prefixed by <<):
>> ERROR: modpost: "get_mem_cgroup_from_current" [drivers/iommu/iommufd/iommufd.ko] undefined! >> ERROR: modpost: "iommu_map_nosync" [drivers/iommu/iommufd/iommufd.ko] undefined! >> ERROR: modpost: "iommu_sync_map" [drivers/iommu/iommufd/iommufd.ko] undefined!
--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
Re: [RFC PATCH v2 06/11] iommufd: Map memory provider files
In reply to Fred GriffoulQuoted 36 lines · Fred Griffoul
From: Fred Griffoul <[email protected]>
IOMMU_IOAS_MAP_FILEpins 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. A revoke charges the page tables it allocates to the memory cgroup that mapped the file, not to the task that revoked.
Each frame gets a
PAGE_SIZEentry, so a partial revoke never splits a large IOMMU page. The next patch maps larger blocks. Holes stay unmapped, read-only pages are mapped withoutIOMMU_WRITE, and MMIO pages withIOMMU_MMIO. Frame 0 is refused with-EINVAL:iova_to_phys()returns 0 for an IOVA that is not mapped, so a revoke would take that page for a hole and leave it mapped.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.Assisted-by Claude:claude-opus-5-5Signed-off-by Fred Griffoul <[email protected]>---
drivers/iommu/iommufd/Kconfig | 1 + drivers/iommu/iommufd/io_pagetable.c | 13 +- drivers/iommu/iommufd/io_pagetable.h | 27 ++- drivers/iommu/iommufd/pages.c | 288 ++++++++++++++++++++++++++- include/uapi/linux/iommufd.h | 11 +- 5 files changed, 334 insertions(+), 6 deletions(-)
[snip]
Quoted 138 lines
+
/* The pages are not pinned, so their domains are tracked inpages->tracker. */ static inline booliopt_pages_tracked(struct iopt_pages *pages)
{drivers/iommu/iommufd/io_pagetable.h +1
-1-return iopt_is_dmabuf (pages); +return iopt_is_dmabuf (pages) ||iopt_is_provider (pages);}
static inline bool
iopt_dmabuf_revoked(struct iopt_pages *pages)drivers/iommu/iommufd/io_pagetable.h +4
-0@@ -285,6 +306,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 +82
-0@@ -52,6 +52,8 @@#include <linux/iommu.h> #include <linux/iommufd.h> #include <linux/kthread.h> +#include <linux/mem_provider.h> +#include <linux/memcontrol.h> #include <linux/overflow.h> #include <linux/slab.h> #include <linux/sched/mm.h> @@ -238,6 +240,35 @@ static void iommu_unmap_nofail(struct iommu_domain *domain, unsigned long iova,WARN_ON (ret != size); } +/* +* Provider pages are mapped with PAGE_SIZE entries, and may have holes. Some +* IOMMU drivers warn when asked to unmap an IOVA that is not mapped, so find +* the runs that are mapped and unmap each one, without touching the holes. +* iopt_provider_map() refuses frame 0, which iova_to_phys() reports for +* an IOVA that is not mapped. +*/ +static void iopt_provider_unmap (struct iopt_area *area, +struct iommu_domain *domain, +unsigned long start_index, +unsigned long last_index) +{ +unsigned long iova =iopt_area_index_to_iova (area, start_index); +size_t left = (last_index - start_index +1 ) *PAGE_SIZE ; + +while (left) { +size_t len =0 ; + +while (len < left &&iommu_iova_to_phys (domain, iova + len)) + len +=PAGE_SIZE ; +if (len) +iommu_unmap_nofail (domain, iova, len); +/* Step over the run and the hole page that ended it. */ + len =min (len +PAGE_SIZE , left); + iova += len; + left -= len; + } +} + static void iopt_area_unmap_domain_range(struct iopt_area *area, struct iommu_domain *domain, unsigned long start_index,@@ -245,6 +276,11 @@ static void iopt_area_unmap_domain_range(struct iopt_area *area, {unsigned long start_iova =iopt_area_index_to_iova (area, start_index); +if (area->provider) { +iopt_provider_unmap (area, domain, start_index, last_index); +return ; + } +iommu_unmap_nofail (domain, start_iova,iopt_area_index_to_iova_last (area, last_index) - start_iova +1 );@@ -1349,6 +1385,10 @@ static int pfn_reader_first(struct pfn_reader *pfns, struct iopt_pages *pages, WARN_ON(last_index < start_index))return -EINVAL ; +/* Provider pages are read from the provider, see iopt_provider_map() */ +if (WARN_ON (iopt_is_provider (pages))) +return -EINVAL ; + rc =pfn_reader_init (pfns, pages, start_index, last_index);if (rc)return rc;@@ -1647,6 +1687,228 @@ void iopt_pages_untrack_all_domains(struct iopt_area *area, } } +static int iopt_provider_prot (struct iopt_area *area,u32 attrs) +{ +int prot = area->iommu_prot; + +if (attrs &MEM_PROVIDER_ATTR_READONLY ) + prot &= ~IOMMU_WRITE ; +if (mem_provider_type (attrs) !=MEM_PROVIDER_TYPE_RAM ) { + prot &= ~IOMMU_CACHE ; + prot |=IOMMU_MMIO ; + } +return prot; +} + +/* +* Map what the provider backs in [start_index, last_index] of the area into +* @domain, and leave the holes unmapped. Each frame is mapped with a +* PAGE_SIZE entry, so that a revoke of part of a large block never has to +* split a larger IOMMU page. On failure nothing in the range is mapped. +*/ +static int iopt_provider_map (struct iopt_area *area,struct iopt_pages *pages, +struct iommu_domain *domain, +unsigned long start_index, +unsigned long last_index) +{ +unsigned long base = pages->provider.start >>PAGE_SHIFT ; +unsigned long index = start_index; +int rc; + +lockdep_assert_held (&pages->mutex); + +if ((1UL <<__ffs (domain->pgsize_bitmap)) >PAGE_SIZE ) +return -EOPNOTSUPP ; + +/* +* A revoke unmaps under pages->mutex only, so it would race with a +* dirty bitmap read, and lose the dirty bits of what it unmaps. +* Provider pages are not mapped in a domain with dirty tracking. +*/ +if (domain->dirty_ops) +return -EOPNOTSUPP ; + +while (index <= last_index) {
drivers/iommu/iommufd/pages.c void iopt_pages_untrack_all_domains(struct iopt_area *area, · line 1741
Quoted 10 lines
drivers/iommu/iommufd/pages.c +10
-0+unsigned long pfn, iova, block_end, nr, i; +int order =PUD_ORDER ; +u32 attrs; +int prot; + + rc =mem_provider_get_page (&pages->provider.att, base + index, + &pfn, &order, &attrs); +if (rc == -EFAULT ) { + index++; +continue ;
Hi Fred,
Thanks for this.
With this approach, silently skipping holes during IOAS_MAP_FILE means iommufd has no tracking of which IOVA ranges in the area are actually mapped, which complicates unmap and could also hide a bug if a hole in the range was not expected?
I am wondering whether the areas can track the holes, or whether we should have areas for the mapped/unmapped ranges? This should allow proper sanity checks when doing revoke. I am also thinking about this from the live update point of view, where we might need to sanity check that the backing memory of mapped regions is preserved.
Could you please CC me on v3? I'd like to follow this from the live update IOMMU and iommufd preservation side.
https://lore.kernel.org/all/[email protected]/
Thanks,
Sami
Re: [RFC PATCH v2 06/11] iommufd: Map memory provider files
Quoted 4 lines · Samiullah Khawaja
With this approach, silently skipping holes during
IOAS_MAP_FILEmeans iommufd has no tracking of which IOVA ranges in the area are actually mapped, which complicates unmap and could also hide a bug if a hole in the range was not expected?
I think if we are going to do this it should only work with iommupt and iommupt should provide an unmap that is compatible with the holes.
There are other places that would like such an operation, IIRC.
This will have to block an access reaching into a guest memfd mapping as well, so that should be OK.
Jason
RFC PATCH v2 7/11 iommufd: Use large IOMMU pages for provider mappings
In reply to Fred GriffoulFrom: Fred Griffoul <[email protected]>
Provider pages are mapped with one PAGE_SIZE entry each. A device that uses a large provider block then misses in the IOTLB on every page, and the IOMMU needs more page table memory than the block requires. A revoke also flushes the IOTLB once per run of pages it unmaps.
Map each block that the provider reports with large IOMMU pages where the IOVA and the frames are aligned alike, and with smaller ones where they are not. Only the pages of the block are mapped, as before.
A large IOMMU page can only be unmapped whole, so a revoke that cuts one widens its range to the whole page. It maps back what the provider backs now, and a device may also fault on the rest of that page while it is remapped. The widening finds the page with iova_to_phys():
pages that only look like one large page make the revoke remap more than it must, which is harmless.
iommu_unmap() may not split the range of one map call either, and virtio-iommu refuses to. Map each IOMMU page with its own call: the widened range ends on IOMMU page boundaries, so it also ends on map call boundaries.
A revoke now batches its unmaps with iommu_unmap_fast() and flushes the IOTLB once.
--- drivers/iommu/iommufd/pages.c | 114 +++++++++++++++++++++++++++++----- include/uapi/linux/iommufd.h | 11 +++- 2 files changed, 105 insertions(+), 20 deletions(-)
drivers/iommu/iommufd/pages.c +97 -17
@@ -241,11 +241,17 @@ static void iommu_unmap_nofail(struct iommu_domain *domain, unsigned long iova, }/* -* Provider pages are mapped with PAGE_SIZE entries, and may have holes. Some -* IOMMU drivers warn when asked to unmap an IOVA that is not mapped, so find -* the runs that are mapped and unmap each one, without touching the holes. -* iopt_provider_map() refuses frame 0, which iova_to_phys() reports for -* an IOVA that is not mapped. +* Provider pages may have holes. Some IOMMU drivers warn when asked to unmap +* an IOVA that is not mapped, so find the runs that are mapped and unmap each +* one, without touching the holes, and flush the IOTLB once at the end. +* iopt_provider_map() refuses frame 0, which iova_to_phys() reports for an +* IOVA that is not mapped. +* +* A run may hold large entries, which can only be unmapped whole: neither end +* of the range may fall inside one. iopt_provider_map() maps each entry with +* its own call, so an end that is not inside an entry does not split a map +* call either, which iommu_unmap() does not allow. The ends of the area are +* safe, and iopt_provider_revoke() widens its range to the entries it cuts. */ static void iopt_provider_unmap(struct iopt_area *area, struct iommu_domain *domain,
@@ -254,19 +260,23 @@ static void iopt_provider_unmap(struct iopt_area *area, {unsigned long iova =iopt_area_index_to_iova (area, start_index);size_t left = (last_index - start_index +1 ) *PAGE_SIZE ; +struct iommu_iotlb_gather gather; +iommu_iotlb_gather_init (&gather);while (left) {size_t len =0 ;while (len < left &&iommu_iova_to_phys (domain, iova + len)) len +=PAGE_SIZE ;if (len) -iommu_unmap_nofail (domain, iova, len); +WARN_ON (iommu_unmap_fast (domain, iova, len, &gather) != + len);/* Step over the run and the hole page that ended it. */ len =min (len +PAGE_SIZE , left); iova += len; left -= len; } +iommu_iotlb_sync (domain, &gather); } static void iopt_area_unmap_domain_range(struct iopt_area *area,
@@ -1700,11 +1710,30 @@ static int iopt_provider_prot(struct iopt_area *area, u32 attrs)return prot; } +/* +* The size of the entry that maps @len bytes at @iova to @paddr, the largest +* that iopt_provider_entry() looks for and that fits. Mapping each entry with +* its own call keeps the revoke from splitting a map call. +*/ +static size_t iopt_provider_entry_size (struct iommu_domain *domain, +unsigned long iova,phys_addr_t paddr, +size_t len) +{ +unsigned long sizes = domain->pgsize_bitmap & +GENMASK (PUD_SHIFT ,PAGE_SHIFT +1 ); +u64 align = iova | paddr; + + sizes &=GENMASK (__fls (len),0 ); +if (align) + sizes &=GENMASK_ULL (__ffs64 (align),0 ); +return sizes ?BIT (__fls (sizes)) :PAGE_SIZE ; +} +/* * Map what the provider backs in [start_index, last_index] of the area into -* @domain, and leave the holes unmapped. Each frame is mapped with a -* PAGE_SIZE entry, so that a revoke of part of a large block never has to -* split a larger IOMMU page. On failure nothing in the range is mapped. +* @domain, and leave the holes unmapped. Each block that the provider reports +* is mapped with the largest entries that the IOVA and the frames allow, one +* call per entry. On failure nothing in the range is mapped. */ static int iopt_provider_map(struct iopt_area *area, struct iopt_pages *pages, struct iommu_domain *domain,
@@ -1729,7 +1758,8 @@ static int iopt_provider_map(struct iopt_area *area, struct iopt_pages *pages,return -EOPNOTSUPP ;while (index <= last_index) { -unsigned long pfn, iova, block_end, nr, i; +unsigned long pfn, iova, block_end, nr; +size_t len, done, size;int order =PUD_ORDER ;u32 attrs;int prot;
@@ -1752,20 +1782,25 @@ static int iopt_provider_map(struct iopt_area *area, struct iopt_pages *pages, iova =iopt_area_index_to_iova (area, index); prot =iopt_provider_prot (area, attrs); -for (i =0 ; i < nr; i++) { - rc =iommu_map_nosync (domain, iova + i *PAGE_SIZE , -PFN_PHYS (pfn + i),PAGE_SIZE , prot, + len = nr *PAGE_SIZE ; +for (done =0 ; done < len; done += size) { + size =iopt_provider_entry_size (domain, iova + done, +PFN_PHYS (pfn) + done, + len - done); +/* On failure, iommu_map_nosync() unmaps what it mapped. */ + rc =iommu_map_nosync (domain, iova + done, +PFN_PHYS (pfn) + done, size, prot,GFP_KERNEL_ACCOUNT );if (rc)break ; } -if (i) { -int sync_rc =iommu_sync_map (domain, iova, i *PAGE_SIZE ); + index += done >>PAGE_SHIFT ; +if (done) { +int sync_rc =iommu_sync_map (domain, iova, done);if (!rc) rc = sync_rc; } - index += i;if (rc) goto err_unmap; }
@@ -1804,9 +1839,51 @@ static int iopt_provider_fill_domains(struct iopt_area *area,return rc; } +/* +* Find the large entry that may hold page @index, which iopt_provider_unmap() +* can only remove whole, and return its first and last index. An entry of a +* given size is aligned to it, lies inside the area, and maps its pages +* linearly, so look for the largest such block around @index. Mapped pages +* that only look like one entry make the revoke remap more than it must, which +* is harmless. +*/ +static void iopt_provider_entry (struct iopt_area *area, +struct iommu_domain *domain, +unsigned long index,unsigned long *first, +unsigned long *last) +{ +unsigned long iova =iopt_area_index_to_iova (area, index); +/* iopt_provider_map() maps at most a PUD-sized block at once. */ +unsigned long sizes = domain->pgsize_bitmap & +GENMASK (PUD_SHIFT ,PAGE_SHIFT +1 ); +phys_addr_t phys =iommu_iova_to_phys (domain, iova); + + *first = *last = index; +if (!phys) +return ; + +while (sizes) { +unsigned long size =BIT (__fls (sizes)); +unsigned long start =ALIGN_DOWN (iova, size); +unsigned long end = start + size -PAGE_SIZE ; + + sizes &= ~size; +if (start <iopt_area_iova (area) || + end +PAGE_SIZE -1 >iopt_area_last_iova (area)) +continue ; +if (iommu_iova_to_phys (domain, start) != phys - (iova - start) || +iommu_iova_to_phys (domain, end) != phys + (end - iova)) +continue ; + *first =iopt_area_iova_to_index (area, start); + *last =iopt_area_iova_to_index (area, end); +return ; + } +} +/* * The provider changed the frames behind [offset, offset + len). In every -* domain, unmap the range and map what the provider backs now. A device that +* domain, unmap the range and map what the provider backs now. A large entry +* that the range cuts is unmapped and mapped again whole. A device that * accesses the range in between faults. */ static void iopt_provider_revoke(struct mem_provider_attachment *att,
@@ -1836,9 +1913,12 @@ static void iopt_provider_revoke(struct mem_provider_attachment *att,struct iopt_area *area = track->area;unsigned long s =max (first,iopt_area_index (area));unsigned long l =min (last,iopt_area_last_index (area)); +unsigned long unused;if (s > l)continue ; +iopt_provider_entry (area, track->domain, s, &s, &unused); +iopt_provider_entry (area, track->domain, l, &unused, &l);iopt_provider_unmap (area, track->domain, s, l); rc =iopt_provider_map (area, pages, track->domain, s, l);if (rc)
include/uapi/linux/iommufd.h +8 -3
@@ -241,9 +241,14 @@ struct iommu_ioas_map {* 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. +* access to a page that is being changed, or that is not backed, faults. +* Large IOMMU pages are used where @iova and the provider's memory are aligned +* alike; a change to part of a large page remaps all of it, so a device may +* also fault on the rest of it while that happens. If the remap after a change +* fails, the range stays unmapped; userspace recovers by unmapping the file +* and mapping it again. 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;
Signature · 1 line
2.47.3
Re: [RFC PATCH v2 07/11] iommufd: Use large IOMMU pages for provider mappings
Quoted 11 lines · Fred Griffoul
From: Fred Griffoul <[email protected]>
Provider pages are mapped with one
PAGE_SIZEentry each. A device that uses a large provider block then misses in the IOTLB on every page, and the IOMMU needs more page table memory than the block requires. A revoke also flushes the IOTLB once per run of pages it unmaps.Map each block that the provider reports with large IOMMU pages where the IOVA and the frames are aligned alike, and with smaller ones where they are not. Only the pages of the block are mapped, as before.
Quoted 6 lines
A large IOMMU page can only be unmapped whole, so a revoke that cuts one widens its range to the whole page. It maps back what the provider backs now, and a device may also fault on the rest of that page while it is remapped. The widening finds the page with
iova_to_phys():
pages that only look like one large page make the revoke remap more than it must, which is harmless.
You are going to need to go into generic_pt and implement cut and a more suitable unmap to make this stuff work properly. We can't over unmap on conversions.
Quoted 4 lines
iommu_unmap()may not split the range of one map call either, and virtio-iommu refuses to. Map each IOMMU page with its own call: the widened range ends on IOMMU page boundaries, so it also ends on map call boundaries.
Also please don't write commit messages with AI. WTF is this even trying to say? The subject is "use large pages" and this text says "map each page with its own call"
Jason
Re: [RFC PATCH v2 07/11] iommufd: Use large IOMMU pages for provider mappings
Quoted 3 lines · Jason Gunthorpe
You are going to need to go into
generic_ptand implement cut and a more suitable unmap to make this stuff work properly. We can't over unmap on conversions.
Agreed. I'll drop this patch from v3 for now.
Just to check I understand what you have in mind: a cut operation in generic_pt that splits a large entry in place into smaller ones, so that the revoke unmaps exactly its range, and iommufd uses large pages only on domains that support it?
Quoted 3 lines
Also please don't write commit messages with AI. WTF is this even trying to say? The subject is "use large pages" and this text says "map each page with its own call"
Sorry about that. It goes away with the patch, and I'll check and rewrite the other commit messages for v3.
Fred
RFC PATCH v2 8/11 iommufd/selftest: Add mock-domain IOVA queries
In reply to Fred GriffoulFrom: 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
@@ -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
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [RFC PATCH v2 08/11] iommufd/selftest: Add mock-domain IOVA queries
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] iommufd: soft lockup in iommufd_test_md_check_mapped loop - [Medium] iommufd: UAF race between…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] iommufd: soft lockup in iommufd_test_md_check_mapped loop
- [Medium] iommufd: UAF race between mock page table walk and dma-buf revoke --
commit 64ca9f35d00cc158de5f4700e220a39eb8a04615
Author: Fred Griffoul <[email protected]>
iommufd/selftest: Add mock-domain IOVA queries
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.
Quoted 4 lines
drivers/iommu/iommufd/selftest.c +0
-0
[ ... ]
Quoted 12 lines
drivers/iommu/iommufd/selftest.c +12
-0+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))
drivers/iommu/iommufd/selftest.c static int iommufd_test_dmabuf_get(struct iommufd_ucmd *ucmd, · line 2089
Quoted 10 lines
drivers/iommu/iommufd/selftest.c +10
-0+return PTR_ERR (hwpt); + + page_size =1 <<__ffs (mock->domain.pgsize_bitmap); +if (iova % page_size || !mock_domain_covers (mock, iova, page_size)) { + rc = -EINVAL ; + goto out_put; + } +down_write (mock_domain_unmap_lock (hwpt)); + cmd->iova_to_phys.out_phys = + mock->domain.ops->iova_to_phys (&mock->domain, iova);
[Severity: Medium]
Could this page table walk race with a concurrent dma-buf revoke or memory provider unmap?
Since those unmap operations run under their own pages mutex instead of domains_rwsem, it seems possible for a concurrent unmap (for instance, triggered by a fuzzer or concurrently running test) to free a page table level while iova_to_phys() is still walking it, potentially leading to a use-after-free.
Quoted 12 lines
drivers/iommu/iommufd/selftest.c +12
-0+up_write (mock_domain_unmap_lock (hwpt)); + 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) +{
[ ... ]
drivers/iommu/iommufd/selftest.c static int iommufd_test_dmabuf_get(struct iommufd_ucmd *ucmd, · line 2121
Quoted 4 lines
drivers/iommu/iommufd/selftest.c +4
-0+down_write (mock_domain_unmap_lock (hwpt)); +for (; length; length -= page_size, iova += page_size) { +bool is_mapped = + mock->domain.ops->iova_to_phys (&mock->domain, iova) !=0 ;
[Severity: Medium]
Can this loop run for an unbounded amount of time and cause a soft lockup?
Since the test ioctl interface allows very large values for length, and page_size can be as small as 4096 bytes, this loop could iterate trillions of times without yielding.
Because it holds domains_rwsem for writing, would this stall the CPU and starve other users of the semaphore?
Quoted 12 lines
drivers/iommu/iommufd/selftest.c +12
-0+ +if (is_mapped != mapped) { + rc = -ENOENT ; +break ; + } + } +up_write (mock_domain_unmap_lock (hwpt)); + +out_put: +iommufd_put_object (ucmd->ictx, &hwpt->obj); +return rc; +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
RFC PATCH v2 9/11 iommufd/selftest: Add a mock memory provider
In reply to Fred GriffoulFrom: 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. It can also back the file with one contiguous allocation and report large blocks. Test that holes stay unmapped and that a revoke changes only its range, also inside a large IOMMU page. Also test 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 | 24 ++ drivers/iommu/iommufd/selftest.c | 216 ++++++++++++++++++ tools/testing/selftests/iommu/iommufd.c | 185 +++++++++++++++ tools/testing/selftests/iommu/iommufd_utils.h | 69 ++++++ 4 files changed, 494 insertions(+)
drivers/iommu/iommufd/iommufd_test.h +24 -0
@@ -33,8 +33,22 @@ 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 , +}; + +/* IOMMU_TEST_OP_PROVIDER_GET: back the file with one contiguous allocation */ +#define MOCK_PROVIDER_FLAG_CONTIG (1 << 0) +enum {MOCK_IOMMUPT_DEFAULT =0 , MOCK_IOMMUPT_HUGE,
@@ -209,6 +223,16 @@ struct iommu_test_cmd {__aligned_u64 iova;__aligned_u64 out_phys;/* 0 if unmapped */ } iova_to_phys; +struct { +__u32 length; +__u32 flags; + } provider_get; +struct { +__s32 fd; +__u32 state; +__aligned_u64 offset; +__aligned_u64 length; + } provider_set; };__u32 last; };
drivers/iommu/iommufd/selftest.c +216 -0
234 lines not on this page · raw message
tools/testing/selftests/iommu/iommufd.c +185 -0
191 lines not on this page · raw message
tools/testing/selftests/iommu/iommufd_utils.h +69 -0
75 lines not on this page · raw message
Signature · 1 line
2.47.3
RFC PATCH v2 10/11 samples/kvm: Add a memory provider sample
In reply to Fred GriffoulFrom: 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.
--- MAINTAINERS | 1 + samples/Kconfig | 17 + samples/Makefile | 1 + samples/kvm/Makefile | 2 + samples/kvm/mem_provider_sample.c | 855 ++++++++++++++++++++++++++++++ samples/kvm/mem_provider_sample.h | 135 +++++ 6 files changed, 1011 insertions(+) create mode 100644 samples/kvm/Makefile create mode 100644 samples/kvm/mem_provider_sample.c create mode 100644 samples/kvm/mem_provider_sample.h
MAINTAINERS +1 -0
@@ -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
@@ -326,6 +326,23 @@ source "samples/rust/Kconfig" source "samples/damon/Kconfig" +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
@@ -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_MEM_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
@@ -0,0 +1,2 @@ +# SPDX-License-Identifier: GPL-2.0 +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
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [RFC PATCH v2 10/11] samples/kvm: Add a memory provider sample
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Critical] kvm: misaligned huge page PFN causes host memory corruption - [High] mm: bitmap integer…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Critical] kvm: misaligned huge page PFN causes host memory corruption
- [High] mm: bitmap integer truncation leads to out-of-bounds write
--
commit 361e4f16cd6774e9f8e63152565759849581de53
Author: Fred Griffoul <[email protected]>
samples/kvm: Add a memory provider sample
This patch adds a sample memory provider for guest_memfd and iommufd. It lends a physical memory region, either given by addr/len parameters or allocated via alloc_contig_pages(), to guest VMs and moves pages between children.
Quoted 5 lines
samples/kvm/mem_provider_sample.c new file +0
-0@@ -0,0 +1,855 @@
[ ... ]
Quoted 13 lines
samples/kvm/mem_provider_sample.c new file +13
-0+static int mps_mp_get_page (struct mem_provider_file *mpf,pgoff_t index, +unsigned long *pfn,int *max_order,u32 *attrs) +{ + struct mps_info *info = container_of(mpf, struct mps_info, mpf); +unsigned long run; + +if (index >= info->npages) +return -EINVAL ; + +if (!mps_page_present (info, index)) +return -EFAULT ; + +/* The aligned block around @index must be one run. */
samples/kvm/mem_provider_sample.c line 211
Quoted 10 lines
samples/kvm/mem_provider_sample.c new file +10
-0+ run =mps_run (info, index); +while (*max_order) { +unsigned long first =ALIGN_DOWN (index,1UL << *max_order); + +if (first + (1UL << *max_order) <= index + run && + (first == index ||mps_page_present (info, first)) && +mps_run (info, first) >=1UL << *max_order) +break ; + (*max_order)--; + }
[Severity: Critical]
Are we missing a hardware PFN alignment check for huge pages?
The loop validates that the internal state is consistent for a block, but doesn't verify if info->base_pfn + first is naturally aligned to the huge page boundary (1UL << *max_order).
Because alloc_contig_pages() or the addr module parameter do not guarantee alignment to arbitrary huge page boundaries, KVM or the hardware MMU could force alignment by masking the lower bits of the PFN. Would this result in the guest mapping memory before the intended base_pfn and accessing unowned host memory?
[ ... ]
samples/kvm/mem_provider_sample.c line 259
Quoted 8 lines
samples/kvm/mem_provider_sample.c new file +8
-0+static void mps_set_readonly (struct mps_info *info,unsigned long start, +unsigned long end,bool readonly) +{ +mutex_lock (&info->lock); +if (readonly) +bitmap_set (info->readonly, start, end - start); +else +bitmap_clear (info->readonly, start, end - start);
[Severity: High]
Can start and end - start silently truncate here?
These parameters are unsigned long, but bitmap_set() and bitmap_clear() expect unsigned int for the start and nbits arguments. If the region size is extremely large, this could result in mapping into a truncated bitmap footprint and corrupting adjacent kernel heap memory.
Quoted 3 lines
samples/kvm/mem_provider_sample.c new file +3
-0+mps_revoke (info, start, end); +mutex_unlock (&info->lock); +}
[ ... ]
Quoted 7 lines
samples/kvm/mem_provider_sample.c new file +7
-0+static int mps_new_file (unsigned long base_pfn,unsigned long npages, +u32 flags,struct mps_info **infop, +struct file **filep) +{ +struct mps_info *info; +struct file *file; +int fd, ret;
samples/kvm/mem_provider_sample.c line 375
Quoted 10 lines
samples/kvm/mem_provider_sample.c new file +10
-0+ + info =kzalloc_obj (*info); +if (!info) +return -ENOMEM ; +mem_provider_file_init (&info->mpf); + info->base_pfn = base_pfn; + info->npages = npages; + info->mmap_capable = flags &MPS_FLAG_MMAP_CAPABLE ; + info->absent =bitmap_zalloc (npages,GFP_KERNEL ); + info->readonly =bitmap_zalloc (npages,GFP_KERNEL );
[Severity: High]
Will the allocation size be truncated here?
The npages parameter is an unsigned long derived from the user-controlled setup.size (via ioctl) or the len module parameter. Because bitmap_zalloc() accepts an unsigned int for nbits, any npages value exceeding UINT_MAX (e.g., a region > 16 TB) will be silently truncated, causing massively undersized bitmaps to be allocated.
Quoted 4 lines
samples/kvm/mem_provider_sample.c new file +4
-0+if (!info->absent || !info->readonly) { + ret = -ENOMEM ; + goto err_free; + }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
RFC PATCH v2 11/11 KVM: selftests: Test a memory provider shared by KVM and iommufd
In reply to Fred GriffoulFrom: 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.
A third VM, on a child that starts on a 2 MiB boundary, checks that KVM maps the provider's block with a 2 MiB page, and that donating a page inside the block takes that mapping away. It skips if the provider's frames are not aligned.
--- tools/testing/selftests/kvm/Makefile.kvm | 1 + .../selftests/kvm/x86/mem_provider_test.c | 653 ++++++++++++++++++ 2 files changed, 654 insertions(+) create mode 100644 tools/testing/selftests/kvm/x86/mem_provider_test.c
tools/testing/selftests/kvm/Makefile.kvm +1 -0
@@ -89,6 +89,7 @@ TEST_GEN_PROGS_x86 += x86/hyperv_tlb_flush TEST_GEN_PROGS_x86 += x86/kvm_clock_test TEST_GEN_PROGS_x86 += x86/kvm_pv_test TEST_GEN_PROGS_x86 += x86/kvm_buslock_test +TEST_GEN_PROGS_x86 += x86/mem_provider_test TEST_GEN_PROGS_x86 += x86/monitor_mwait_test TEST_GEN_PROGS_x86 += x86/msrs_test TEST_GEN_PROGS_x86 += x86/nested_close_kvm_test
tools/testing/selftests/kvm/x86/mem_provider_test.c new file +653 -0
653 lines not on this page · raw message
Signature · 1 line
2.47.3
Quoted 2 lines · Fred Griffoul
From: Fred Griffoul <[email protected]>
[ ... 24 lines skipped ... ]
Quoted 11 lines
Why a new interface
===================
kvm_gmem_opsgives KVM a way in. For devices, the only option today is a dma-buf plus a private call that iommufd looks up withsymbol_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 needssymbol_get().
Quoted 6 lines
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_memfdfrom the VMM's own mapping, all before the revoke returns.
What confused me was the introduction of memory providers as a subsystem in their own. What we really need is the ability to map PFNs from other subsystems into KVM stage-2 and into subsystems such as iommufd?.
Restricting the scope to the above, at least initially, would make this much easier to reason about.
For my use case, the VFIO fd becomes the backing provider (referred to as backend below). We can create a guest_memfd using that resource_fd, allowing MMIO BAR ranges to be mapped into KVM stage-2.
Another feature provided by this series is the ability to map the same range into iommufd. We probably want to restrict this to shared ranges. It may be simpler for guest_memfd to drive this. The resulting relationship would be:
+-----------------------+
| VFIO PCI BAR backing |
+-----------------------+
|
| guest_memfd_backing_ops
| Supplies BAR PFNs
v
+------------------------------------------+
| guest_memfd |
| |
| Controls shared/private state |
| Exports shared, accessible PFNs |
| Revokes consumer mappings when needed |
+------------------------------------------+
|
| mem_provider_ops
| IOAS_MAP_FILE(fd = guest_memfd)
v
+-----------------------+
| IOMMUFD |
| |
| Creates and refreshes |
| IOMMU DMA mappings |
+-----------------------+
| v
Device DMA access
Another capability the memory-provider interface could provide is kernel-initiated IOAS mapping, for example by allowing a guest_memfd fd to be used with IOAS_MAP_FILE.
Currently, a private-to-shared conversion causes a VM exit, followed by an IOAS_MAP for the newly shared range. Could using guest_memfd with IOAS_MAP_FILE avoid this?
Perhaps the series could be rearranged as follows:
- Allow a guest_memfd fd to be used with IOAS_MAP_FILE.
- Add a VFIO or other backend for guest_memfd, without calling it a provider.
- Add support for guest_memfd to provide guest PFNs to other subsystems through its file descriptor.
Would this work?
-aneesh
Quoted 6 lines · Aneesh Kumar K.V
What confused me was the introduction of memory providers as a subsystem in their own. What we really need is the ability to map PFNs from other subsystems into KVM stage-2 and into subsystems such as iommufd?.
Restricting the scope to the above, at least initially, would make this much easier to reason about.
Thanks for looking at it. I should have explained this better in the cover letter.
A memory provider is the driver that owns some memory, like a carve-out or a device BAR. It lends pages to whoever maps them, and it can take any of them back later. guest_memfd is one user of that memory, and iommufd is another, but neither depends on the other.
With this series, iommufd can map a provider file without any VM. Today it cannot map such memory, because memory without struct page cannot be pinned. For example, a host service that recycles provider memory between VMs could clear it with a DMA engine driven through VFIO and iommufd, instead of the CPU. And since such memory can outlive the process, or a kexec of the host, a network or storage dataplane could restart or be updated without losing its DMA buffers.
Quoted 3 lines
For my use case, the VFIO fd becomes the backing provider (referred to as backend below). We can create a
guest_memfdusing thatresource_fd, allowing MMIO BAR ranges to be mapped into KVM stage-2.
That fits well. VFIO could be a provider for its BARs: get_page() reports the BAR frames with the MMIO type. guest_memfd takes the VFIO fd as resource_fd, and iommufd can map the same fd. That could also replace the dma-buf plus symbol_get() path that iommufd uses for vfio-pci today.
Quoted 3 lines
Another feature provided by this series is the ability to map the same range into iommufd. We probably want to restrict this to shared ranges. It may be simpler for
guest_memfdto drive this.
Agreed that guest_memfd must drive shared and private. I replied to Ackerley on how that could work with the provider interface:
https://lore.kernel.org/all/[email protected]/
In short, on a conversion to private, guest_memfd claims the range on the provider file. The provider code in mm then revokes it for every other consumer, iommufd included, and hands them holes until guest_memfd unclaims it. So guest_memfd stays in charge of conversions, and iommufd only ever maps shared pages, without going through guest_memfd.
Quoted 3 lines
Currently, a private-to-shared conversion causes a VM exit, followed by an
IOAS_MAPfor the newly shared range. Could usingguest_memfdwithIOAS_MAP_FILEavoid this?
Yes, the IOAS_MAP goes away. The conversion itself still comes through the VMM, but once guest_memfd unclaims the range, iommufd maps the pages again on its own.
Quoted 6 lines
Perhaps the series could be rearranged as follows:
- Allow a
guest_memfdfd to be used withIOAS_MAP_FILE.
- Add a VFIO or other backend forguest_memfd, without calling it a provider.
- Add support forguest_memfdto provide guest PFNs to other subsystems through its file descriptor.
I'd rather not make guest_memfd the only way in. With kvm_gmem_ops, each backend implements a guest_memfd: it binds memslots, invalidates KVM's mappings, handles the host mapping, and for confidential VMs prepares the frames and gives them back to the host. That puts KVM internals in every driver. With a provider, the driver only reports its frames and revokes them, and guest_memfd does the KVM side once, for every provider.
Your diagram already uses mem_provider_ops between guest_memfd and iommufd. It is the same interface: get the frame behind a page, and revoke a range. So I'd define it once and let drivers use it too. That also covers the cases above, where there is no VM and no guest_memfd to go through.
guest_memfd can still provide its own file to iommufd where there is no provider behind it, for a guest_memfd that allocates folios. That would use the same interface, and the same iommufd code.
Would that work for your VFIO case?
Thanks,
Fred