Re: [PATCH v5] KVM: riscv: Skip CSR restore if VCPU is reloaded on the same core

From: Andrew Jones

Date: Wed Feb 25 2026 - 15:26:50 EST


On Wed, Feb 25, 2026 at 11:14:02AM +0800, Jinyu Tang wrote:
> struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr;
> struct kvm_vcpu_config *cfg = &vcpu->arch.cfg;
>
> + /*
> + * If VCPU is being reloaded on the same physical CPU and no
> + * other KVM VCPU has run on this CPU since it was last put,
> + * we can skip the expensive CSR and HGATP writes.
> + *
> + * Note: If a new CSR is added to this fast-path skip block,
> + * make sure that 'csr_dirty' is set to true in any
> + * ioctl (e.g., KVM_SET_ONE_REG) that modifies it.
> + */
> + if (vcpu == __this_cpu_read(kvm_former_vcpu) &&
> + vcpu->arch.last_exit_cpu == cpu && !vcpu->arch.csr_dirty)

The most expensive check condition, __this_cpu_read(), should come last
in order to short-circuit it when either of the cheap checks fail.

> + goto csr_restore_done;
> +
> + vcpu->arch.csr_dirty = false;
> if (kvm_riscv_nacl_sync_csr_available()) {
> nsh = nacl_shmem();
> nacl_csr_write(nsh, CSR_VSSTATUS, csr->vsstatus);
> @@ -624,6 +642,7 @@ void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
>
> kvm_riscv_mmu_update_hgatp(vcpu);
>
> +csr_restore_done:
> kvm_riscv_vcpu_timer_restore(vcpu);
>
> kvm_riscv_vcpu_host_fp_save(&vcpu->arch.host_context);
> @@ -645,6 +664,8 @@ void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
> void *nsh;
> struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr;
>
> + __this_cpu_write(kvm_former_vcpu, vcpu);

This write can be skipped by the fast path since kvm_former_vcpu is
already set to vcpu.

Thanks,
drew