Skip to contentSkip to conversation

vfio: Use file-based reference counting for KVM

PATCH Superseded Steffen Eiden 5 participants 6 messages Aug 12 – Sep 3

Subsystems (8)
x86 KVM s390 KVM x86 +4 more subsystems

v1 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 vfio: Use file-based reference counting for KVM

Replace manual module reference counting with file-based reference counting for KVM integration. Previously, VFIO used symbol_get() to obtain function pointers for kvm_get_kvm_safe() and kvm_put_kvm(), then manually tracked module references through these symbols. This approach required storing the put_kvm function pointer in each device and carefully managing symbol references. Remove the put_kvm field in struct vfio_device as is it no longer used.

Pass struct file pointers instead of struct kvm pointers throughout the VFIO-KVM interface. This leverages the kernel's existing file reference counting mechanism via get_file()/get_file_active() and fput(), eliminating the need for manual module reference tracking. The file->private_data field provides access to the underlying struct kvm when needed.

group->kvm and df->kvm hold a reference of their own, taken when the pointer is stored and dropped when it is overwritten or cleared. They have to: the kvm-vfio device fd holds a VM reference of its own, so the VM file can be closed and released while the kvm-vfio device is still alive and still pointing at it. filp_cachep is SLAB_TYPESAFE_BY_RCU, so a stale pointer left in those slots could be made to reference a recycled, unrelated file.

kvm->file itself carries no reference, so that it does not pin the VM. It is only ever read with get_file_active(), which is safe because kvm_vm_release() clears it, i.e. before the struct file is freed.

This simplifies the code and removes all remaining externally exported symbols for KVM, paving the path for a second concurrent KVM module.

---
This is a spin-off for the arm-on-s390 series for fast-lane merging requested by sean[0]. It is based on patch 1 [1] of the v6 of the arm-on-s390 series but with some fixes for some issues pointed out by sashiko. The useless rcu protection of kvm->file is removed and the getting-the-file-handle process is streamlined.

Based on next-20260811.

Steffen

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

---
 arch/x86/include/asm/kvm_page_track.h |  8 ++---
 arch/x86/kvm/Makefile                 |  5 +--
 arch/x86/kvm/mmu/page_track.c         | 20 +++++++-----
 drivers/s390/crypto/vfio_ap_ops.c     | 20 ++++++++----
 drivers/vfio/group.c                  | 11 ++++++-
 drivers/vfio/pci/vfio_pci_zdev.c      |  7 ++++-
 drivers/vfio/vfio.h                   | 10 +++---
 drivers/vfio/vfio_main.c              | 57 +++++++++++------------------------
 include/linux/kvm_host.h              |  8 +++++
 include/linux/vfio.h                  |  5 ++-
 virt/kvm/kvm_main.c                   | 20 ++++++++++--
 virt/kvm/vfio.c                       | 13 +++++---
 12 files changed, 106 insertions(+), 78 deletions(-)
arch/x86/include/asm/kvm_page_track.h +4 -4
index 3d040741044b..046a25c8fe4f 100644
@@ -44,13 +44,13 @@ struct kvm_page_track_notifier_node {
 				    struct kvm_page_track_notifier_node *node);
 };
 
-int kvm_page_track_register_notifier(struct kvm *kvm,
+int kvm_page_track_register_notifier(struct file *file,
 				     struct kvm_page_track_notifier_node *n);
-void kvm_page_track_unregister_notifier(struct kvm *kvm,
+void kvm_page_track_unregister_notifier(struct file *file,
 					struct kvm_page_track_notifier_node *n);
 
-int kvm_write_track_add_gfn(struct kvm *kvm, gfn_t gfn);
-int kvm_write_track_remove_gfn(struct kvm *kvm, gfn_t gfn);
+int kvm_write_track_add_gfn(struct file *file, gfn_t gfn);
+int kvm_write_track_remove_gfn(struct file *file, gfn_t gfn);
 #else
 /*
  * Allow defining a node in a structure even if page tracking is disabled, e.g.
arch/x86/kvm/Makefile +1 -4
index 0474604ab8a1..96f89d6f7e6a 100644
@@ -60,10 +60,7 @@ exports_grep_trailer := --include='*.[ch]' -nrw $(srctree)/virt/kvm $(srctree)/a
 			grep -v -e kvm_page_track_register_notifier \
 				-e kvm_page_track_unregister_notifier \
 				-e kvm_write_track_add_gfn \
-				-e kvm_write_track_remove_gfn \
-				-e kvm_get_kvm \
-				-e kvm_get_kvm_safe \
-				-e kvm_put_kvm
+				-e kvm_write_track_remove_gfn
 
 # 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
arch/x86/kvm/mmu/page_track.c +12 -8
index 7e8195a311bb..98f133e4f0b3 100644
@@ -237,10 +237,11 @@ static int kvm_enable_external_write_tracking(struct kvm *kvm)
  * register the notifier so that event interception for the tracked guest
  * pages can be received.
  */
-int kvm_page_track_register_notifier(struct kvm *kvm,
+int kvm_page_track_register_notifier(struct file *file,
 				     struct kvm_page_track_notifier_node *n)
 {
 	struct kvm_page_track_notifier_head *head;
+	struct kvm *kvm = file_to_kvm(file);
 	int r;
 
 	if (!kvm || kvm->mm != current->mm)
@@ -252,7 +253,7 @@ int kvm_page_track_register_notifier(struct kvm *kvm,
 			return r;
 	}
 
-	kvm_get_kvm(kvm);
+	get_file(file);
 
 	head = &kvm->arch.track_notifier_head;
 
@@ -267,10 +268,11 @@ EXPORT_SYMBOL_GPL(kvm_page_track_register_notifier);
  * stop receiving the event interception. It is the opposed operation of
  * kvm_page_track_register_notifier().
  */
-void kvm_page_track_unregister_notifier(struct kvm *kvm,
+void kvm_page_track_unregister_notifier(struct file *file,
 					struct kvm_page_track_notifier_node *n)
 {
 	struct kvm_page_track_notifier_head *head;
+	struct kvm *kvm = file_to_kvm(file);
 
 	head = &kvm->arch.track_notifier_head;
 
@@ -279,7 +281,7 @@ void kvm_page_track_unregister_notifier(struct kvm *kvm,
 	write_unlock(&kvm->mmu_lock);
 	synchronize_srcu(&head->track_srcu);
 
-	kvm_put_kvm(kvm);
+	fput(file);
 }
 EXPORT_SYMBOL_GPL(kvm_page_track_unregister_notifier);
 
@@ -336,11 +338,12 @@ void kvm_page_track_delete_slot(struct kvm *kvm, struct kvm_memory_slot *slot)
  * add guest page to the tracking pool so that corresponding access on that
  * page will be intercepted.
  *
- * @kvm: the guest instance we are interested in.
+ * @file: the VM file of the guest instance we are interested in.
  * @gfn: the guest page.
  */
-int kvm_write_track_add_gfn(struct kvm *kvm, gfn_t gfn)
+int kvm_write_track_add_gfn(struct file *file, gfn_t gfn)
 {
+	struct kvm *kvm = file_to_kvm(file);
 	struct kvm_memory_slot *slot;
 	int idx;
 
@@ -366,11 +369,12 @@ EXPORT_SYMBOL_GPL(kvm_write_track_add_gfn);
  * remove the guest page from the tracking pool which stops the interception
  * of corresponding access on that page.
  *
- * @kvm: the guest instance we are interested in.
+ * @file: the VM file of the guest instance we are interested in.
  * @gfn: the guest page.
  */
-int kvm_write_track_remove_gfn(struct kvm *kvm, gfn_t gfn)
+int kvm_write_track_remove_gfn(struct file *file, gfn_t gfn)
 {
+	struct kvm *kvm = file_to_kvm(file);
 	struct kvm_memory_slot *slot;
 	int idx;
 
drivers/s390/crypto/vfio_ap_ops.c +14 -6
index 99a0efd999ef..42d331c84e66 100644
@@ -1817,17 +1817,27 @@ static const struct attribute_group *vfio_ap_mdev_attr_groups[] = {
 
 /**
  * vfio_ap_mdev_set_kvm - sets all data for @matrix_mdev that are needed
- * to manage AP resources for the guest whose state is represented by @kvm
+ * to manage AP resources for the guest whose state is represented by
+ * @kvm_file
  *
  * @matrix_mdev: a mediated matrix device
- * @kvm: reference to KVM instance
+ * @kvm_file: the KVM VM file this vfio device is associated with
  *
- * Return: 0 if no other mediated matrix device has a reference to @kvm;
+ * Return: 0 if no other mediated matrix device has a reference to the VM;
  * otherwise, returns an -EPERM.
  */
 static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
-				struct kvm *kvm)
+				struct file *kvm_file)
 {
+	struct kvm *kvm;
+
+	if (!kvm_file)
+		return -ENOENT;
+
+	kvm = kvm_file->private_data;
+	if (!kvm)
+		return -ENOENT;
+
 	if (kvm->arch.crypto.crycbd) {
 		get_update_locks_for_kvm(kvm);
 		if (kvm->arch.crypto.pqap_hook) {
@@ -1836,7 +1846,6 @@ static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
 		}
 		kvm->arch.crypto.pqap_hook = &matrix_mdev->pqap_hook;
 
-		kvm_get_kvm(kvm);
 		matrix_mdev->kvm = kvm;
 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
 		release_update_locks_for_kvm(kvm);
@@ -1889,7 +1898,6 @@ static void vfio_ap_mdev_unset_kvm(struct ap_matrix_mdev *matrix_mdev)
 		matrix_mdev->kvm = NULL;
 
 		release_update_locks_for_kvm(kvm);
-		kvm_put_kvm(kvm);
 	}
 }
 
drivers/vfio/group.c +10 -1
index b2299e5bc6df..5bf8cbdff377 100644
@@ -860,11 +860,20 @@ bool vfio_group_enforced_coherent(struct vfio_group *group)
 	return ret;
 }
 
-void vfio_group_set_kvm(struct vfio_group *group, struct kvm *kvm)
+void vfio_group_set_kvm(struct vfio_group *group, struct file *kvm)
 {
+	struct file *old;
+
+	if (kvm)
+		get_file(kvm);
+
 	spin_lock(&group->kvm_ref_lock);
+	old = group->kvm;
 	group->kvm = kvm;
 	spin_unlock(&group->kvm_ref_lock);
+
+	if (old)
+		fput(old);
 }
 
 /**
drivers/vfio/pci/vfio_pci_zdev.c +6 -1
index 0990fdb146b7..d3a110101353 100644
@@ -144,6 +144,7 @@ int vfio_pci_info_zdev_add_caps(struct vfio_pci_core_device *vdev,
 int vfio_pci_zdev_open_device(struct vfio_pci_core_device *vdev)
 {
 	struct zpci_dev *zdev = to_zpci(vdev->pdev);
+	struct kvm *kvm;
 
 	if (!zdev)
 		return -ENODEV;
@@ -151,8 +152,12 @@ int vfio_pci_zdev_open_device(struct vfio_pci_core_device *vdev)
 	if (!vdev->vdev.kvm)
 		return 0;
 
+	kvm = vdev->vdev.kvm->private_data;
+	if (!kvm)
+		return -ENOENT;
+
 	if (zpci_kvm_hook.kvm_register)
-		return zpci_kvm_hook.kvm_register(zdev, vdev->vdev.kvm);
+		return zpci_kvm_hook.kvm_register(zdev, kvm);
 
 	return -ENOENT;
 }
drivers/vfio/vfio.h +5 -5
index 7728bc99b63d..f76504d707e1 100644
@@ -23,7 +23,7 @@ struct vfio_device_file {
 	u8 access_granted;
 	u32 devid; /* only valid when iommufd is valid */
 	spinlock_t kvm_ref_lock; /* protect kvm field */
-	struct kvm *kvm;
+	struct file *kvm;
 	struct iommufd_ctx *iommufd; /* protected by struct vfio_device_set::lock */
 };
 
@@ -88,7 +88,7 @@ struct vfio_group {
 #endif
 	enum vfio_group_type		type;
 	struct mutex			group_lock;
-	struct kvm			*kvm;
+	struct file			*kvm;
 	struct file			*opened_file;
 	struct iommufd_ctx		*iommufd;
 	spinlock_t			kvm_ref_lock;
@@ -107,7 +107,7 @@ void vfio_device_group_unuse_iommu(struct vfio_device *device);
 void vfio_df_group_close(struct vfio_device_file *df);
 struct vfio_group *vfio_group_from_file(struct file *file);
 bool vfio_group_enforced_coherent(struct vfio_group *group);
-void vfio_group_set_kvm(struct vfio_group *group, struct kvm *kvm);
+void vfio_group_set_kvm(struct vfio_group *group, struct file *kvm);
 bool vfio_device_has_container(struct vfio_device *device);
 int __init vfio_group_init(void);
 void vfio_group_cleanup(void);
@@ -429,11 +429,11 @@ static inline void vfio_virqfd_exit(void)
 #endif
 
 #if IS_ENABLED(CONFIG_KVM)
-void vfio_device_get_kvm_safe(struct vfio_device *device, struct kvm *kvm);
+void vfio_device_get_kvm_safe(struct vfio_device *device, struct file *kvm);
 void vfio_device_put_kvm(struct vfio_device *device);
 #else
 static inline void vfio_device_get_kvm_safe(struct vfio_device *device,
-					    struct kvm *kvm)
+					    struct file *kvm)
 {
 }
 
drivers/vfio/vfio_main.c +18 -39

105 lines not on this page · raw message

include/linux/kvm_host.h +8 -0
index 03bfc92864b6..bfecce1b5955 100644
@@ -784,6 +784,13 @@ struct kvm {
 	 * kvm_swap_active_memslots().
 	 */
 	struct mutex slots_arch_lock;
+	/*
+	 * Back-reference to the VM file for subsystems (e.g., VFIO). Holds no
+	 * reference to avoid pinning the VM. Access via get_file_active(&kvm->file)
+	 * only—safe because cleared in kvm_vm_release() before file freed. Callers
+	 * storing the result must take their own reference via get_file()
+	 */
+	struct file *file;
 	struct mm_struct *mm; /* userspace tied to this vm */
 	unsigned long nr_memslot_pages;
 	/* The two memslot sets - active and inactive (per address space) */
@@ -1082,6 +1089,7 @@ void kvm_get_kvm(struct kvm *kvm);
 bool kvm_get_kvm_safe(struct kvm *kvm);
 void kvm_put_kvm(struct kvm *kvm);
 bool file_is_kvm(struct file *file);
+struct kvm *file_to_kvm(struct file *file);
 void kvm_put_kvm_no_destroy(struct kvm *kvm);
 
 static inline struct kvm_memslots *__kvm_memslots(struct kvm *kvm, int as_id)
include/linux/vfio.h +2 -3
index 45f08986359e..0cc91c6f96d2 100644
@@ -54,7 +54,7 @@ struct vfio_device {
 	struct list_head dev_set_list;
 	unsigned int migration_flags;
 	u8 precopy_info_v2;
-	struct kvm *kvm;
+	struct file *kvm;
 
 	/* Members below here are private, not for driver use */
 	unsigned int index;
@@ -66,7 +66,6 @@ struct vfio_device {
 	unsigned int open_count;
 	struct completion comp;
 	struct iommufd_access *iommufd_access;
-	void (*put_kvm)(struct kvm *kvm);
 	struct inode *inode;
 #if IS_ENABLED(CONFIG_IOMMUFD)
 	struct iommufd_device *iommufd_device;
@@ -378,7 +377,7 @@ static inline bool vfio_file_has_dev(struct file *file, struct vfio_device *devi
 #endif
 bool vfio_file_is_valid(struct file *file);
 bool vfio_file_enforced_coherent(struct file *file);
-void vfio_file_set_kvm(struct file *file, struct kvm *kvm);
+void vfio_file_set_kvm(struct file *vfio_file, struct file *kvm);
 
 #define VFIO_PIN_PAGES_MAX_ENTRIES	(PAGE_SIZE/sizeof(unsigned long))
 
virt/kvm/kvm_main.c +17 -3
index 65eb26a0520d..34b4c43908b3 100644
@@ -1314,7 +1314,7 @@ void kvm_get_kvm(struct kvm *kvm)
 {
 	refcount_inc(&kvm->users_count);
 }
-EXPORT_SYMBOL_GPL(kvm_get_kvm);
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_kvm);
 
 /*
  * Make sure the vm is not during destruction, which is a safe version of
@@ -1324,14 +1324,14 @@ bool kvm_get_kvm_safe(struct kvm *kvm)
 {
 	return refcount_inc_not_zero(&kvm->users_count);
 }
-EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_kvm_safe);
 
 void kvm_put_kvm(struct kvm *kvm)
 {
 	if (refcount_dec_and_test(&kvm->users_count))
 		kvm_destroy_vm(kvm);
 }
-EXPORT_SYMBOL_GPL(kvm_put_kvm);
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_put_kvm);
 
 /*
  * Used to put a reference that was taken on behalf of an object associated
@@ -1352,6 +1352,8 @@ static int kvm_vm_release(struct inode *inode, struct file *filp)
 
 	kvm_irqfd_release(kvm);
 
+	WRITE_ONCE(kvm->file, NULL);
+
 	kvm_put_kvm(kvm);
 	return 0;
 }
@@ -5496,6 +5498,15 @@ bool file_is_kvm(struct file *file)
 }
 EXPORT_SYMBOL_FOR_KVM_INTERNAL(file_is_kvm);
 
+struct kvm *file_to_kvm(struct file *file)
+{
+	if (!file_is_kvm(file))
+		return NULL;
+
+	return file->private_data;
+}
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(file_to_kvm);
+
 static int kvm_dev_ioctl_create_vm(unsigned long type)
 {
 	char fdname[ITOA_MAX_LEN + 1];
@@ -5527,6 +5538,9 @@ static int kvm_dev_ioctl_create_vm(unsigned long type)
 	 * cases it will be called by the final fput(file) and will take
 	 * care of doing kvm_put_kvm(kvm).
 	 */
+
+	kvm->file = file;
+
 	kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
 
 	fd_install(fd, file);
virt/kvm/vfio.c +9 -4
index 6cdc4e9a333a..19548a430942 100644
@@ -35,15 +35,15 @@ struct kvm_vfio {
 	bool noncoherent;
 };
 
-static void kvm_vfio_file_set_kvm(struct file *file, struct kvm *kvm)
+static void kvm_vfio_file_set_kvm(struct file *vfio_file, struct file *kvm)
 {
-	void (*fn)(struct file *file, struct kvm *kvm);
+	void (*fn)(struct file *vfio_file, struct file *kvm);
 
 	fn = symbol_get(vfio_file_set_kvm);
 	if (!fn)
 		return;
 
-	fn(file, kvm);
+	fn(vfio_file, kvm);
 
 	symbol_put(vfio_file_set_kvm);
 }
@@ -144,6 +144,7 @@ static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)
 {
 	struct kvm_vfio *kv = dev->private;
 	struct kvm_vfio_file *kvf;
+	struct file *kvm_file __free(fput) = NULL;
 	struct file *filp __free(fput) = NULL;
 
 	filp = fget(fd);
@@ -154,6 +155,10 @@ static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)
 	if (!kvm_vfio_file_is_valid(filp))
 		return -EINVAL;
 
+	kvm_file = get_file_active(&dev->kvm->file);
+	if (!kvm_file)
+		return -ENOENT;
+
 	guard(mutex)(&kv->lock);
 
 	list_for_each_entry(kvf, &kv->file_list, node) {
@@ -168,7 +173,7 @@ static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)
 	kvf->file = get_file(filp);
 	list_add_tail(&kvf->node, &kv->file_list);
 
-	kvm_vfio_file_set_kvm(kvf->file, dev->kvm);
+	kvm_vfio_file_set_kvm(kvf->file, kvm_file);
 	kvm_vfio_update_coherency(dev);
 
 	return 0;

---
base-commit: 5e6de6a2b522f659defacb1551d0465ba6ce13cf
change-id: 20260812-vfio-f9069d8ab545

Best regards,

Signature · 1 line
Steffen Eiden <[email protected]>
#1 lore raw
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

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

Pre-existing issues:
- [High] Missing SRCU read lock when iterating over KVM memslots in kvm_enable_external_write_tracking. --

--- Patch [1]: [PATCH] vfio: Use file-based reference counting for KVM --- commit 6e2d7f7af50df153e78728c6ab103209dafd02a4
Author: Steffen Eiden <[email protected]>
Subject: vfio: Use file-based reference counting for KVM

This commit replaces manual module reference counting with file-based reference counting for KVM integration in VFIO. It passes struct file pointers instead of struct kvm pointers throughout the interface to leverage the kernel's existing file reference counting mechanism.

arch/x86/kvm/mmu/page_track.c static int kvm_enable_external_write_tracking(struct kvm *kvm)

Quoted 5 lines
arch/x86/kvm/mmu/page_track.c +0 -0
index 7e8195a311bb0..98f133e4f0b32 100644
@@ -237,10 +237,11 @@ static int kvm_enable_external_write_tracking(struct kvm *kvm)

[Severity: High]
This is a pre-existing issue, but does kvm_enable_external_write_tracking() need to hold srcu_read_lock(&kvm->srcu) when iterating over the memslots array?

Looking at the function, it retrieves and iterates over the memslots array while only holding the slots_arch_lock mutex:

mutex_lock(&kvm->slots_arch_lock);
...

for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
    slots = __kvm_memslots(kvm, i);
    kvm_for_each_memslot(slot, bkt, slots) {
        r = kvm_page_track_write_tracking_alloc(slot);
        if (r)
            goto out_unlock;
    }
}

Without holding srcu_read_lock(&kvm->srcu) or the writer-side slots_lock, could a concurrent memslot update swap and free the memslots array while the loop is traversing it, causing a use-after-free?

Quoted 6 lines
arch/x86/kvm/mmu/page_track.c +1 -1
  * register the notifier so that event interception for the tracked guest
  * pages can be received.
  */
-int kvm_page_track_register_notifier(struct kvm *kvm,
+int kvm_page_track_register_notifier(struct file *file,
 				     struct kvm_page_track_notifier_node *n)

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#2 lore raw
Quoted 25 lines · On Wed, Aug 12, 2026, [email protected] wrote:

arch/x86/kvm/mmu/page_track.c static int kvm_enable_external_write_tracking(struct kvm *kvm)

Quoted 5 lines
arch/x86/kvm/mmu/page_track.c +0 -0
index 7e8195a311bb0..98f133e4f0b32 100644
@@ -237,10 +237,11 @@ static int kvm_enable_external_write_tracking(struct kvm *kvm)

[Severity: High]
This is a pre-existing issue, but does kvm_enable_external_write_tracking() need to hold srcu_read_lock(&kvm->srcu) when iterating over the memslots array?

Looking at the function, it retrieves and iterates over the memslots array while only holding the slots_arch_lock mutex:

mutex_lock(&kvm->slots_arch_lock);
...

for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
    slots = __kvm_memslots(kvm, i);
    kvm_for_each_memslot(slot, bkt, slots) {
        r = kvm_page_track_write_tracking_alloc(slot);
        if (r)
            goto out_unlock;
    }
}
Quoted 3 lines

Without holding srcu_read_lock(&kvm->srcu) or the writer-side slots_lock, could a concurrent memslot update swap and free the memslots array while the loop is traversing it, causing a use-after-free?

No, because the part of kvm_swap_active_memslots() that performs the actual swap runs with slots_arch_lock held.

maintainer Reviewed-by on v1 1/1
#3 lore raw
In reply to Steffen Eiden
Quoted 46 lines · Steffen Eiden

...

drivers/s390/crypto/vfio_ap_ops.c +14 -5
index 99a0efd999ef..42d331c84e66 100644
@@ -1817,17 +1817,27 @@ static const struct attribute_group *vfio_ap_mdev_attr_groups[] = {
 
  /**
   * vfio_ap_mdev_set_kvm - sets all data for @matrix_mdev that are needed
- * to manage AP resources for the guest whose state is represented by @kvm
+ * to manage AP resources for the guest whose state is represented by
+ * @kvm_file
   *
   * @matrix_mdev: a mediated matrix device
- * @kvm: reference to KVM instance
+ * @kvm_file: the KVM VM file this vfio device is associated with
   *
- * Return: 0 if no other mediated matrix device has a reference to @kvm;
+ * Return: 0 if no other mediated matrix device has a reference to the VM;
   * otherwise, returns an -EPERM.
   */
  static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
-				struct kvm *kvm)
+				struct file *kvm_file)
  {
+	struct kvm *kvm;
+
+	if (!kvm_file)
+		return -ENOENT;
+
+	kvm = kvm_file->private_data;
+	if (!kvm)
+		return -ENOENT;
+
  	if (kvm->arch.crypto.crycbd) {
  		get_update_locks_for_kvm(kvm);
  		if (kvm->arch.crypto.pqap_hook) {
@@ -1836,7 +1846,6 @@ static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
  		}
  		kvm->arch.crypto.pqap_hook = &matrix_mdev->pqap_hook;
 
-		kvm_get_kvm(kvm);
  		matrix_mdev->kvm = kvm;
  		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
  		release_update_locks_for_kvm(kvm);

drivers/s390/crypto/vfio_ap_ops.c static void vfio_ap_mdev_unset_kvm(struct ap_matrix_mdev *matrix_mdev) · line 1902

Quoted 6 lines
drivers/s390/crypto/vfio_ap_ops.c +0 -1
@@ -1889,7 +1898,6 @@ static void vfio_ap_mdev_unset_kvm(struct ap_matrix_mdev *matrix_mdev)
  		matrix_mdev->kvm = NULL;
 
  		release_update_locks_for_kvm(kvm);
-		kvm_put_kvm(kvm);
  	}
  }
maintainer
#4 lore raw
In reply to Steffen Eiden
Quoted 34 lines · On Wed, 12 Aug 2026 20:55:30 +0200 Steffen Eiden <[email protected]> wrote:

Replace manual module reference counting with file-based reference counting for KVM integration. Previously, VFIO used symbol_get() to obtain function pointers for kvm_get_kvm_safe() and kvm_put_kvm(), then manually tracked module references through these symbols. This approach required storing the put_kvm function pointer in each device and carefully managing symbol references. Remove the put_kvm field in struct vfio_device as is it no longer used.

Pass struct file pointers instead of struct kvm pointers throughout the VFIO-KVM interface. This leverages the kernel's existing file reference counting mechanism via get_file()/get_file_active() and fput(), eliminating the need for manual module reference tracking. The file->private_data field provides access to the underlying struct kvm when needed.

group->kvm and df->kvm hold a reference of their own, taken when the pointer is stored and dropped when it is overwritten or cleared. They have to: the kvm-vfio device fd holds a VM reference of its own, so the VM file can be closed and released while the kvm-vfio device is still alive and still pointing at it. filp_cachep is SLAB_TYPESAFE_BY_RCU, so a stale pointer left in those slots could be made to reference a recycled, unrelated file.

kvm->file itself carries no reference, so that it does not pin the VM. It is only ever read with get_file_active(), which is safe because kvm_vm_release() clears it, i.e. before the struct file is freed.

This simplifies the code and removes all remaining externally exported symbols for KVM, paving the path for a second concurrent KVM module.

Quoted 6 lines

---
This is a spin-off for the arm-on-s390 series for fast-lane merging requested by sean[0]. It is based on patch 1 [1] of the v6 of the arm-on-s390 series but with some fixes for some issues pointed out by sashiko. The useless rcu protection of kvm->file is removed and the getting-the-file-handle process is streamlined.

We'll need a shared branch to merge this across two subsystems and the vfio-ap driver. Based on $Subject and LoC I can volunteer to provide that once we're settled. A couple minor issues below...

Quoted 13 lines
drivers/vfio/pci/vfio_pci_zdev.c +1 -0
index 0990fdb146b7..d3a110101353 100644
@@ -144,6 +144,7 @@ int vfio_pci_info_zdev_add_caps(struct vfio_pci_core_device *vdev,
 int vfio_pci_zdev_open_device(struct vfio_pci_core_device *vdev)
 {
 	struct zpci_dev *zdev = to_zpci(vdev->pdev);
+	struct kvm *kvm;
 
 	if (!zdev)
 		return -ENODEV;

drivers/vfio/pci/vfio_pci_zdev.c int vfio_pci_zdev_open_device(struct vfio_pci_core_device *vdev) · line 160

Quoted 10 lines
drivers/vfio/pci/vfio_pci_zdev.c +5 -1
@@ -151,8 +152,12 @@ int vfio_pci_zdev_open_device(struct vfio_pci_core_device *vdev)
 	if (!vdev->vdev.kvm)
 		return 0;
 
+	kvm = vdev->vdev.kvm->private_data;
+	if (!kvm)
+		return -ENOENT;
+
 	if (zpci_kvm_hook.kvm_register)
-		return zpci_kvm_hook.kvm_register(zdev, vdev->vdev.kvm);
+		return zpci_kvm_hook.kvm_register(zdev, kvm);

There are conflicts here with Farhan's 9f240376d034 ("s390/pci: Store PCI error information for passthrough devices"), we need to maintain the error exit funnel through stop mediation.

Quoted 25 lines
drivers/vfio/pci/vfio_pci_zdev.c +0 -0
 	return -ENOENT;
 }
drivers/vfio/vfio.h +2 -2
index 7728bc99b63d..f76504d707e1 100644
@@ -23,7 +23,7 @@ struct vfio_device_file {
 	u8 access_granted;
 	u32 devid; /* only valid when iommufd is valid */
 	spinlock_t kvm_ref_lock; /* protect kvm field */
-	struct kvm *kvm;
+	struct file *kvm;
 	struct iommufd_ctx *iommufd; /* protected by struct vfio_device_set::lock */
 };
 
@@ -88,7 +88,7 @@ struct vfio_group {
 #endif
 	enum vfio_group_type		type;
 	struct mutex			group_lock;
-	struct kvm			*kvm;
+	struct file			*kvm;
 	struct file			*opened_file;
 	struct iommufd_ctx		*iommufd;
 	spinlock_t			kvm_ref_lock;

drivers/vfio/vfio.h void vfio_device_group_unuse_iommu(struct vfio_device *device); · line 113

Quoted 8 lines
drivers/vfio/vfio.h +1 -1
@@ -107,7 +107,7 @@ void vfio_device_group_unuse_iommu(struct vfio_device *device);
 void vfio_df_group_close(struct vfio_device_file *df);
 struct vfio_group *vfio_group_from_file(struct file *file);
 bool vfio_group_enforced_coherent(struct vfio_group *group);
-void vfio_group_set_kvm(struct vfio_group *group, struct kvm *kvm);
+void vfio_group_set_kvm(struct vfio_group *group, struct file *kvm);
 bool vfio_device_has_container(struct vfio_device *device);
 int __init vfio_group_init(void);
 void vfio_group_cleanup(void);

There's a stub in the !CONFIG_VFIO_GROUP set of declarations below this that isn't updated to the new prototype, build breaks. Thanks,

Alex

#5 lore raw
Quoted 44 lines · Alex Williamson
Quoted 34 lines · On Wed, 12 Aug 2026 20:55:30 +0200 Steffen Eiden <[email protected]> wrote:

Replace manual module reference counting with file-based reference counting for KVM integration. Previously, VFIO used symbol_get() to obtain function pointers for kvm_get_kvm_safe() and kvm_put_kvm(), then manually tracked module references through these symbols. This approach required storing the put_kvm function pointer in each device and carefully managing symbol references. Remove the put_kvm field in struct vfio_device as is it no longer used.

Pass struct file pointers instead of struct kvm pointers throughout the VFIO-KVM interface. This leverages the kernel's existing file reference counting mechanism via get_file()/get_file_active() and fput(), eliminating the need for manual module reference tracking. The file->private_data field provides access to the underlying struct kvm when needed.

group->kvm and df->kvm hold a reference of their own, taken when the pointer is stored and dropped when it is overwritten or cleared. They have to: the kvm-vfio device fd holds a VM reference of its own, so the VM file can be closed and released while the kvm-vfio device is still alive and still pointing at it. filp_cachep is SLAB_TYPESAFE_BY_RCU, so a stale pointer left in those slots could be made to reference a recycled, unrelated file.

kvm->file itself carries no reference, so that it does not pin the VM. It is only ever read with get_file_active(), which is safe because kvm_vm_release() clears it, i.e. before the struct file is freed.

This simplifies the code and removes all remaining externally exported symbols for KVM, paving the path for a second concurrent KVM module.

Quoted 6 lines

---
This is a spin-off for the arm-on-s390 series for fast-lane merging requested by sean[0]. It is based on patch 1 [1] of the v6 of the arm-on-s390 series but with some fixes for some issues pointed out by sashiko. The useless rcu protection of kvm->file is removed and the getting-the-file-handle process is streamlined.

Quoted 4 lines

We'll need a shared branch to merge this across two subsystems and the vfio-ap driver. Based on $Subject and LoC I can volunteer to provide that once we're settled. A couple minor issues below...

Thank you for this, would be great!

Quoted 16 lines
Quoted 16 lines
drivers/vfio/pci/vfio_pci_zdev.c +1 -0
index 0990fdb146b7..d3a110101353 100644
@@ -144,6 +144,7 @@ int vfio_pci_info_zdev_add_caps(struct vfio_pci_core_device *vdev,
 int vfio_pci_zdev_open_device(struct vfio_pci_core_device *vdev)
 {
 	struct zpci_dev *zdev = to_zpci(vdev->pdev);
+	struct kvm *kvm;
 
 	if (!zdev)
 		return -ENODEV;
@@ -151,8 +152,12 @@ int vfio_pci_zdev_open_device(struct vfio_pci_core_device *vdev)
 	if (!vdev->vdev.kvm)
 		return 0;
 
Quoted 12 lines

drivers/vfio/pci/vfio_pci_zdev.c int vfio_pci_zdev_open_device(struct vfio_pci_core_device *vdev) · line 160

Quoted 7 lines
drivers/vfio/pci/vfio_pci_zdev.c +5 -1
+	kvm = vdev->vdev.kvm->private_data;
+	if (!kvm)
+		return -ENOENT;
+
 	if (zpci_kvm_hook.kvm_register)
-		return zpci_kvm_hook.kvm_register(zdev, vdev->vdev.kvm);
+		return zpci_kvm_hook.kvm_register(zdev, kvm);

There are conflicts here with Farhan's 9f240376d034 ("s390/pci: Store PCI error information for passthrough devices"), we need to maintain the error exit funnel through stop mediation.

just sent a rebased v2 with that issue resolved.

Quoted 37 lines
Quoted 25 lines
drivers/vfio/pci/vfio_pci_zdev.c +0 -0
 	return -ENOENT;
 }
drivers/vfio/vfio.h +2 -2
index 7728bc99b63d..f76504d707e1 100644
@@ -23,7 +23,7 @@ struct vfio_device_file {
 	u8 access_granted;
 	u32 devid; /* only valid when iommufd is valid */
 	spinlock_t kvm_ref_lock; /* protect kvm field */
-	struct kvm *kvm;
+	struct file *kvm;
 	struct iommufd_ctx *iommufd; /* protected by struct vfio_device_set::lock */
 };
 
@@ -88,7 +88,7 @@ struct vfio_group {
 #endif
 	enum vfio_group_type		type;
 	struct mutex			group_lock;
-	struct kvm			*kvm;
+	struct file			*kvm;
 	struct file			*opened_file;
 	struct iommufd_ctx		*iommufd;
 	spinlock_t			kvm_ref_lock;

drivers/vfio/vfio.h void vfio_device_group_unuse_iommu(struct vfio_device *device); · line 113

Quoted 8 lines
drivers/vfio/vfio.h +1 -1
@@ -107,7 +107,7 @@ void vfio_device_group_unuse_iommu(struct vfio_device *device);
 void vfio_df_group_close(struct vfio_device_file *df);
 struct vfio_group *vfio_group_from_file(struct file *file);
 bool vfio_group_enforced_coherent(struct vfio_group *group);
-void vfio_group_set_kvm(struct vfio_group *group, struct kvm *kvm);
+void vfio_group_set_kvm(struct vfio_group *group, struct file *kvm);
 bool vfio_device_has_container(struct vfio_device *device);
 int __init vfio_group_init(void);
 void vfio_group_cleanup(void);

There's a stub in the !CONFIG_VFIO_GROUP set of declarations below this that isn't updated to the new prototype, build breaks. Thanks,

Quoted 1 line

Alex

Ah I missed that. fixed in v2.

Steffen