Skip to content

Commit 5f6de5c

Browse files
dmatlackbonzini
authored andcommitted
KVM: Prevent module exit until all VMs are freed
Tie the lifetime the KVM module to the lifetime of each VM via kvm.users_count. This way anything that grabs a reference to the VM via kvm_get_kvm() cannot accidentally outlive the KVM module. Prior to this commit, the lifetime of the KVM module was tied to the lifetime of /dev/kvm file descriptors, VM file descriptors, and vCPU file descriptors by their respective file_operations "owner" field. This approach is insufficient because references grabbed via kvm_get_kvm() do not prevent closing any of the aforementioned file descriptors. This fixes a long standing theoretical bug in KVM that at least affects async page faults. kvm_setup_async_pf() grabs a reference via kvm_get_kvm(), and drops it in an asynchronous work callback. Nothing prevents the VM file descriptor from being closed and the KVM module from being unloaded before this callback runs. Fixes: af585b9 ("KVM: Halt vcpu if page it tries to access is swapped out") Fixes: 3d3aab1 ("KVM: set owner of cpu and vm file operations") Cc: stable@vger.kernel.org Suggested-by: Ben Gardon <bgardon@google.com> [ Based on a patch from Ben implemented for Google's kernel. ] Signed-off-by: David Matlack <dmatlack@google.com> Message-Id: <20220303183328.1499189-2-dmatlack@google.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
1 parent c9b8fec commit 5f6de5c

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

virt/kvm/kvm_main.c

+13
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,8 @@ EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
117117

118118
static const struct file_operations stat_fops_per_vm;
119119

120+
static struct file_operations kvm_chardev_ops;
121+
120122
static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
121123
unsigned long arg);
122124
#ifdef CONFIG_KVM_COMPAT
@@ -1131,6 +1133,16 @@ static struct kvm *kvm_create_vm(unsigned long type)
11311133
preempt_notifier_inc();
11321134
kvm_init_pm_notifier(kvm);
11331135

1136+
/*
1137+
* When the fd passed to this ioctl() is opened it pins the module,
1138+
* but try_module_get() also prevents getting a reference if the module
1139+
* is in MODULE_STATE_GOING (e.g. if someone ran "rmmod --wait").
1140+
*/
1141+
if (!try_module_get(kvm_chardev_ops.owner)) {
1142+
r = -ENODEV;
1143+
goto out_err;
1144+
}
1145+
11341146
return kvm;
11351147

11361148
out_err:
@@ -1220,6 +1232,7 @@ static void kvm_destroy_vm(struct kvm *kvm)
12201232
preempt_notifier_dec();
12211233
hardware_disable_all();
12221234
mmdrop(mm);
1235+
module_put(kvm_chardev_ops.owner);
12231236
}
12241237

12251238
void kvm_get_kvm(struct kvm *kvm)

0 commit comments

Comments
 (0)