Skip to contentSkip to conversation

KVM/VFIO: guest_memfd support for device MMIO resources

RFC PATCH Superseded Aneesh Kumar K.V (Arm) 2 participants 11 messages Oct 10 – Oct 16

Subsystems (6)
Documentation KVM IOMMU VFIO driver +2 more subsystems

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover KVM/VFIO: guest_memfd support for device MMIO resources

This series adds a guest_memfd device-resource framework for exposing PCI BAR memory to guests. The intended use is confidential device assignment, where KVM needs to coordinate private device mappings with shared access through VFIO. The Arm CCA backend is provided separately; these patches contain the guest_memfd, VFIO and IOMMUFD interfaces it uses.

The guest_memfd framework and Arm CCA backend are available together at:

https://git.gitlab.arm.com/linux-arm/linux-cca.git cca/topics/cca-da-gmem-backend

Userspace creates a device-backed guest_memfd using the ordinary VFIO device fd as resource_fd, with GUEST_MEMFD_FLAG_USE_RESOURCE, GUEST_MEMFD_FLAG_DEVICE and GUEST_MEMFD_FLAG_INIT_SHARED. Eligible BAR intervals are registered as guest_memfd memslots. File offsets use the existing VFIO region-offset namespace, allowing one guest_memfd to cover multiple BAR intervals. Device-backed guest_memfd rejects mmap and fallocate; shared guest faults obtain bare BAR PFNs from the provider instead of resolving the memslot HVA or allocating folios.

IOMMUFD resolves and pins the device's existing vDEVICE for the VM and serializes MMIO conversion through its MMIO mutex. VFIO supplies BAR PFNs, checks eligible ranges and excludes independent dma-buf exports while a guest_memfd provider is attached. VFIO host mmap faults, read/write and ioeventfd accesses check the requested range's guest_memfd attributes. Conversion revokes cached host mappings and shared guest mappings before installing private mappings. Other shared intervals remain accessible.

This series depends on:
* Ackerley Tng's "Allow guest_memfd to be created using a resource (pool) fd" RFC, which provides the tmpfs resource-provider API:
https://lore.kernel.org/all/[email protected]/
* The IOMMUFD/TSM series, which provides the vIOMMU and vDEVICE interfaces:
https://lore.kernel.org/all/[email protected]/

Notes:
* While developing this framework, I looked at David Woodhouse's guest_memfd provider work, including the gmem-provider-v3 branch. It was used for comparison and was not merged. The posted RFC v2 is here:
https://lore.kernel.org/all/[email protected]/
* Codex assisted with implementation, review and series organization.

Cc Ackerley Tng <[email protected]>
Cc Alex Williamson <[email protected]>
Cc David Woodhouse <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc "Joerg Roedel (AMD)" <[email protected]>
Cc Kevin Tian <[email protected]>
Cc Paolo Bonzini <[email protected]>
Cc Robin Murphy <[email protected]>
Cc Sean Christopherson <[email protected]>
Cc Will Deacon <[email protected]>
Cc Alexey Kardashevskiy <[email protected]>
Cc Xu Yilun <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Suzuki K Poulose <[email protected]>
Cc Steven Price <[email protected]>
Cc Fred Griffoul <[email protected]>

Aneesh Kumar K.V (Arm) (6):
KVM: guest_memfd: attach and bind device resources
KVM: guest_memfd: Support private/shared conversion of device memory
iommufd: Support MMIO provider attachment to vDEVICEs vfio/pci: Provide guest_memfd backing for PCI BARs KVM/VFIO: Remove device mappings during guest_memfd teardown
KVM: Invalidate guest_memfd mappings before removing memslot bindings

 Documentation/virt/kvm/api.rst          |   4 +
 drivers/iommu/iommufd/viommu.c          |  90 ++++
 drivers/vfio/device_cdev.c              |   3 +-
 drivers/vfio/group.c                    |   4 +-
 drivers/vfio/pci/Kconfig                |  11 +
 drivers/vfio/pci/Makefile               |   2 +
 drivers/vfio/pci/vfio_pci.c             |   3 +
 drivers/vfio/pci/vfio_pci_core.c        |  13 +
 drivers/vfio/pci/vfio_pci_dmabuf.c      |  10 +
 drivers/vfio/pci/vfio_pci_gmem.c        | 349 +++++++++++++++
 drivers/vfio/pci/vfio_pci_gmem.h        |  36 ++
 drivers/vfio/pci/vfio_pci_gmem_access.c | 138 ++++++
 drivers/vfio/pci/vfio_pci_rdwr.c        |  13 +-
 drivers/vfio/vfio.h                     |   8 +
 drivers/vfio/vfio_main.c                |  34 +-
 include/linux/guest_memfd.h             |  50 +++
 include/linux/iommufd.h                 |  33 ++
 include/linux/kvm_host.h                |  14 +-
 include/linux/vfio.h                    |   3 +
 include/linux/vfio_pci_core.h           |  23 +
 include/uapi/linux/kvm.h                |   1 +
 virt/kvm/guest_memfd.c                  | 545 +++++++++++++++++++++++-
 virt/kvm/guest_memfd.h                  |   6 +
 virt/kvm/kvm_main.c                     |   4 +
 24 files changed, 1362 insertions(+), 35 deletions(-)
 create mode 100644 drivers/vfio/pci/vfio_pci_gmem.c
 create mode 100644 drivers/vfio/pci/vfio_pci_gmem.h
 create mode 100644 drivers/vfio/pci/vfio_pci_gmem_access.c
Signature · 1 line
2.43.0
#1 lore raw

RFC PATCH 1/6 KVM: guest_memfd: attach and bind device resources

Introduce the device resource flag and registration of a provider file operations identity. KVM checks file->f_op before interpreting private_data as guest_memfd_device_operations.

Add attach() to establish the provider, bind() to associate eligible file offsets with memslots, get_pfn() for shared device PFNs, release() for the provider lifetime.

Cc Paolo Bonzini <[email protected]>
Cc Sean Christopherson <[email protected]>
Cc David Hildenbrand <[email protected]>
Assisted-by Codex
---
 Documentation/virt/kvm/api.rst |   4 +
 include/linux/guest_memfd.h    |  34 +++++++
 include/linux/kvm_host.h       |   9 +-
 include/uapi/linux/kvm.h       |   1 +
 virt/kvm/guest_memfd.c         | 167 ++++++++++++++++++++++++++++++---
 5 files changed, 202 insertions(+), 13 deletions(-)
Documentation/virt/kvm/api.rst +4 -0
index 5ece28765d2c..a4abee9f1ce1 100644
@@ -6527,6 +6527,10 @@ specified via KVM_CREATE_GUEST_MEMFD.  Currently defined flags:
                                 must be a supported resource (e.g. tmpfs mount
                                 root directory). Currently, tmpfs resource pools
                                 require noswap and huge=never mount options.
+  GUEST_MEMFD_FLAG_DEVICE       Use a device resource file as resource_fd. Requires
+                                GUEST_MEMFD_FLAG_USE_RESOURCE and
+                                GUEST_MEMFD_FLAG_INIT_SHARED; mmap is disallowed.
+                                The fd must expose guest_memfd device operations.
   ============================= ================================================
 
 When the KVM MMU performs a PFN lookup to service a guest fault, the fault will
include/linux/guest_memfd.h +34 -0
index 60eb4f008c24..4f232612a525 100644
@@ -5,8 +5,42 @@
 #include <linux/types.h>
 
 struct file;
+struct file_operations;
 struct folio;
 struct mempolicy;
+struct kvm;
+struct guest_memfd_device;
+
+/* Binding data stays valid only while the device guest_memfd is active. */
+struct guest_memfd_device_binding {
+	/* Architecture-specific mapping owner, e.g. an RMM vDEVICE handle. */
+	unsigned long owner;
+	u64 vdev_id;
+};
+
+/* Embedded by a device provider and returned from attach(). */
+struct guest_memfd_device_context {
+	struct guest_memfd_device *device;
+};
+
+struct guest_memfd_device_operations {
+	struct guest_memfd_device_context *(*attach)(struct file *resource,
+		struct guest_memfd_device *gdev);
+	int (*bind)(void *data, u64 offset, u64 size,
+		struct guest_memfd_device_binding *binding);
+	int (*get_pfn)(void *data, u64 offset, unsigned long *pfn);
+	void (*release)(void *data);
+};
+
+/* A registered file type stores device operations in file->private_data. */
+int guest_memfd_register_device_fops(const struct file_operations *fops);
+void guest_memfd_unregister_device_fops(const struct file_operations *fops);
+
+struct guest_memfd_device {
+	struct kvm *kvm;
+	u64 size;
+	void *core;
+};
 
 /**
  * struct guest_memfd_provider_operations - Operations for external memory providers
include/linux/kvm_host.h +8 -1
index 1dda54e8dee8..f1675a3e00b6 100644
@@ -56,6 +56,7 @@
  */
 #define KVM_MEMSLOT_INVALID			(1UL << 16)
 #define KVM_MEMSLOT_GMEM_ONLY			(1UL << 17)
+#define KVM_MEMSLOT_GMEM_DEVICE			(1UL << 18)
 
 /*
  * Bit 63 of the memslot generation number is an "update in-progress flag",
@@ -2605,16 +2606,22 @@ static inline bool kvm_is_private_gfn(struct kvm *kvm, gfn_t gfn)
 #endif /* kvm_arch_has_private_mem */
 
 #ifdef CONFIG_KVM_GUEST_MEMFD
+struct guest_memfd_device_binding;
+
 bool kvm_gmem_is_private_gfn(struct kvm *kvm, gfn_t gfn);
 bool kvm_gmem_range_has_attributes(struct kvm_memory_slot *slot, gfn_t start,
 				   gfn_t end, u64 attributes);
+bool kvm_arch_gmem_device_supported(struct kvm *kvm);
+void kvm_arch_gmem_device_bind(struct kvm_memory_slot *slot,
+		const struct guest_memfd_device_binding *binding);
 int kvm_gmem_set_attributes(struct kvm_memory_slot *slot, gfn_t start,
 			    gfn_t end, u64 attributes);
 bool kvm_arch_supports_gmem_init_shared(struct kvm *kvm);
 
 static inline u64 kvm_gmem_get_supported_flags(struct kvm *kvm)
 {
-	u64 flags = GUEST_MEMFD_FLAG_MMAP | GUEST_MEMFD_FLAG_USE_RESOURCE;
+	u64 flags = GUEST_MEMFD_FLAG_MMAP | GUEST_MEMFD_FLAG_USE_RESOURCE |
+		    GUEST_MEMFD_FLAG_DEVICE;
 
 	if (!kvm || kvm_arch_supports_gmem_init_shared(kvm))
 		flags |= GUEST_MEMFD_FLAG_INIT_SHARED;
include/uapi/linux/kvm.h +1 -0
index 9408ddde164a..b0d853f88ca8 100644
@@ -1681,6 +1681,7 @@ struct kvm_memory_attributes2 {
 #define GUEST_MEMFD_FLAG_MMAP		(1ULL << 0)
 #define GUEST_MEMFD_FLAG_INIT_SHARED	(1ULL << 1)
 #define GUEST_MEMFD_FLAG_USE_RESOURCE	(1ULL << 2)
+#define GUEST_MEMFD_FLAG_DEVICE		(1ULL << 3)
 
 struct kvm_create_guest_memfd {
 	__u64 size;
virt/kvm/guest_memfd.c +155 -12

316 lines not on this page · raw message

Signature · 1 line
2.43.0
#2 lore raw

RFC PATCH 2/6 KVM: guest_memfd: Support private/shared conversion of device memory

In reply to Aneesh Kumar K.V (Arm)

Allow architectures to convert device-backed guest_memfd ranges to private memory. Coordinate conversion with the device provider and update guest_memfd attributes only after the architecture operation succeeds.

Hold the inode invalidate lock across conversion and the attribute update. Provider callbacks allow a device conversion lock to cover the same operation, with the inode lock acquired first. This prevents faults and competing device operations from observing an incomplete conversion.

Cc Paolo Bonzini <[email protected]>
Cc Sean Christopherson <[email protected]>
Cc David Hildenbrand <[email protected]>
Assisted-by Codex
---
 include/linux/guest_memfd.h |  12 +++
 include/linux/kvm_host.h    |   5 +
 virt/kvm/guest_memfd.c      | 186 +++++++++++++++++++++++++++++++++++-
 3 files changed, 201 insertions(+), 2 deletions(-)
include/linux/guest_memfd.h +12 -0
index 4f232612a525..b566c581f04d 100644
@@ -11,6 +11,13 @@ struct mempolicy;
 struct kvm;
 struct guest_memfd_device;
 
+/* Claims come from a pending architecture exit, never from a userspace PA. */
+struct guest_memfd_device_request {
+	u64 gpa;
+	u64 pa;
+	u64 vdev_id;
+};
+
 /* Binding data stays valid only while the device guest_memfd is active. */
 struct guest_memfd_device_binding {
 	/* Architecture-specific mapping owner, e.g. an RMM vDEVICE handle. */
@@ -29,6 +36,11 @@ struct guest_memfd_device_operations {
 	int (*bind)(void *data, u64 offset, u64 size,
 		struct guest_memfd_device_binding *binding);
 	int (*get_pfn)(void *data, u64 offset, unsigned long *pfn);
+	/* A protected request prepares private mapping; NULL prepares sharing. */
+	int (*prepare_conversion)(struct guest_memfd_device_context *context,
+		const struct guest_memfd_device_request *req);
+	void (*finish_conversion)(struct guest_memfd_device_context *context,
+		const struct guest_memfd_device_request *req);
 	void (*release)(void *data);
 };
 
include/linux/kvm_host.h +5 -0
index f1675a3e00b6..32bd56f39f59 100644
@@ -2614,6 +2614,11 @@ bool kvm_gmem_range_has_attributes(struct kvm_memory_slot *slot, gfn_t start,
 bool kvm_arch_gmem_device_supported(struct kvm *kvm);
 void kvm_arch_gmem_device_bind(struct kvm_memory_slot *slot,
 		const struct guest_memfd_device_binding *binding);
+int kvm_arch_gmem_device_map(struct kvm *kvm,
+		const struct kvm_memory_slot *slot,
+		u64 gpa, u64 size, u64 pa);
+int kvm_arch_gmem_device_unmap(struct kvm *kvm, u64 gpa, u64 size);
+int kvm_gmem_device_map(struct kvm *kvm, u64 gpa, u64 size, u64 pa, u64 vdev_id);
 int kvm_gmem_set_attributes(struct kvm_memory_slot *slot, gfn_t start,
 			    gfn_t end, u64 attributes);
 bool kvm_arch_supports_gmem_init_shared(struct kvm *kvm);
virt/kvm/guest_memfd.c +184 -2

216 lines not on this page · raw message

Signature · 1 line
2.43.0
#3 lore raw

RFC PATCH 3/6 iommufd: Support MMIO provider attachment to vDEVICEs

In reply to Aneesh Kumar K.V (Arm)

Allow a device MMIO provider to attach to the existing vDEVICE after the backend validates its association with the VM. Keep the vDEVICE and IOMMUFD context alive until the provider detaches.

Add a per-vDEVICE MMIO mutex to serialize provider attachment and detachment, and allow providers and backends to use the same lock for memory conversion and device state changes. Provide callbacks to invalidate MMIO mappings and query whether private ranges remain.

Cc Jason Gunthorpe <[email protected]>
Cc Kevin Tian <[email protected]>
Cc "Joerg Roedel (AMD)" <[email protected]>
Cc Will Deacon <[email protected]>
Cc Robin Murphy <[email protected]>
Assisted-by Codex
---
 drivers/iommu/iommufd/viommu.c | 90 ++++++++++++++++++++++++++++++++++
 include/linux/iommufd.h        | 33 +++++++++++++
 2 files changed, 123 insertions(+)
drivers/iommu/iommufd/viommu.c +90 -0
index 9155d0dcb4b4..24a817fb2ae8 100644
@@ -250,6 +250,7 @@ int iommufd_vdevice_alloc_ioctl(struct iommufd_ucmd *ucmd)
 		goto out_unlock_igroup;
 	}
 
+	mutex_init(&vdev->mmio_lock);
 	vdev->virt_id = virt_id;
 	vdev->viommu = viommu;
 	refcount_inc(&viommu->obj.users);
@@ -487,3 +488,92 @@ int iommufd_hw_queue_alloc_ioctl(struct iommufd_ucmd *ucmd)
 	iommufd_put_object(ucmd->ictx, &viommu->obj);
 	return rc;
 }
+
+struct iommufd_vdevice *
+iommufd_device_attach_mmio_provider(struct iommufd_device *idev,
+		struct kvm *kvm, void *data,
+		void (*invalidate_mmio)(void *),
+		bool (*has_private_mmio)(void *),
+		unsigned long *owner)
+{
+	struct iommufd_vdevice *vdev;
+	int ret;
+
+	if (!idev)
+		return ERR_PTR(-ENODEV);
+
+	guard(mutex)(&idev->igroup->lock);
+	if (idev->destroying)
+		return ERR_PTR(-EOPNOTSUPP);
+
+	vdev = idev->vdev;
+	if (!vdev)
+		return ERR_PTR(-EOPNOTSUPP);
+
+	if (!vdev->viommu->ops ||
+	    !vdev->viommu->ops->vdevice_get_mmio_owner)
+		return ERR_PTR(-EOPNOTSUPP);
+
+	guard(mutex)(&vdev->mmio_lock);
+	if (vdev->mmio_provider_data)
+		return ERR_PTR(-EBUSY);
+
+	ret = vdev->viommu->ops->vdevice_get_mmio_owner(vdev, kvm, owner);
+	if (ret)
+		return ERR_PTR(ret);
+
+	/* IOMMU_DESTROY must wait for the attached gmem provider to detach. */
+	ret = iommufd_try_inc_users(idev->ictx, &vdev->obj);
+	if (ret)
+		return ERR_PTR(ret);
+
+	iommufd_ctx_get(idev->ictx);
+	vdev->mmio_provider_data = data;
+	vdev->invalidate_mmio = invalidate_mmio;
+	vdev->has_private_mmio = has_private_mmio;
+	invalidate_mmio(data);
+	return vdev;
+}
+EXPORT_SYMBOL_NS_GPL(iommufd_device_attach_mmio_provider, "IOMMUFD");
+
+void iommufd_vdevice_detach_mmio_provider(struct iommufd_vdevice *vdev)
+{
+	struct iommufd_ctx *ictx = vdev->viommu->ictx;
+
+	scoped_guard(mutex, &vdev->mmio_lock) {
+		WARN_ON(iommufd_vdevice_has_private_mmio(vdev));
+		vdev->mmio_provider_data = NULL;
+		vdev->invalidate_mmio = NULL;
+		vdev->has_private_mmio = NULL;
+	}
+	refcount_dec(&vdev->obj.users);
+	iommufd_ctx_put(ictx);
+}
+EXPORT_SYMBOL_NS_GPL(iommufd_vdevice_detach_mmio_provider, "IOMMUFD");
+
+void iommufd_vdevice_mmio_lock(struct iommufd_vdevice *vdev)
+{
+	mutex_lock(&vdev->mmio_lock);
+}
+EXPORT_SYMBOL_NS_GPL(iommufd_vdevice_mmio_lock, "IOMMUFD");
+
+void iommufd_vdevice_mmio_unlock(struct iommufd_vdevice *vdev)
+{
+	mutex_unlock(&vdev->mmio_lock);
+}
+EXPORT_SYMBOL_NS_GPL(iommufd_vdevice_mmio_unlock, "IOMMUFD");
+
+/**
+ * iommufd_vdevice_has_private_mmio() - check for private MMIO ranges
+ * @vdev: vDEVICE whose private MMIO state is being checked
+ *
+ * Return: true if the attached provider has committed private ranges.
+ */
+bool iommufd_vdevice_has_private_mmio(struct iommufd_vdevice *vdev)
+{
+	lockdep_assert_held(&vdev->mmio_lock);
+	if (!vdev->has_private_mmio)
+		return false;
+	return vdev->has_private_mmio(vdev->mmio_provider_data);
+}
+EXPORT_SYMBOL_NS_GPL(iommufd_vdevice_has_private_mmio, "IOMMUFD");
include/linux/iommufd.h +33 -0
index 2e67846d6f35..3f3b9d1dd22a 100644
@@ -7,10 +7,12 @@
 #define __LINUX_IOMMUFD_H
 
 #include <linux/bits.h>
+#include <linux/cleanup.h>
 #include <linux/err.h>
 #include <linux/errno.h>
 #include <linux/iommu.h>
 #include <linux/refcount.h>
+#include <linux/mutex.h>
 #include <linux/types.h>
 #include <linux/xarray.h>
 #include <uapi/linux/iommufd.h>
@@ -26,6 +28,7 @@ struct iommufd_device;
 struct iommufd_viommu_ops;
 struct tsm_dev;
 struct page;
+struct kvm;
 struct tsm_guest_req_info;
 
 enum iommufd_object_type {
@@ -73,6 +76,20 @@ int iommufd_device_replace(struct iommufd_device *idev, ioasid_t pasid,
 			   u32 *pt_id);
 void iommufd_device_detach(struct iommufd_device *idev, ioasid_t pasid);
 
+/* The returned opaque vDEVICE pins its IOMMUFD context and physical owner. */
+struct iommufd_vdevice *
+iommufd_device_attach_mmio_provider(struct iommufd_device *idev,
+		struct kvm *kvm, void *data,
+		void (*invalidate_mmio)(void *),
+		bool (*has_private_mmio)(void *),
+		unsigned long *owner);
+void iommufd_vdevice_detach_mmio_provider(struct iommufd_vdevice *vdev);
+void iommufd_vdevice_mmio_lock(struct iommufd_vdevice *vdev);
+void iommufd_vdevice_mmio_unlock(struct iommufd_vdevice *vdev);
+DEFINE_GUARD(iommufd_vdevice_mmio, struct iommufd_vdevice *,
+	     iommufd_vdevice_mmio_lock(_T), iommufd_vdevice_mmio_unlock(_T))
+bool iommufd_vdevice_has_private_mmio(struct iommufd_vdevice *vdev);
+
 struct iommufd_ctx *iommufd_device_to_ictx(struct iommufd_device *idev);
 u32 iommufd_device_to_id(struct iommufd_device *idev);
 
@@ -130,6 +147,18 @@ struct iommufd_vdevice {
 	 */
 	u64 virt_id;
 
+	/* Serializes provider attachment and conversion. */
+	struct mutex mmio_lock;
+	/* Attached provider and callbacks, protected by mmio_lock until detach. */
+	void *mmio_provider_data;
+	/*
+	 * Revoke VFIO userspace BAR mappings and shared guest stage-2 mappings
+	 * before delegation. Private guest mappings remain intact; guest_memfd
+	 * removes them through its architecture unmap operation.
+	 */
+	void (*invalidate_mmio)(void *data);
+	bool (*has_private_mmio)(void *data);
+
 	/* Guest TSM requests accepted by this vdevice; set by vdevice_init(). */
 	u64 tsm_req_op_mask;
 	u32 tsm_tvm_arch;
@@ -187,6 +216,7 @@ struct iommufd_hw_queue {
  *                include/uapi/linux/iommufd.h)
  *                If driver has a deinit function to revert what vdevice_init op
  *                does, it should set it to the @vdev->destroy function pointer
+ * @vdevice_get_mmio_owner: Validate the VM and return its MMIO owner.
  * @vdevice_tsm_req: Forward a guest TSM request to a driver-owned vDEVICE
  * @get_hw_queue_size: Get the size of a driver-defined HW queue structure for a
  *                     given @viommu corresponding to @queue_type. Driver should
@@ -218,6 +248,9 @@ struct iommufd_viommu_ops {
 		const struct iommu_user_data *user_data);
 	int (*cache_invalidate)(struct iommufd_viommu *viommu,
 				struct iommu_user_data_array *array);
+	/* Owner lookup runs with vdevice->mmio_lock held. */
+	int (*vdevice_get_mmio_owner)(struct iommufd_vdevice *vdev,
+		struct kvm *kvm, unsigned long *owner);
 	const size_t vdevice_size;
 	int (*vdevice_init)(struct iommufd_vdevice *vdev);
 	ssize_t (*vdevice_tsm_req)(struct iommufd_vdevice *vdev,
Signature · 1 line
2.43.0
#4 lore raw

RFC PATCH 4/6 vfio/pci: Provide guest_memfd backing for PCI BARs

In reply to Aneesh Kumar K.V (Arm)

Allow an ordinary VFIO PCI device fd to supply BAR memory to guest_memfd. Validate eligible BAR ranges and provide their PFNs for shared guest mappings. Keep the VFIO file and its IOMMUFD vDEVICE alive while the provider is attached.

Revoke host and shared guest mappings before private conversion, and check guest_memfd attributes before allowing host BAR access. Exclude independent dma-buf exports while attached because their mappings bypass these access checks.

Hold the vDEVICE MMIO mutex across conversion and attribute updates. Use the VFIO memory lock to serialize BAR access and revocation. Host access checks try the inode invalidate lock without waiting, avoiding deadlock with conversion, which acquires that lock first.

Cc Alex Williamson <[email protected]>
Cc Sean Christopherson <[email protected]>
Cc Paolo Bonzini <[email protected]>
Cc David Hildenbrand <[email protected]>
Assisted-by Codex
---
 drivers/vfio/device_cdev.c              |   3 +-
 drivers/vfio/group.c                    |   4 +-
 drivers/vfio/pci/Kconfig                |  11 +
 drivers/vfio/pci/Makefile               |   2 +
 drivers/vfio/pci/vfio_pci.c             |   3 +
 drivers/vfio/pci/vfio_pci_core.c        |  13 +
 drivers/vfio/pci/vfio_pci_dmabuf.c      |  10 +
 drivers/vfio/pci/vfio_pci_gmem.c        | 322 ++++++++++++++++++++++++
 drivers/vfio/pci/vfio_pci_gmem.h        |  30 +++
 drivers/vfio/pci/vfio_pci_gmem_access.c | 134 ++++++++++
 drivers/vfio/pci/vfio_pci_rdwr.c        |  13 +-
 drivers/vfio/vfio.h                     |   8 +
 drivers/vfio/vfio_main.c                |  34 ++-
 include/linux/guest_memfd.h             |   3 +
 include/linux/vfio.h                    |   3 +
 include/linux/vfio_pci_core.h           |  23 ++
 virt/kvm/guest_memfd.c                  | 105 ++++++++
 17 files changed, 702 insertions(+), 19 deletions(-)
 create mode 100644 drivers/vfio/pci/vfio_pci_gmem.c
 create mode 100644 drivers/vfio/pci/vfio_pci_gmem.h
 create mode 100644 drivers/vfio/pci/vfio_pci_gmem_access.c
drivers/vfio/device_cdev.c +1 -2
index 1d9515c967b0..3f251120b1cf 100644
@@ -46,7 +46,7 @@ int vfio_device_fops_cdev_open(struct inode *inode, struct file *filep)
 		goto err_put_registration;
 	}
 
-	filep->private_data = df;
+	filep->private_data = &df->gmem_ops;
 
 	/*
 	 * Use the pseudo fs inode on the device to link all mmaps
@@ -54,7 +54,6 @@ int vfio_device_fops_cdev_open(struct inode *inode, struct file *filep)
 	 * associated to this device using unmap_mapping_range().
 	 */
 	filep->f_mapping = device->inode->i_mapping;
-
 	return 0;
 
 err_put_registration:
drivers/vfio/group.c +2 -2
index 5bf8cbdff377..5f45d30ac62a 100644
@@ -271,7 +271,8 @@ static struct file *vfio_device_open_file(struct vfio_device *device)
 		goto err_free;
 
 	filep = anon_inode_getfile_fmode("[vfio-device]", &vfio_device_fops,
-				   df, O_RDWR, FMODE_PREAD | FMODE_PWRITE);
+					 &df->gmem_ops,
+					 O_RDWR, FMODE_PREAD | FMODE_PWRITE);
 	if (IS_ERR(filep)) {
 		ret = PTR_ERR(filep);
 		goto err_close_device;
@@ -282,7 +283,6 @@ static struct file *vfio_device_open_file(struct vfio_device *device)
 	 * associated to this device using unmap_mapping_range().
 	 */
 	filep->f_mapping = device->inode->i_mapping;
-
 	if (device->group->type == VFIO_NO_IOMMU)
 		dev_warn(device->dev, "vfio-noiommu device opened by user "
 			 "(%s:%d)\n", current->comm, task_pid_nr(current));
drivers/vfio/pci/Kconfig +11 -0
index 296bf01e185e..477c5afad7a2 100644
@@ -55,6 +55,17 @@ config VFIO_PCI_ZDEV_KVM
 
 	  To enable s390x KVM vfio-pci extensions, say Y.
 
+config VFIO_PCI_GMEM
+	bool "VFIO PCI device guest_memfd resource provider"
+	depends on VFIO_PCI && IOMMUFD && ARM64 && KVM
+	depends on KVM_GUEST_MEMFD
+	help
+	  Allow the VFIO PCI device fd to provide BAR PFNs to guest_memfd,
+	  including confidential-device range conversion through its
+	  existing IOMMUFD vDEVICE. This requires a capable TSM backend.
+	  Shared access is revoked before confidential range mapping and is
+	  restored only after private mappings and device state permit it.
+
 config VFIO_PCI_DMABUF
 	def_bool y if VFIO_PCI_CORE && PCI_P2PDMA && DMA_SHARED_BUFFER
 
drivers/vfio/pci/Makefile +2 -0
index 6138f1bf241d..1abb7448c8b1 100644
@@ -3,6 +3,8 @@
 vfio-pci-core-y := vfio_pci_core.o vfio_pci_intrs.o vfio_pci_rdwr.o vfio_pci_config.o
 vfio-pci-core-$(CONFIG_VFIO_PCI_ZDEV_KVM) += vfio_pci_zdev.o
 vfio-pci-core-$(CONFIG_VFIO_PCI_DMABUF) += vfio_pci_dmabuf.o
+vfio-pci-core-$(CONFIG_VFIO_PCI_GMEM) += vfio_pci_gmem_access.o
+vfio-pci-core-$(CONFIG_VFIO_PCI_GMEM) += vfio_pci_gmem.o
 obj-$(CONFIG_VFIO_PCI_CORE) += vfio-pci-core.o
 
 vfio-pci-y := vfio_pci.o
drivers/vfio/pci/vfio_pci.c +3 -0
index 830369ff878d..675357255a01 100644
@@ -147,6 +147,9 @@ static int vfio_pci_init_dev(struct vfio_device *core_vdev)
 }
 
 static const struct vfio_device_ops vfio_pci_ops = {
+#if IS_ENABLED(CONFIG_VFIO_PCI_GMEM)
+	.gmem_ops = &vfio_pci_gmem_ops,
+#endif
 	.name		= "vfio-pci",
 	.init		= vfio_pci_init_dev,
 	.release	= vfio_pci_core_release_dev,
drivers/vfio/pci/vfio_pci_core.c +13 -0
index 6757054e9d87..1f4bdea4546d 100644
@@ -1714,6 +1714,7 @@ static void vfio_pci_zap_bars(struct vfio_pci_core_device *vdev)
 	loff_t len = end - start;
 
 	unmap_mapping_range(core_vdev->inode->i_mapping, start, len, true);
+	vfio_pci_gmem_invalidate(vdev);
 }
 
 void vfio_pci_zap_and_down_write_memory_lock(struct vfio_pci_core_device *vdev)
@@ -1763,6 +1764,18 @@ vm_fault_t vfio_pci_vmf_insert_pfn(struct vfio_pci_core_device *vdev,
 	if (vdev->pm_runtime_engaged || !__vfio_pci_memory_enabled(vdev))
 		return VM_FAULT_SIGBUS;
 
+	/* Use base-page mappings so each BAR page gets its own access check. */
+	if (order && vdev->gmem)
+		return VM_FAULT_FALLBACK;
+	/*
+	 * A VFIO mmap can outlive conversion to private memory. Recheck
+	 * the guest_memfd and VM attributes for this page so a fault
+	 * cannot restore a host mapping of a private BAR range.
+	 */
+	if (!vfio_pci_gmem_access_allowed(vdev,
+				(u64)vmf->pgoff << PAGE_SHIFT, PAGE_SIZE))
+		return VM_FAULT_SIGBUS;
+
 	if (!order)
 		return vmf_insert_pfn(vmf->vma, vmf->address, pfn);
 
drivers/vfio/pci/vfio_pci_dmabuf.c +10 -0
index c16f460c01d6..b3ae2d97629f 100644
@@ -306,6 +306,16 @@ int vfio_pci_core_feature_dma_buf(struct vfio_pci_core_device *vdev, u32 flags,
 	/* dma_buf_put() now frees priv */
 	INIT_LIST_HEAD(&priv->dmabufs_elm);
 	down_write(&vdev->memory_lock);
+	/*
+	 * dma-buf consumers bypass guest_memfd range access checks, and their
+	 * mappings are not revoked by conversion to private memory. Exclude
+	 * exports while attached; memory_lock serializes this with attachment.
+	 */
+	if (vdev->gmem) {
+		up_write(&vdev->memory_lock);
+		dma_buf_put(priv->dmabuf);
+		return -EBUSY;
+	}
 	dma_resv_lock(priv->dmabuf->resv, NULL);
 	priv->revoked = !__vfio_pci_memory_enabled(vdev);
 	list_add_tail(&priv->dmabufs_elm, &vdev->dmabufs);
drivers/vfio/pci/vfio_pci_gmem.c new file +322 -0

322 lines not on this page · raw message

drivers/vfio/pci/vfio_pci_gmem.h new file +30 -0
new file mode 100644
index 000000000000..e5ad19ba6748
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef VFIO_PCI_GMEM_H
+#define VFIO_PCI_GMEM_H
+
+#include <linux/container_of.h>
+#include <linux/guest_memfd.h>
+#include <linux/pci.h>
+
+struct iommufd_vdevice;
+struct vfio_pci_core_device;
+
+struct vfio_pci_gmem {
+	struct guest_memfd_device_context context;
+	struct vfio_pci_core_device *vdev;
+	struct iommufd_vdevice *ivdev;
+	struct file *resource;
+	unsigned long owner;
+	resource_size_t start[PCI_STD_NUM_BARS];
+	resource_size_t len[PCI_STD_NUM_BARS];
+};
+
+static inline struct vfio_pci_gmem *
+vfio_pci_gmem_from_context(struct guest_memfd_device_context *context)
+{
+	return container_of_const(context, struct vfio_pci_gmem, context);
+}
+
+void vfio_gmem_invalidate_mmio(void *data);
+
+#endif /* VFIO_PCI_GMEM_H */
drivers/vfio/pci/vfio_pci_gmem_access.c new file +134 -0

134 lines not on this page · raw message

drivers/vfio/pci/vfio_pci_rdwr.c +10 -3
index 7f14dd46de17..54c1b3d2f725 100644
@@ -44,7 +44,9 @@ int vfio_pci_core_iowrite##size(struct vfio_pci_core_device *vdev,	\
 {									\
 	if (test_mem) {							\
 		down_read(&vdev->memory_lock);				\
-		if (!__vfio_pci_memory_enabled(vdev)) {			\
+		if (!__vfio_pci_memory_enabled(vdev) ||			\
+		    !vfio_pci_gmem_io_access_allowed(vdev, io,		\
+						     sizeof(u##size))) {	\
 			up_read(&vdev->memory_lock);			\
 			return -EIO;					\
 		}							\
@@ -70,7 +72,9 @@ int vfio_pci_core_ioread##size(struct vfio_pci_core_device *vdev,	\
 {									\
 	if (test_mem) {							\
 		down_read(&vdev->memory_lock);				\
-		if (!__vfio_pci_memory_enabled(vdev)) {			\
+		if (!__vfio_pci_memory_enabled(vdev) ||			\
+		    !vfio_pci_gmem_io_access_allowed(vdev, io,		\
+						     sizeof(u##size))) {	\
 			up_read(&vdev->memory_lock);			\
 			return -EIO;					\
 		}							\
@@ -380,7 +384,10 @@ static int vfio_pci_ioeventfd_handler(void *opaque, void *unused)
 	if (ioeventfd->test_mem) {
 		if (!down_read_trylock(&vdev->memory_lock))
 			return 1; /* Lock contended, use thread */
-		if (!__vfio_pci_memory_enabled(vdev)) {
+		if (!__vfio_pci_memory_enabled(vdev) ||
+		    !vfio_pci_gmem_access_allowed(vdev,
+				VFIO_PCI_INDEX_TO_OFFSET(ioeventfd->bar) +
+				ioeventfd->pos, ioeventfd->count)) {
 			up_read(&vdev->memory_lock);
 			return 0;
 		}
drivers/vfio/vfio.h +8 -0
index 9b619951a5d0..af0940a063a9 100644
@@ -7,6 +7,7 @@
 #define __VFIO_VFIO_H__
 
 #include <linux/file.h>
+#include <linux/guest_memfd.h>
 #include <linux/device.h>
 #include <linux/cdev.h>
 #include <linux/module.h>
@@ -17,6 +18,8 @@ struct iommu_group;
 struct vfio_container;
 
 struct vfio_device_file {
+	/* Exposed through file->private_data for VFIO device files. */
+	struct guest_memfd_device_operations gmem_ops;
 	struct vfio_device *device;
 	struct vfio_group *group;
 
@@ -27,6 +30,11 @@ struct vfio_device_file {
 	struct iommufd_ctx *iommufd; /* protected by struct vfio_device_set::lock */
 };
 
+static inline struct vfio_device_file *vfio_device_file_from_file(struct file *file)
+{
+	return container_of(file->private_data, struct vfio_device_file, gmem_ops);
+}
+
 void vfio_device_put_registration(struct vfio_device *device);
 bool vfio_device_try_get_registration(struct vfio_device *device);
 int vfio_df_open(struct vfio_device_file *df);
drivers/vfio/vfio_main.c +22 -12
index ed96acfa8635..c3df4f9b1ba4 100644
@@ -509,6 +509,8 @@ vfio_allocate_device_file(struct vfio_device *device)
 	if (!df)
 		return ERR_PTR(-ENOMEM);
 
+	if (device->ops->gmem_ops)
+		df->gmem_ops = *device->ops->gmem_ops;
 	df->device = device;
 	spin_lock_init(&df->kvm_ref_lock);
 
@@ -642,7 +644,7 @@ static inline void vfio_device_pm_runtime_put(struct vfio_device *device)
  */
 static int vfio_device_fops_release(struct inode *inode, struct file *filep)
 {
-	struct vfio_device_file *df = filep->private_data;
+	struct vfio_device_file *df = vfio_device_file_from_file(filep);
 	struct vfio_device *device = df->device;
 
 	if (df->group)
@@ -1340,7 +1342,7 @@ static long vfio_get_region_info(struct vfio_device *device,
 static long vfio_device_fops_unl_ioctl(struct file *filep,
 				       unsigned int cmd, unsigned long arg)
 {
-	struct vfio_device_file *df = filep->private_data;
+	struct vfio_device_file *df = vfio_device_file_from_file(filep);
 	struct vfio_device *device = df->device;
 	void __user *uptr = (void __user *)arg;
 	int ret;
@@ -1393,7 +1395,7 @@ static long vfio_device_fops_unl_ioctl(struct file *filep,
 static ssize_t vfio_device_fops_read(struct file *filep, char __user *buf,
 				     size_t count, loff_t *ppos)
 {
-	struct vfio_device_file *df = filep->private_data;
+	struct vfio_device_file *df = vfio_device_file_from_file(filep);
 	struct vfio_device *device = df->device;
 
 	/* Paired with smp_store_release() following vfio_df_open() */
@@ -1410,7 +1412,7 @@ static ssize_t vfio_device_fops_write(struct file *filep,
 				      const char __user *buf,
 				      size_t count, loff_t *ppos)
 {
-	struct vfio_device_file *df = filep->private_data;
+	struct vfio_device_file *df = vfio_device_file_from_file(filep);
 	struct vfio_device *device = df->device;
 
 	/* Paired with smp_store_release() following vfio_df_open() */
@@ -1425,7 +1427,7 @@ static ssize_t vfio_device_fops_write(struct file *filep,
 
 static int vfio_device_fops_mmap(struct file *filep, struct vm_area_struct *vma)
 {
-	struct vfio_device_file *df = filep->private_data;
+	struct vfio_device_file *df = vfio_device_file_from_file(filep);
 	struct vfio_device *device = df->device;
 
 	/* Paired with smp_store_release() following vfio_df_open() */
@@ -1442,7 +1444,7 @@ static int vfio_device_fops_mmap(struct file *filep, struct vm_area_struct *vma)
 static void vfio_device_show_fdinfo(struct seq_file *m, struct file *filep)
 {
 	char *path;
-	struct vfio_device_file *df = filep->private_data;
+	struct vfio_device_file *df = vfio_device_file_from_file(filep);
 	struct vfio_device *device = df->device;
 
 	path = kobject_get_path(&device->dev->kobj, GFP_KERNEL);
@@ -1470,11 +1472,9 @@ const struct file_operations vfio_device_fops = {
 
 static struct vfio_device *vfio_device_from_file(struct file *file)
 {
-	struct vfio_device_file *df = file->private_data;
-
 	if (file->f_op != &vfio_device_fops)
 		return NULL;
-	return df->device;
+	return vfio_device_file_from_file(file)->device;
 }
 
 /**
@@ -1517,7 +1517,7 @@ EXPORT_SYMBOL_GPL(vfio_file_enforced_coherent);
 
 static void vfio_device_file_set_kvm(struct file *file, struct file *kvm)
 {
-	struct vfio_device_file *df = file->private_data;
+	struct vfio_device_file *df = vfio_device_file_from_file(file);
 	struct file *old;
 
 	if (kvm)
@@ -1814,9 +1814,15 @@ static int __init vfio_init(void)
 
 	ida_init(&vfio.device_ida);
 
+	if (IS_ENABLED(CONFIG_KVM_GUEST_MEMFD)) {
+		ret = guest_memfd_register_device_fops(&vfio_device_fops);
+		if (ret)
+			return ret;
+	}
+
 	ret = vfio_group_init();
 	if (ret)
-		return ret;
+		goto err_group;
 
 	ret = vfio_virqfd_init();
 	if (ret)
@@ -1834,13 +1840,15 @@ static int __init vfio_init(void)
 	vfio_debugfs_create_root();
 	pr_info(DRIVER_DESC " version: " DRIVER_VERSION "\n");
 	return 0;
-
 err_alloc_dev_chrdev:
 	class_unregister(&vfio_device_class);
 err_dev_class:
 	vfio_virqfd_exit();
 err_virqfd:
 	vfio_group_cleanup();
+err_group:
+	if (IS_ENABLED(CONFIG_KVM_GUEST_MEMFD))
+		guest_memfd_unregister_device_fops(&vfio_device_fops);
 	return ret;
 }
 
@@ -1853,6 +1861,8 @@ static void __exit vfio_cleanup(void)
 	vfio_virqfd_exit();
 	vfio_group_cleanup();
 	xa_destroy(&vfio_device_set_xa);
+	if (IS_ENABLED(CONFIG_KVM_GUEST_MEMFD))
+		guest_memfd_unregister_device_fops(&vfio_device_fops);
 }
 
 module_init(vfio_init);
include/linux/guest_memfd.h +3 -0
index b566c581f04d..24f4b3c79afa 100644
@@ -52,6 +52,9 @@ struct guest_memfd_device {
 	struct kvm *kvm;
 	u64 size;
 	void *core;
+	void (*invalidate)(struct guest_memfd_device *gdev);
+	bool (*has_private)(struct guest_memfd_device *gdev);
+	bool (*host_accessible)(struct guest_memfd_device *gdev, u64 offset, u64 size);
 };
 
 /**
include/linux/vfio.h +3 -0
index 0cc91c6f96d2..8f71117a2851 100644
@@ -113,7 +113,10 @@ struct vfio_device {
  *             this device is attached to.
  * @device_feature: Optional, fill in the VFIO_DEVICE_FEATURE ioctl
  */
+struct guest_memfd_device_operations;
+
 struct vfio_device_ops {
+	const struct guest_memfd_device_operations *gmem_ops;
 	char	*name;
 	int	(*init)(struct vfio_device *vdev);
 	void	(*release)(struct vfio_device *vdev);
include/linux/vfio_pci_core.h +23 -0
index 9a1674c152aa..73294230d54e 100644
@@ -149,8 +149,31 @@ struct vfio_pci_core_device {
 	struct notifier_block	nb;
 	struct rw_semaphore	memory_lock;
 	struct list_head	dmabufs;
+	/* Attached provider; publication/removal require memory_lock for write. */
+	struct vfio_pci_gmem *gmem;
 };
 
+#if IS_ENABLED(CONFIG_VFIO_PCI_GMEM)
+extern const struct guest_memfd_device_operations vfio_pci_gmem_ops;
+void vfio_pci_gmem_invalidate(struct vfio_pci_core_device *vdev);
+bool vfio_pci_gmem_access_allowed(struct vfio_pci_core_device *vdev,
+				u64 offset, u64 size);
+bool vfio_pci_gmem_io_access_allowed(struct vfio_pci_core_device *vdev,
+				   void __iomem *io, size_t size);
+#else
+static inline void vfio_pci_gmem_invalidate(struct vfio_pci_core_device *vdev) {}
+static inline bool vfio_pci_gmem_access_allowed(struct vfio_pci_core_device *vdev,
+					     u64 offset, u64 size)
+{
+	return true;
+}
+static inline bool vfio_pci_gmem_io_access_allowed(struct vfio_pci_core_device *vdev,
+						void __iomem *io, size_t size)
+{
+	return true;
+}
+#endif
+
 enum vfio_pci_io_width {
 	VFIO_PCI_IO_WIDTH_1 = 1,
 	VFIO_PCI_IO_WIDTH_2 = 2,
virt/kvm/guest_memfd.c +105 -0

117 lines not on this page · raw message

Signature · 1 line
2.43.0
#5 lore raw

RFC PATCH 5/6 KVM/VFIO: Remove device mappings during guest_memfd teardown

In reply to Aneesh Kumar K.V (Arm)

On final guest_memfd close, stop new provider access and callbacks before removing private device mappings and releasing the provider. Keep slot bindings available until the mappings have been removed.

Serialize teardown with conversion using the inode invalidate lock. VFIO takes the vDEVICE MMIO mutex and its memory lock when disabling access and callbacks, preventing concurrent faults or device operations from using provider state being torn down.

Cc Alex Williamson <[email protected]>
Cc Paolo Bonzini <[email protected]>
Cc Sean Christopherson <[email protected]>
Cc David Hildenbrand <[email protected]>
Assisted-by Codex
---
 drivers/vfio/pci/vfio_pci_gmem.c        | 27 +++++++++++++++++++++++++
 drivers/vfio/pci/vfio_pci_gmem.h        |  6 ++++++
 drivers/vfio/pci/vfio_pci_gmem_access.c | 12 +++++++----
 include/linux/guest_memfd.h             |  1 +
 virt/kvm/guest_memfd.c                  | 21 +++++++++++++++++++
 5 files changed, 63 insertions(+), 4 deletions(-)
drivers/vfio/pci/vfio_pci_gmem.c +27 -0
index d232b5c3e539..3f8630a0eeca 100644
@@ -183,6 +183,8 @@ static int vfio_gmem_bind(void *data, u64 offset, u64 size,
 	int ret;
 
 	guard(iommufd_vdevice_mmio)(ctx->ivdev);
+	if (ctx->callbacks_detached)
+		return -ENODEV;
 	ret = vfio_gmem_resolve_bar_range(ctx, offset, size, &bar, &off, &pa);
 	if (ret)
 		return ret;
@@ -226,6 +228,8 @@ static int vfio_gmem_get_pfn(void *data, u64 offset, unsigned long *pfn)
 	int ret;
 
 	guard(rwsem_read)(&vdev->memory_lock);
+	if (ctx->callbacks_detached)
+		return -ENODEV;
 	if (vdev->pm_runtime_engaged || !__vfio_pci_memory_enabled(vdev))
 		return -EAGAIN;
 
@@ -255,6 +259,10 @@ static int vfio_gmem_prepare_conversion(struct guest_memfd_device_context *conte
 	struct vfio_pci_gmem *ctx = vfio_pci_gmem_from_context(context);
 
 	iommufd_vdevice_mmio_lock(ctx->ivdev);
+	if (req && ctx->callbacks_detached) {
+		iommufd_vdevice_mmio_unlock(ctx->ivdev);
+		return -ENODEV;
+	}
 	if (req && req->vdev_id != ctx->ivdev->virt_id) {
 		iommufd_vdevice_mmio_unlock(ctx->ivdev);
 		return -EPERM;
@@ -284,6 +292,24 @@ static void vfio_gmem_finish_conversion(struct guest_memfd_device_context *conte
 	iommufd_vdevice_mmio_unlock(ctx->ivdev);
 }
 
+/**
+ * vfio_gmem_detach() - stop invalidation callbacks before core teardown
+ * @data: attached provider context
+ *
+ * Mark the provider detached under the VFIO memory lock and revoke BAR
+ * translations.
+ */
+static void vfio_gmem_detach(void *data)
+{
+	struct vfio_pci_gmem *ctx = vfio_pci_gmem_from_context(data);
+
+	guard(iommufd_vdevice_mmio)(ctx->ivdev);
+	scoped_guard(rwsem_write, &ctx->vdev->memory_lock) {
+		ctx->callbacks_detached = true;
+	}
+	vfio_gmem_invalidate_mmio(&ctx->context);
+}
+
 /**
  * vfio_gmem_release() - release a provider after successful core cleanup
  * @data: provider context to release
@@ -315,6 +341,7 @@ const struct guest_memfd_device_operations vfio_pci_gmem_ops = {
 	.get_pfn = vfio_gmem_get_pfn,
 	.prepare_conversion = vfio_gmem_prepare_conversion,
 	.finish_conversion = vfio_gmem_finish_conversion,
+	.detach = vfio_gmem_detach,
 	.release = vfio_gmem_release,
 };
 EXPORT_SYMBOL_GPL(vfio_pci_gmem_ops);
drivers/vfio/pci/vfio_pci_gmem.h +6 -0
index e5ad19ba6748..a47a8d386051 100644
@@ -17,6 +17,12 @@ struct vfio_pci_gmem {
 	unsigned long owner;
 	resource_size_t start[PCI_STD_NUM_BARS];
 	resource_size_t len[PCI_STD_NUM_BARS];
+	/*
+	 * Disables callbacks and new bind/private requests. Set once with
+	 * both the vDEVICE MMIO and VFIO memory locks held; readers hold
+	 * either lock. Shared cleanup remains allowed after detachment.
+	 */
+	bool callbacks_detached;
 };
 
 static inline struct vfio_pci_gmem *
drivers/vfio/pci/vfio_pci_gmem_access.c +8 -4
index a3975b536e22..254a311b5072 100644
@@ -14,7 +14,7 @@
  * Called by vfio_pci_zap_bars() after it removes host BAR mappings. Notify
  * guest_memfd synchronously so KVM removes the corresponding shared guest
  * mappings. This helper does not remove host mappings or change attributes.
- * Skip notification if no provider is attached.
+ * Skip notification if no provider is attached or its callbacks are detached.
  *
  * The guest_memfd callback takes SRCU and the KVM MMU lock without taking
  * the inode invalidate lock, which may already be held during conversion.
@@ -25,7 +25,7 @@ void vfio_pci_gmem_invalidate(struct vfio_pci_core_device *vdev)
 	struct vfio_pci_gmem *ctx = vdev->gmem;
 
 	lockdep_assert_held_write(&vdev->memory_lock);
-	if (ctx)
+	if (ctx && !ctx->callbacks_detached)
 		ctx->context.device->invalidate(ctx->context.device);
 }
 
@@ -33,11 +33,12 @@ void vfio_pci_gmem_invalidate(struct vfio_pci_core_device *vdev)
  * vfio_gmem_invalidate_mmio() - revoke host and shared guest BAR translations
  * @data: attached provider context
  *
- * Initiate BAR revocation for conversion or access refresh. Call
+ * Initiate BAR revocation for conversion, access refresh or teardown. Call
  * vfio_pci_zap_and_down_write_memory_lock() to remove host BAR mappings;
  * its BAR zap path also calls vfio_pci_gmem_invalidate() to remove the
  * corresponding shared guest mappings. Release the VFIO memory lock before
- * returning.
+ * returning. Host mappings are removed even if guest_memfd callbacks are
+ * detached.
  *
  * During private conversion, the caller holds the inode invalidate lock to
  * prevent new guest_memfd faults. Host faults and I/O try that lock when
@@ -68,6 +69,7 @@ void vfio_gmem_invalidate_mmio(void *data)
  * Consult completed guest_memfd attributes for the requested interval.
  * Private mappings in another interval do not block this access. Try the
  * inode lock instead of waiting in the reverse order from conversion.
+ * Detachment excludes access during teardown.
  *
  * Return: true when the requested interval is accessible.
  */
@@ -84,6 +86,8 @@ bool vfio_pci_gmem_access_allowed(struct vfio_pci_core_device *vdev,
 	if (!ctx->ivdev)
 		return false;
 
+	if (ctx->callbacks_detached)
+		return false;
 	return ctx->context.device->host_accessible(ctx->context.device,
 						    offset, size);
 }
include/linux/guest_memfd.h +1 -0
index 24f4b3c79afa..8373ef8150c5 100644
@@ -41,6 +41,7 @@ struct guest_memfd_device_operations {
 		const struct guest_memfd_device_request *req);
 	void (*finish_conversion)(struct guest_memfd_device_context *context,
 		const struct guest_memfd_device_request *req);
+	void (*detach)(void *data);
 	void (*release)(void *data);
 };
 
virt/kvm/guest_memfd.c +21 -0
index fc37066bfaa5..f493b452fae8 100644
@@ -381,6 +381,7 @@ static void kvm_gmem_invalidate_end(struct inode *inode, pgoff_t start,
 static int kvm_gmem_device_convert(struct inode *inode, pgoff_t start,
 		pgoff_t nr_pages, const struct guest_memfd_device_request *req,
 		const struct kvm_memory_slot *slot);
+static void kvm_gmem_device_close(struct inode *inode);
 
 static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 {
@@ -503,6 +504,9 @@ static int kvm_gmem_release(struct inode *inode, struct file *file)
 
 	filemap_invalidate_lock(inode->i_mapping);
 
+	if (GMEM_I(inode)->device_ops)
+		kvm_gmem_device_close(inode);
+
 	xa_for_each(&f->bindings, index, slot) {
 		WRITE_ONCE(slot->gmem.file, NULL);
 	}
@@ -1362,6 +1366,23 @@ int kvm_gmem_device_map(struct kvm *kvm, u64 gpa, u64 size, u64 pa, u64 vdev_id)
 }
 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_gmem_device_map);
 
+static void kvm_gmem_device_close(struct inode *inode)
+{
+	struct gmem_inode *gi = GMEM_I(inode);
+	int ret;
+
+	gi->device_ops->detach(gi->provider);
+	ret = gi->device_ops->prepare_conversion(gi->provider, NULL);
+	if (!ret) {
+		ret = kvm_gmem_device_make_shared(inode, 0,
+						i_size_read(inode) >> PAGE_SHIFT);
+		if (!ret)
+			WRITE_ONCE(gi->device_has_private, false);
+		gi->device_ops->finish_conversion(gi->provider, NULL);
+	}
+	WRITE_ONCE(gi->device.core, NULL);
+}
+
 static int kvm_gmem_attach_resource(struct kvm *kvm,
 		struct inode *inode, int resource_fd)
 {
Signature · 1 line
2.43.0
#6 lore raw

RFC PATCH 6/6 KVM: Invalidate guest_memfd mappings before removing memslot bindings

In reply to Aneesh Kumar K.V (Arm)

Unmap guest_memfd ranges before deleting their memslot bindings. Remove private device mappings before committing deletion, and invalidate remaining mappings while holding the inode invalidate lock.

Cc Paolo Bonzini <[email protected]>
Cc Sean Christopherson <[email protected]>
Cc David Hildenbrand <[email protected]>
Assisted-by Codex
---
 virt/kvm/guest_memfd.c | 70 ++++++++++++++++++++++++++++++++++++++++--
 virt/kvm/guest_memfd.h |  6 ++++
 virt/kvm/kvm_main.c    |  4 +++
 3 files changed, 77 insertions(+), 3 deletions(-)
virt/kvm/guest_memfd.c +67 -3
index f493b452fae8..f58270d0510d 100644
@@ -1330,6 +1330,58 @@ static int kvm_gmem_device_convert(struct inode *inode, pgoff_t start,
 	return ret;
 }
 
+/**
+ * kvm_gmem_prepare_memslot_delete() - remove guest_memfd mappings before deletion
+ * @kvm: VM whose memslot is being removed
+ * @slot: original guest_memfd memslot being removed
+ *
+ * The caller has replaced the active slot with an entry marked
+ * KVM_MEMSLOT_INVALID, preventing new guest faults from creating mappings.
+ * Remove private device mappings, then invalidate the remaining guest_memfd
+ * mappings, including shared mappings.
+ *
+ * Perform this cleanup while the guest_memfd binding still provides the
+ * file-offset-to-GPA translation needed to locate the guest mappings.
+ * The device provider remains attached until guest_memfd close.
+ *
+ * Caller holds slots_lock.
+ * Return: 0 on success or a negative error code.
+ */
+int kvm_gmem_prepare_memslot_delete(const struct kvm_memory_slot *slot)
+{
+	struct file *file = READ_ONCE(slot->gmem.file);
+	pgoff_t start = slot->gmem.pgoff;
+	pgoff_t end = start + slot->npages;
+	struct inode *inode;
+	int ret;
+
+	/* slots_lock keeps the bindings alive until file release can finish. */
+	file = get_file_active(&file);
+	if (!file) {
+		/* Let .release drain the bindings before deletion can discard them. */
+		if (READ_ONCE(slot->gmem.file))
+			return -EBUSY;
+		return 0;
+	}
+	inode = file_inode(file);
+	if (GMEM_I(inode)->device_ops) {
+		ret = kvm_gmem_device_convert(inode, start, slot->npages, NULL, NULL);
+		if (ret)
+			goto out;
+	}
+
+	filemap_invalidate_lock(inode->i_mapping);
+	__kvm_gmem_invalidate_start(file->private_data, start, end,
+				    kvm_gmem_get_all_gfns_filter(inode));
+	__kvm_gmem_invalidate_end(file->private_data, start, end);
+	filemap_invalidate_unlock(inode->i_mapping);
+	ret = 0;
+out:
+	fput(file);
+	return ret;
+}
+
+
 int kvm_gmem_device_map(struct kvm *kvm, u64 gpa, u64 size, u64 pa, u64 vdev_id)
 {
 	struct guest_memfd_device_request req = { gpa, pa, vdev_id };
@@ -1620,11 +1672,19 @@ int kvm_gmem_bind(struct kvm *kvm, struct kvm_memory_slot *slot,
 	return r;
 }
 
-static void __kvm_gmem_unbind(struct kvm_memory_slot *slot, struct gmem_file *f)
+static void __kvm_gmem_unbind(struct kvm_memory_slot *slot, struct file *file)
 {
+	struct gmem_file *f = file->private_data;
 	unsigned long start = slot->gmem.pgoff;
 	unsigned long end = start + slot->npages;
 
+	/*
+	 * Unmap this slot's guest mappings before removing it from f->bindings.
+	 * The invalidation helper walks f->bindings to find the slots to unmap.
+	 */
+	__kvm_gmem_invalidate_start(f, start, end,
+				    kvm_gmem_get_all_gfns_filter(file_inode(file)));
+	__kvm_gmem_invalidate_end(f, start, end);
 	xa_store_range(&f->bindings, start, end - 1, NULL, GFP_KERNEL);
 
 	/*
@@ -1656,12 +1716,16 @@ void kvm_gmem_unbind(struct kvm_memory_slot *slot)
 	 * until the caller drops slots_lock.
 	 */
 	if (!file) {
-		__kvm_gmem_unbind(slot, slot->gmem.file->private_data);
+		struct file *closing_file = slot->gmem.file;
+
+		filemap_invalidate_lock(closing_file->f_mapping);
+		__kvm_gmem_unbind(slot, closing_file);
+		filemap_invalidate_unlock(closing_file->f_mapping);
 		return;
 	}
 
 	filemap_invalidate_lock(file->f_mapping);
-	__kvm_gmem_unbind(slot, file->private_data);
+	__kvm_gmem_unbind(slot, file);
 	filemap_invalidate_unlock(file->f_mapping);
 }
 
virt/kvm/guest_memfd.h +6 -0
index 0f9c6f840838..6fad6adfdadc 100644
@@ -11,6 +11,7 @@ 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);
+int kvm_gmem_prepare_memslot_delete(const struct kvm_memory_slot *slot);
 #else
 static inline int kvm_gmem_init(struct module *module)
 {
@@ -29,6 +30,11 @@ static inline void kvm_gmem_unbind(struct kvm_memory_slot *slot)
 {
 	WARN_ON_ONCE(1);
 }
+
+static inline int kvm_gmem_prepare_memslot_delete(const struct kvm_memory_slot *slot)
+{
+	return 0;
+}
 #endif /* CONFIG_KVM_GUEST_MEMFD */
 
 #endif /* __KVM_GUEST_MEMFD_H__ */
virt/kvm/kvm_main.c +4 -0
index f3f46a8563b3..58da57b8a268 100644
@@ -1696,6 +1696,10 @@ static int kvm_prepare_memory_region(struct kvm *kvm,
 	}
 
 	r = kvm_arch_prepare_memory_region(kvm, old, new, change);
+	if (!r && change == KVM_MR_DELETE) {
+		if (old->flags & KVM_MEM_GUEST_MEMFD)
+			r = kvm_gmem_prepare_memslot_delete(old);
+	}
 
 	/* Free the bitmap on failure if it was allocated above. */
 	if (r && new && new->dirty_bitmap && (!old || !old->dirty_bitmap))
Signature · 1 line
2.43.0
#7 lore raw
In reply to Aneesh Kumar K.V (Arm)
Quoted 6 lines · Aneesh Kumar K.V (Arm)

This series adds a guest_memfd device-resource framework for exposing PCI BAR memory to guests. The intended use is confidential device assignment, where KVM needs to coordinate private device mappings with shared access through VFIO. The Arm CCA backend is provided separately; these patches contain the guest_memfd, VFIO and IOMMUFD interfaces it uses.

Thank you Aneesh!

I definitely like this since it builds upon [1], the model where guest_memfd coordinates zapping during conversions for the provider. Please see comparison with the alternative at [2].

Quoted 3 lines

[...snip...]

I have questions:

Quoted 3 lines

Userspace creates a device-backed guest_memfd using the ordinary VFIO device fd as resource_fd, with GUEST_MEMFD_FLAG_USE_RESOURCE, GUEST_MEMFD_FLAG_DEVICE

With the model described at [1][2][3], I was thinking that the VFIO fd would be the resource fd. I'm hoping that there wouldn't be a need for GUEST_MEMFD_FLAG_DEVICE.

The plan [3] was for resource fd to represent just the resource but not provide any way to access the underlying resource, so that after .attach(), guest_memfd's fd should be the way userspace would access the underlying resource.

For tmpfs, the example in [1], fsmount() returns an fd that has no .mmap/.read/.write ops, which fits the plan above perfectly. It tells guest_memfd about the resource, but does not give userspace access to the resource.

In VFIO's case, vfio_device_fops does implement .mmap()/.read/.write, and I don't think there's a better existing fd that represents a single device.

Quoted 7 lines

and GUEST_MEMFD_FLAG_INIT_SHARED. Eligible BAR
intervals are registered as guest_memfd memslots. File offsets use the existing VFIO region-offset namespace, allowing one guest_memfd to cover multiple BAR intervals. Device-backed guest_memfd rejects mmap and fallocate; shared guest faults obtain bare BAR PFNs from the provider instead of resolving the memslot HVA or allocating folios.

The model I have in mind is kind of opposite from above. Instead of the guest_memfd rejecting mmap(), I'm thinking that the VFIO fd should be the one that rejects mmap(), read() and write() once guest_memfd attaches to it.

If userspace needed to mmap() the VFIO fd, it should instead mmap() the guest_memfd fd. guest_memfd doesn't support read() and write() now, but support can be added. The read/write for guest_memfd just forwards to vfio if the offset range is shared and blocks if the range is private.

For mmap(), for regular memory, mmap() is always allowed, but faulting dependsd on shared/private status. It would be nice if the same logic could apply to guest_memfds that wrap VFIO.

I prefer the userspace accesses to go through guest_memfd to VFIO so that the shared/private-ness can be enforced from guest_memfd.

Is GUEST_MEMFD_FLAG_DEVICE there because GUEST_MEMFD_FLAG_USE_RESOURCE tells guest_memfd to look up resource_inode->i_sb->s_op->gmem_provider_ops but for VFIO, gmem_provider_ops can't be stored in super_operations? If that's the only reason, that's a very good reason to store gmem_provider_ops in file_operations for gmem_provider_ops to serve different kinds resources and include VFIO.

I also noticed the need to guest_memfd_register_device_fops, so that guest_memfd knows the device supports being attached to?

What do you think of this: we have a common attach function for all VFIO fds in file_operations that would look up the struct vfio_device to determine if guest_memfd can attach to the vfio device? Actually, which devices would not support attaching? Wouldn't all devices support attaching? I'm thinking that using a device that is all-shared via guest_memfd should be no different from using the device directly. All operations should flow through to the device.

Regarding conversions, I would like to check: with Confidential IO, are conversions at runtime actually necessary?

Is the only "conversion" the one when the guest accepts a device? If so, maybe that "conversion" can be implemented by replacing memslots.

Pre-accept, mmap() the vfio fd directly, set it up in memslots.

Post-accept, remove the old memslot, wrap the vfio fd with guest_memfd, set up the guest_memfd statically with shared/private ranges as the TDI report requested and never allow conversions, replace the pre-accept memslot.

Quoted 11 lines

IOMMUFD resolves and pins the device's existing vDEVICE for the VM and serializes MMIO conversion through its MMIO mutex. VFIO supplies BAR PFNs, checks eligible ranges and excludes independent dma-buf exports while a guest_memfd provider is attached. VFIO host mmap faults, read/write and ioeventfd accesses check the requested range's guest_memfd attributes. Conversion revokes cached host mappings and shared guest mappings before installing private mappings. Other shared intervals remain accessible.

[...snip...]

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/CAEvNRgEseLO+LbkwXrEit0H2LH5Wx-srSvHEMpt0=upPL3tF=g@mail.gmail.com/
[3] https://lpc.events/event/20/contributions/2551/attachments/2047/4693/lpc-2026-gmem-other-backends.pdf

#8 lore raw
Quoted 34 lines · Ackerley Tng
Quoted 6 lines · Aneesh Kumar K.V (Arm)

This series adds a guest_memfd device-resource framework for exposing PCI BAR memory to guests. The intended use is confidential device assignment, where KVM needs to coordinate private device mappings with shared access through VFIO. The Arm CCA backend is provided separately; these patches contain the guest_memfd, VFIO and IOMMUFD interfaces it uses.

Thank you Aneesh!

I definitely like this since it builds upon [1], the model where guest_memfd coordinates zapping during conversions for the provider. Please see comparison with the alternative at [2].

Quoted 3 lines

[...snip...]

I have questions:

Quoted 3 lines

Userspace creates a device-backed guest_memfd using the ordinary VFIO device fd as resource_fd, with GUEST_MEMFD_FLAG_USE_RESOURCE, GUEST_MEMFD_FLAG_DEVICE

With the model described at [1][2][3], I was thinking that the VFIO fd would be the resource fd. I'm hoping that there wouldn't be a need for GUEST_MEMFD_FLAG_DEVICE.

The plan [3] was for resource fd to represent just the resource but not provide any way to access the underlying resource, so that after .attach(), guest_memfd's fd should be the way userspace would access the underlying resource.

Quoted 9 lines

For tmpfs, the example in [1], fsmount() returns an fd that has no .mmap/.read/.write ops, which fits the plan above perfectly. It tells guest_memfd about the resource, but does not give userspace access to the resource.

In VFIO's case, vfio_device_fops does implement .mmap()/.read/.write, and I don't think there's a better existing fd that represents a single device.

With VFIO, after attachment we can reject new mmap() calls by checking the attachment status in vfio_pci_core_mmap(). During attachment, we can reject the operation if the VFIO fd already has an mmap. But I guess read(), write(), and VFIO_DEVICE_IOEVENTFD should still operate through the VFIO fd, or are you suggesting that all of them operate through guest_memfd?

I am not sure we want to move the ioeventfd ioctl out of VFIO. If it remains there, userspace needs write access to shared BAR regions via vfio fd, so it would make sense to continue allowing read() and write() as well. If we allow read() and write(), should we also allow mmap()?

I agree that keeping userspace mappings(mmap) under guest_memfd rather than VFIO simplifies conversion. The conversion then becomes:

unmap_mapping_pages(inode->i_mapping, start, nr_pages, true); //unmap user mapping kvm_gmem_invalidate_start(inode, start, start + nr_pages, KVM_FILTER_SHARED); // stage2 unmap

Both are now under guest_memfd control, so no VFIO callback is needed.

Quoted 20 lines
Quoted 8 lines

and GUEST_MEMFD_FLAG_INIT_SHARED. Eligible BAR
intervals are registered as guest_memfd memslots. File offsets use the existing VFIO region-offset namespace, allowing one guest_memfd to cover multiple BAR intervals. Device-backed guest_memfd rejects mmap and fallocate; shared guest faults obtain bare BAR PFNs from the provider instead of resolving the memslot HVA or allocating folios.

The model I have in mind is kind of opposite from above. Instead of the guest_memfd rejecting mmap(), I'm thinking that the VFIO fd should be the one that rejects mmap(), read() and write() once guest_memfd attaches to it.

If userspace needed to mmap() the VFIO fd, it should instead mmap() the guest_memfd fd. guest_memfd doesn't support read() and write() now, but support can be added. The read/write for guest_memfd just forwards to vfio if the offset range is shared and blocks if the range is private.

Quoted 7 lines

For mmap(), for regular memory, mmap() is always allowed, but faulting dependsd on shared/private status. It would be nice if the same logic could apply to guest_memfds that wrap VFIO.

I prefer the userspace accesses to go through guest_memfd to VFIO so that the shared/private-ness can be enforced from guest_memfd.

Sure, I can implement this. I guess read(), write(), and ioeventfd will continue to go through the VFIO fd?

Quoted 10 lines

Is GUEST_MEMFD_FLAG_DEVICE there because GUEST_MEMFD_FLAG_USE_RESOURCE tells guest_memfd to look up resource_inode->i_sb->s_op->gmem_provider_ops but for VFIO, gmem_provider_ops can't be stored in super_operations? If that's the only reason, that's a very good reason to store gmem_provider_ops in file_operations for gmem_provider_ops to serve different kinds resources and include VFIO.

I can use the same approach for VFIO. I kept the current implementation simpler by using a registration framework on the VFIO side.

I can switch to gmem_provider_ops if we are comfortable adding the device-specific callbacks to guest_memfd_provider_operations. Since the VFIO core supports multiple backend drivers, such as vfio-pci, the superblock operations would essentially forward the calls to the appropriate backend driver. That is a VFIO-specific detail that guest_memfd can ignore.

Quoted 14 lines

I also noticed the need to guest_memfd_register_device_fops, so that guest_memfd knows the device supports being attached to?

What do you think of this: we have a common attach function for all VFIO fds in file_operations that would look up the struct vfio_device to determine if guest_memfd can attach to the vfio device? Actually, which devices would not support attaching? Wouldn't all devices support attaching? I'm thinking that using a device that is all-shared via guest_memfd should be no different from using the device directly. All operations should flow through to the device.

Quoted 3 lines

Regarding conversions, I would like to check: with Confidential IO, are conversions at runtime actually necessary?

They occur at runtime after the guest starts, but are infrequent. The entire region starts shared. The guest validates the interface report and requests that the BAR regions be mapped private. They remain private until the host converts them back to shared during the TDISP unlock operation.

Quoted 11 lines

Is the only "conversion" the one when the guest accepts a device? If so, maybe that "conversion" can be implemented by replacing memslots.

Pre-accept, mmap() the vfio fd directly, set it up in memslots.

Post-accept, remove the old memslot, wrap the vfio fd with guest_memfd, set up the guest_memfd statically with shared/private ranges as the TDI report requested and never allow conversions, replace the pre-accept memslot.

Is there a reason to use two different flows here? Why can't we always use guest_memfd? We could attach the device at startup and use guest_memfd before acceptance, while the BAR is mapped shared. We would not need mmap() unless userspace requires it for another reason; the VM fault handler could fault in those PFNs.

During device acceptance, we convert those BARs to private. On CCA, we also create the stage2 mappings at that point, since private BAR regions do not support fault handling.

Quoted 10 lines
Quoted 10 lines

IOMMUFD resolves and pins the device's existing vDEVICE for the VM and serializes MMIO conversion through its MMIO mutex. VFIO supplies BAR PFNs, checks eligible ranges and excludes independent dma-buf exports while a guest_memfd provider is attached. VFIO host mmap faults, read/write and ioeventfd accesses check the requested range's guest_memfd attributes. Conversion revokes cached host mappings and shared guest mappings before installing private mappings. Other shared intervals remain accessible.

Quoted 6 lines
Quoted 2 lines

[...snip...]

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/CAEvNRgEseLO+LbkwXrEit0H2LH5Wx-srSvHEMpt0=upPL3tF=g@mail.gmail.com/
[3] https://lpc.events/event/20/contributions/2551/attachments/2047/4693/lpc-2026-gmem-other-backends.pdf

-aneesh

#9 lore raw
Quoted 58 lines · Aneesh Kumar K.V
Quoted 34 lines · Ackerley Tng
Quoted 6 lines · Aneesh Kumar K.V (Arm)

This series adds a guest_memfd device-resource framework for exposing PCI BAR memory to guests. The intended use is confidential device assignment, where KVM needs to coordinate private device mappings with shared access through VFIO. The Arm CCA backend is provided separately; these patches contain the guest_memfd, VFIO and IOMMUFD interfaces it uses.

Thank you Aneesh!

I definitely like this since it builds upon [1], the model where guest_memfd coordinates zapping during conversions for the provider. Please see comparison with the alternative at [2].

Quoted 3 lines

[...snip...]

I have questions:

Quoted 3 lines

Userspace creates a device-backed guest_memfd using the ordinary VFIO device fd as resource_fd, with GUEST_MEMFD_FLAG_USE_RESOURCE, GUEST_MEMFD_FLAG_DEVICE

With the model described at [1][2][3], I was thinking that the VFIO fd would be the resource fd. I'm hoping that there wouldn't be a need for GUEST_MEMFD_FLAG_DEVICE.

The plan [3] was for resource fd to represent just the resource but not provide any way to access the underlying resource, so that after .attach(), guest_memfd's fd should be the way userspace would access the underlying resource.

Quoted 9 lines

For tmpfs, the example in [1], fsmount() returns an fd that has no .mmap/.read/.write ops, which fits the plan above perfectly. It tells guest_memfd about the resource, but does not give userspace access to the resource.

In VFIO's case, vfio_device_fops does implement .mmap()/.read/.write, and I don't think there's a better existing fd that represents a single device.

With VFIO, after attachment we can reject new mmap() calls by checking the attachment status in vfio_pci_core_mmap(). During attachment, we can reject the operation if the VFIO fd already has an mmap. But I guess read(), write(), and VFIO_DEVICE_IOEVENTFD should still operate through the VFIO fd, or are you suggesting that all of them operate through guest_memfd?

I am not sure we want to move the ioeventfd ioctl out of VFIO. If it remains there, userspace needs write access to shared BAR regions via vfio fd, so it would make sense to continue allowing read() and write() as well. If we allow read() and write(), should we also allow mmap()?

Quoted 9 lines

I agree that keeping userspace mappings(mmap) under guest_memfd rather than VFIO simplifies conversion. The conversion then becomes:

unmap_mapping_pages(inode->i_mapping, start, nr_pages, true); //unmap user mapping kvm_gmem_invalidate_start(inode, start, start + nr_pages, KVM_FILTER_SHARED); // stage2 unmap

Both are now under guest_memfd control, so no VFIO callback is needed.

+1, yes!

Quoted 24 lines
Quoted 24 lines
Quoted 8 lines

and GUEST_MEMFD_FLAG_INIT_SHARED. Eligible BAR
intervals are registered as guest_memfd memslots. File offsets use the existing VFIO region-offset namespace, allowing one guest_memfd to cover multiple BAR intervals. Device-backed guest_memfd rejects mmap and fallocate; shared guest faults obtain bare BAR PFNs from the provider instead of resolving the memslot HVA or allocating folios.

The model I have in mind is kind of opposite from above. Instead of the guest_memfd rejecting mmap(), I'm thinking that the VFIO fd should be the one that rejects mmap(), read() and write() once guest_memfd attaches to it.

If userspace needed to mmap() the VFIO fd, it should instead mmap() the guest_memfd fd. guest_memfd doesn't support read() and write() now, but support can be added. The read/write for guest_memfd just forwards to vfio if the offset range is shared and blocks if the range is private.

For mmap(), for regular memory, mmap() is always allowed, but faulting dependsd on shared/private status. It would be nice if the same logic could apply to guest_memfds that wrap VFIO.

Quoted 7 lines
Quoted 3 lines

I prefer the userspace accesses to go through guest_memfd to VFIO so that the shared/private-ness can be enforced from guest_memfd.

Sure, I can implement this. I guess read(), write(), and ioeventfd will continue to go through the VFIO fd?

If you agree to having mmap() go through guest_memfd, then read() and write() should also go through guest_memfd imo. I think it makes sense since guest_memfd gates accesses based on shared/private status.

guest_memfd already had plans to support write() [4], so I think supporting read() should be fine too.

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

I'm not super familiar with ioeventfd, let me know if this makes sense:
ioeventfd is a kind of config, like mmap() is a config, but faulting is where the actual access can happen.

guest_memfd always allows mmap(), but only allows faults on shared offset ranges.

If userspace sets up some link between a private range and some eventfd, I think that's ok, since it's not actually doing accesses. When the signalling actually happens, then guest_memfd needs to gate that.

Going by that, I think if the ioeventfd ioctls are just setting up links/mapping, then it can go through the VFIO fd.

Between going via the VFIO fd and guest_memfd, I think if "everything is wrapped by guest_memfd" a simpler mental model to go with, then maybe we could just go with swapping the entire f_ops with guest_memfd's intercepted version?

IIUC during the LPC discussion some people were suggesting creating a brand-new only-for-guest-memfd resource fd and not relying on existing mount fds or VFIO fds. What do you think of that? Instead of using the existing VFIO fd, would it be better to create a new for-gmem-to-wrap VFIO fd? I didn't like the idea of needing to create a new kind of fd for every resource guest_memfd needs to wrap.

Quoted 11 lines
Quoted 10 lines

Is GUEST_MEMFD_FLAG_DEVICE there because GUEST_MEMFD_FLAG_USE_RESOURCE tells guest_memfd to look up resource_inode->i_sb->s_op->gmem_provider_ops but for VFIO, gmem_provider_ops can't be stored in super_operations? If that's the only reason, that's a very good reason to store gmem_provider_ops in file_operations for gmem_provider_ops to serve different kinds resources and include VFIO.

Quoted 5 lines

I can use the same approach for VFIO. I kept the current implementation simpler by using a registration framework on the VFIO side.

I can switch to gmem_provider_ops if we are comfortable adding the device-specific callbacks to guest_memfd_provider_operations. Since the

Yes please, gmem_provider_ops in my RFC was just a minimal set, we can expand that as providers require.

Imo we should have either gmem_provider_ops in some ops (super_operations or file_operations or elsewhere), or a registration model for all of gmem_provider_ops, but not a mixture of global vs registration.

Quoted 19 lines

VFIO core supports multiple backend drivers, such as vfio-pci, the superblock operations would essentially forward the calls to the appropriate backend driver. That is a VFIO-specific detail that guest_memfd can ignore.

Quoted 14 lines

I also noticed the need to guest_memfd_register_device_fops, so that guest_memfd knows the device supports being attached to?

What do you think of this: we have a common attach function for all VFIO fds in file_operations that would look up the struct vfio_device to determine if guest_memfd can attach to the vfio device? Actually, which devices would not support attaching? Wouldn't all devices support attaching? I'm thinking that using a device that is all-shared via guest_memfd should be no different from using the device directly. All operations should flow through to the device.

Quoted 9 lines
Quoted 3 lines

Regarding conversions, I would like to check: with Confidential IO, are conversions at runtime actually necessary?

They occur at runtime after the guest starts, but are infrequent. The entire region starts shared. The guest validates the interface report and requests that the BAR regions be mapped private. They remain private until the host converts them back to shared during the TDISP unlock operation.

I see, so infrequent == once ever? Could the guest want to, at runtime, switch some BARs between shared/private? I wonder if the spec supports runtime conversions.

Quoted 6 lines
Quoted 6 lines

Is the only "conversion" the one when the guest accepts a device? If so, maybe that "conversion" can be implemented by replacing memslots.

Pre-accept, mmap() the vfio fd directly, set it up in memslots.

Quoted 8 lines
Quoted 5 lines

Post-accept, remove the old memslot, wrap the vfio fd with guest_memfd, set up the guest_memfd statically with shared/private ranges as the TDI report requested and never allow conversions, replace the pre-accept memslot.

Is there a reason to use two different flows here? Why can't we always use guest_memfd?

I was hoping blocking conversion could make the implementation simpler if we never need to convert at runtime. It might be easier to merge if we trim the features. :) It's also nice to have consistency with regular guest RAM though.

Quoted 5 lines

We could attach the device at startup and use
guest_memfd before acceptance, while the BAR is mapped shared. We would not need mmap() unless userspace requires it for another reason; the VM fault handler could fault in those PFNs.

Did you mean to just block mmap() access completely from userspace on a gmem-wrapped-vfio-fd?

If the CoCo guest and device allows some BAR to be shared, I was assuming that's because the host might need to take some action on those ranges. If so, then mmap() would be one way to access those ranges (in addition to read()/write()). I think we should still support faulting into userspace page tables for shared ranges from a gmem-wrapped-vfio-fd, and ideally follow the same model as regular guest_memfd where mmap() is always allowed, but not faulting for CoCo-private offset ranges.

Quoted 4 lines

During device acceptance, we convert those BARs to private. On CCA, we also create the stage2 mappings at that point, since private BAR regions do not support fault handling.

I see, thanks for explaining! This is one thing different private BARs, that private BARs cannot be faulted into stage 2 at runtime.

With Confidential IO, private BARs don't support fault handling, do shared BARs support fault handling?

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

IOMMUFD resolves and pins the device's existing vDEVICE for the VM and serializes MMIO conversion through its MMIO mutex. VFIO supplies BAR PFNs, checks eligible ranges and excludes independent dma-buf exports while a

Thanks for excluding dma-buf exports, this is important, we can't let dma-buf exports be a backdoor to access guest-private memory.

Quoted 14 lines
Quoted 6 lines
Quoted 6 lines

guest_memfd provider is attached. VFIO host mmap faults, read/write and ioeventfd accesses check the requested range's guest_memfd attributes. Conversion revokes cached host mappings and shared guest mappings before installing private mappings. Other shared intervals remain accessible.

Quoted 6 lines
Quoted 2 lines

[...snip...]

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/CAEvNRgEseLO+LbkwXrEit0H2LH5Wx-srSvHEMpt0=upPL3tF=g@mail.gmail.com/
[3] https://lpc.events/event/20/contributions/2551/attachments/2047/4693/lpc-2026-gmem-other-backends.pdf

-aneesh

#10 lore raw
Quoted 6 lines · Ackerley Tng
Quoted 4 lines · Aneesh Kumar K.V
Quoted 2 lines · Ackerley Tng

"Aneesh Kumar K.V (Arm)" <[email protected]> writes:

[ ... 65 lines skipped ... ]

Quoted 54 lines
Quoted 25 lines
Quoted 25 lines
Quoted 9 lines

and GUEST_MEMFD_FLAG_INIT_SHARED. Eligible BAR
intervals are registered as guest_memfd memslots. File offsets use the existing VFIO region-offset namespace, allowing one guest_memfd to cover multiple BAR intervals. Device-backed guest_memfd rejects mmap and fallocate; shared guest faults obtain bare BAR PFNs from the provider instead of resolving the memslot HVA or allocating folios.

The model I have in mind is kind of opposite from above. Instead of the guest_memfd rejecting mmap(), I'm thinking that the VFIO fd should be the one that rejects mmap(), read() and write() once guest_memfd attaches to it.

If userspace needed to mmap() the VFIO fd, it should instead mmap() the guest_memfd fd. guest_memfd doesn't support read() and write() now, but support can be added. The read/write for guest_memfd just forwards to vfio if the offset range is shared and blocks if the range is private.

For mmap(), for regular memory, mmap() is always allowed, but faulting dependsd on shared/private status. It would be nice if the same logic could apply to guest_memfds that wrap VFIO.

Quoted 7 lines
Quoted 3 lines

I prefer the userspace accesses to go through guest_memfd to VFIO so that the shared/private-ness can be enforced from guest_memfd.

Sure, I can implement this. I guess read(), write(), and ioeventfd will continue to go through the VFIO fd?

If you agree to having mmap() go through guest_memfd, then read() and write() should also go through guest_memfd imo. I think it makes sense since guest_memfd gates accesses based on shared/private status.

guest_memfd already had plans to support write() [4], so I think supporting read() should be fine too.

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

I'm not super familiar with ioeventfd, let me know if this makes sense:
ioeventfd is a kind of config, like mmap() is a config, but faulting is where the actual access can happen.

guest_memfd always allows mmap(), but only allows faults on shared offset ranges.

If userspace sets up some link between a private range and some eventfd, I think that's ok, since it's not actually doing accesses. When the signalling actually happens, then guest_memfd needs to gate that.

Quoted 9 lines

Going by that, I think if the ioeventfd ioctls are just setting up links/mapping, then it can go through the VFIO fd.

Between going via the VFIO fd and guest_memfd, I think if "everything is wrapped by guest_memfd" a simpler mental model to go with, then maybe we could just go with swapping the entire f_ops with guest_memfd's intercepted version?

I omitted the rest of the email so that we can focus on the above. While implementing mmap redirection through guest_memfd, I found that it results in code duplication in both the VMM and the kernel. The VMM already uses the VFIO fd for these operations. I think we should allow it to continue using the existing flow, with additional checks to ensure that it accesses only shared regions. Requiring the VMM to use guest_memfd as the file descriptor for accessing CoCo guest resources introduces unnecessary duplication.

We cannot move all provider fd ioctls to guest_memfd. Providers may have different ioctls that access shared regions, and supporting all of them through guest_memfd would not be practical. VFIO_DEVICE_IOEVENTFD is one example. If ioctls cannot be moved, the provider code will need access checks anyway. For example, for VFIO I do:

modified drivers/vfio/pci/vfio_pci_rdwr.c
@@ -44,7 +44,9 @@ int vfio_pci_core_iowrite##size(struct vfio_pci_core_device *vdev, \
{ \
if (test_mem) { \
down_read(&vdev->memory_lock); \
- if (!__vfio_pci_memory_enabled(vdev)) { \
+ if (!__vfio_pci_memory_enabled(vdev) || \
+ !vfio_pci_gmem_io_access_allowed(vdev, io, \
+ sizeof(u##size))) { \
up_read(&vdev->memory_lock); \
return -EIO; \
} \
@@ -70,7 +72,9 @@ int vfio_pci_core_ioread##size(struct vfio_pci_core_device *vdev, \
{ \
if (test_mem) { \
down_read(&vdev->memory_lock); \
- if (!__vfio_pci_memory_enabled(vdev)) { \
+ if (!__vfio_pci_memory_enabled(vdev) || \
+ !vfio_pci_gmem_io_access_allowed(vdev, io, \
+ sizeof(u##size))) { \
up_read(&vdev->memory_lock); \
return -EIO; \
} \
@@ -380,7 +384,10 @@ static int vfio_pci_ioeventfd_handler(void *opaque, void *unused)
if (ioeventfd->test_mem) {
if (!down_read_trylock(&vdev->memory_lock))
return 1; /* Lock contended, use thread */
- if (!__vfio_pci_memory_enabled(vdev)) {
+ if (!__vfio_pci_memory_enabled(vdev) ||
+ !vfio_pci_gmem_access_allowed(vdev,
+ VFIO_PCI_INDEX_TO_OFFSET(ioeventfd->bar) +
+ ioeventfd->pos, ioeventfd->count)) {
up_read(&vdev->memory_lock);
return 0;
}

If we are going to do this, it should also be OK to perform the check on the fault path. For VFIO, that is much simpler.

@@ -1766,6 +1764,14 @@ vm_fault_t vfio_pci_vmf_insert_pfn(struct vfio_pci_core_device *vdev,
if (vdev->pm_runtime_engaged || !__vfio_pci_memory_enabled(vdev))
return VM_FAULT_SIGBUS;

+ /* Check each page separately while guest_memfd controls BAR access. */
+ if (order && vdev->gmem)
+ return VM_FAULT_FALLBACK;
+ /* memory_lock keeps revocation from racing admission and PTE insertion. */
+ if (!vfio_pci_gmem_access_allowed(vdev,
+ (u64)vmf->pgoff << PAGE_SHIFT, PAGE_SIZE))
+ return VM_FAULT_SIGBUS;
+
if (!order)
return vmf_insert_pfn(vmf->vma, vmf->address, pfn);

Given the above, it seems much simpler to allow mmap(), read(), write(), and ioctls through the VFIO fd. Attach should require GUEST_MEMFD_FLAG_MMAP, and mmap() on the VFIO fd should be allowed only when that flag is set.

I can post a series demonstrating the implementation duplication if that would help.

-aneesh