Re: [PATCH 1/3] VFIO: take reference to the KVM module

Sean Christopherson
2026-04-10T15:45:03Z

On Fri, Apr 10, 2026, Paolo Bonzini wrote:
> On Fri, Apr 10, 2026 at 4:13 PM Sean Christopherson <seanjc@google.com> wrote:
> >
> > +Dan
> > > We could get rid of the reference count completely (get_file() as a
> > > replacement for kvm_get_kvm(), get_file_active() as a replacement for
> > > kvm_get_kvm_safe()). struct kvm would need to add a back pointer from
> > > struct kvm to struct file,
> >
> > I wasn't thinking of dropping kvm_get_kvm() entirely, rather just not exporting
> > it. Forcing internal KVM usage to grab a reference to the file doesn't add a
> > whole lot value.
>
> It adds not doing things in two different ways. The kvm_file is not
> always available (and if we need to add it, it should be added in
> struct kvm not struct kvm_device).

My thought was to deliberately avoid putting it in "kvm", because as you're
effectively pointing out, the file really shouldn't be passed around within KVM.

Aha! What if we bury it in kvm_vfio? As an acknowledgement that passing around
a kvm_file is only intended for cases where an external, non-KVM entity needs to
to propagate the VM reference.

diff --git a/virt/kvm/vfio.c b/virt/kvm/vfio.c
index 9f9acb66cc1e..2d9bce646136 100644
--- a/virt/kvm/vfio.c
+++ b/virt/kvm/vfio.c
@@ -30,14 +30,15 @@ struct kvm_vfio_file {
};

struct kvm_vfio {
+ struct file *kvm_file;
struct list_head file_list;
struct mutex lock;
bool noncoherent;
};

-static void kvm_vfio_file_set_kvm(struct file *file, struct kvm *kvm)
+static void kvm_vfio_file_set_kvm(struct file *file, struct file *kvm)
{
- void (*fn)(struct file *file, struct kvm *kvm);
+ void (*fn)(struct file *file, struct file *kvm);

fn = symbol_get(vfio_file_set_kvm);
if (!fn)
@@ -175,7 +176,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, kv->kvm_file);
kvm_vfio_update_coherency(dev);

out_unlock:
@@ -372,6 +373,7 @@ static int kvm_vfio_create(struct kvm_device *dev, u32 type)
mutex_init(&kv->lock);

dev->private = kv;
+ kv->kvm_file = file;

return 0;
}