[PATCH v3 1/4] KVM: Add per vCPU flag specifying that a vCPU is loaded
From: Maxim Levitsky
Date: Mon Oct 02 2023 - 07:58:43 EST
Add vcpu->loaded boolean flag specifying that a vCPU is loaded.
Such flag can be useful in a vendor code (e.g AVIC) to make
decisions based on it.
Signed-off-by: Maxim Levitsky <mlevitsk@xxxxxxxxxx>
---
include/linux/kvm_host.h | 1 +
virt/kvm/kvm_main.c | 10 ++++++++++
2 files changed, 11 insertions(+)
diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h
index fb6c6109fdcad69..331432d86e44d51 100644
--- a/include/linux/kvm_host.h
+++ b/include/linux/kvm_host.h
@@ -379,6 +379,7 @@ struct kvm_vcpu {
#endif
bool preempted;
bool ready;
+ bool loaded;
struct kvm_vcpu_arch arch;
struct kvm_vcpu_stat stat;
char stats_id[KVM_STATS_NAME_SIZE];
diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c
index 486800a7024b373..615f2a02b7cb97f 100644
--- a/virt/kvm/kvm_main.c
+++ b/virt/kvm/kvm_main.c
@@ -214,6 +214,10 @@ void vcpu_load(struct kvm_vcpu *vcpu)
__this_cpu_write(kvm_running_vcpu, vcpu);
preempt_notifier_register(&vcpu->preempt_notifier);
kvm_arch_vcpu_load(vcpu, cpu);
+
+ /* Ensure that vcpu->cpu is visible before vcpu->loaded is set to true */
+ smp_wmb();
+ WRITE_ONCE(vcpu->loaded, true);
put_cpu();
}
EXPORT_SYMBOL_GPL(vcpu_load);
@@ -221,6 +225,12 @@ EXPORT_SYMBOL_GPL(vcpu_load);
void vcpu_put(struct kvm_vcpu *vcpu)
{
preempt_disable();
+ WRITE_ONCE(vcpu->loaded, false);
+ /*
+ * Ensure that vcpu->loaded is set and visible,
+ * before KVM actually unloads the vCPU.
+ */
+ smp_wmb();
kvm_arch_vcpu_put(vcpu);
preempt_notifier_unregister(&vcpu->preempt_notifier);
__this_cpu_write(kvm_running_vcpu, NULL);
--
2.26.3