[PATCH 3/4] KVM: introduce memory transaction semaphore

Emanuele Giuseppe Esposito
2022-10-22T15:48:37Z

Right now the semaphore is only used to signal that a vcpu
entered KVM_RUN (not necessarly in guest mode, could be also
blocked/halted).
Later it will be used by specific ioctls (writers) to wait that
all vcpus (readers) exit from KVM_RUN.

Signed-off-by: Emanuele Giuseppe Esposito <eesposit@redhat.com>
---
virt/kvm/kvm_main.c | 14 ++++++++++++++
1 file changed, 14 insertions(+)

diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c
index c080b93edc0d..ae0240928a4a 100644
--- a/virt/kvm/kvm_main.c
+++ b/virt/kvm/kvm_main.c
@@ -119,6 +119,8 @@ static const struct file_operations stat_fops_per_vm;

static struct file_operations kvm_chardev_ops;

+static DECLARE_RWSEM(memory_transaction);
+
static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
unsigned long arg);
#ifdef CONFIG_KVM_COMPAT
@@ -4074,7 +4076,19 @@ static long kvm_vcpu_ioctl(struct file *filp,
synchronize_rcu();
put_pid(oldpid);
}
+ /*
+ * Notify that a vcpu wants to run, and thus could be reading
+ * memslots.
+ * If KVM_KICK_ALL_RUNNING_VCPUS runs afterwards, it will have
+ * to wait that KVM_RUN exited and up_read() is called.
+ * If KVM_KICK_ALL_RUNNING_VCPUS already returned but
+ * KVM_RESUME_ALL_KICKED_VCPUS didn't start yet, then there
+ * is a request pending for the vcpu that will cause it to
+ * exit KVM_RUN.
+ */
+ down_read(&memory_transaction);
r = kvm_arch_vcpu_ioctl_run(vcpu);
+ up_read(&memory_transaction);
trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
break;
}
--
2.31.1