[PATCH v3 3/4] LoongArch: KVM: Move host CSR_GSTAT save and restore in context switch

From: Bibo Mao

Date: Sun Mar 22 2026 - 22:59:27 EST


CSR register CSR_GSTAT stores guest VMID information. With existing
implementation method, VMID is per vCPU similar with ASID on kernel.
Register CSR_GSTAT is written at VM entry even if VMID is not changed.

Here move CSR_GSTAT save/restore in vCPU context switch, and update
register CSR_GSTAT only when VMID is updated at VM entry. At most time
VM enter/exit is much more frequent than vCPU thread context switch.

Signed-off-by: Bibo Mao <maobibo@xxxxxxxxxxx>
---
arch/loongarch/kvm/main.c | 8 ++++----
arch/loongarch/kvm/vcpu.c | 2 ++
2 files changed, 6 insertions(+), 4 deletions(-)

diff --git a/arch/loongarch/kvm/main.c b/arch/loongarch/kvm/main.c
index 2c593ac7892f..304c83863e71 100644
--- a/arch/loongarch/kvm/main.c
+++ b/arch/loongarch/kvm/main.c
@@ -271,11 +271,11 @@ void kvm_check_vpid(struct kvm_vcpu *vcpu)
* memory with new address is changed on other VCPUs.
*/
set_gcsr_llbctl(CSR_LLBCTL_WCLLB);
- }

- /* Restore GSTAT(0x50).vpid */
- vpid = (vcpu->arch.vpid & vpid_mask) << CSR_GSTAT_GID_SHIFT;
- change_csr_gstat(vpid_mask << CSR_GSTAT_GID_SHIFT, vpid);
+ /* Restore GSTAT(0x50).vpid */
+ vpid = (vcpu->arch.vpid & vpid_mask) << CSR_GSTAT_GID_SHIFT;
+ change_csr_gstat(vpid_mask << CSR_GSTAT_GID_SHIFT, vpid);
+ }
}

void kvm_init_vmcs(struct kvm *kvm)
diff --git a/arch/loongarch/kvm/vcpu.c b/arch/loongarch/kvm/vcpu.c
index e82b2c84ce17..8810fcd7e26e 100644
--- a/arch/loongarch/kvm/vcpu.c
+++ b/arch/loongarch/kvm/vcpu.c
@@ -1695,6 +1695,7 @@ static int _kvm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)

/* Restore Root.GINTC from unused Guest.GINTC register */
write_csr_gintc(csr->csrs[LOONGARCH_CSR_GINTC]);
+ write_csr_gstat(csr->csrs[LOONGARCH_CSR_GSTAT]);

/*
* We should clear linked load bit to break interrupted atomics. This
@@ -1790,6 +1791,7 @@ static int _kvm_vcpu_put(struct kvm_vcpu *vcpu, int cpu)
kvm_save_hw_gcsr(csr, LOONGARCH_CSR_ISR3);
}

+ csr->csrs[LOONGARCH_CSR_GSTAT] = read_csr_gstat();
vcpu->arch.aux_inuse |= KVM_LARCH_SWCSR_LATEST;

out:
--
2.39.3