From: Jim Mattson <jmattson@xxxxxxxxxx> When the host modifies a vCPU's MP_STATE after the vCPU has started running, maintain the accuracy of guest aperfmperf tracking: 1. For transitions from !HALTED to HALTED, add any accumulated "background" TSC ticks to the guest_mperf checkpoint before stopping the counter. 2. For transitions from HALTED to !HALTED, record the current TSC in host_tsc to begin accumulating background cycles in guest_mperf. This ensures the guest MPERF counter properly reflects time spent in C0 vs C1 states, even when state transitions are initiated by the host rather than the guest. Signed-off-by: Jim Mattson <jmattson@xxxxxxxxxx> Reviewed-by: Mingwei Zhang <mizhang@xxxxxxxxxx> Signed-off-by: Mingwei Zhang <mizhang@xxxxxxxxxx> --- arch/x86/kvm/x86.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 7c22bda3b1f7b..cd1f1ae86f83f 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -11904,6 +11904,18 @@ int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu, mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED)) goto out; + if (kvm_vcpu_has_run(vcpu) && + guest_can_use(vcpu, X86_FEATURE_APERFMPERF)) { + if (mp_state->mp_state == KVM_MP_STATE_HALTED && + vcpu->arch.mp_state != KVM_MP_STATE_HALTED) { + kvm_accumulate_background_guest_mperf(vcpu); + vcpu->arch.aperfmperf.loaded_while_running = false; + } else if (mp_state->mp_state != KVM_MP_STATE_HALTED && + vcpu->arch.mp_state == KVM_MP_STATE_HALTED) { + vcpu->arch.aperfmperf.host_tsc = rdtsc(); + } + } + if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) { vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED; set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events); -- 2.47.0.371.ga323438b13-goog