Re: [RFC PATCH v3 07/21] KVM: x86: Add KVM_VCPU_TSC_SCALE and fix the documentation on TSC migration

From: Sean Christopherson
Date: Tue Aug 13 2024 - 21:53:06 EST


On Wed, May 22, 2024, David Woodhouse wrote:
> diff --git a/arch/x86/include/uapi/asm/kvm.h b/arch/x86/include/uapi/asm/kvm.h
> index 72ad5ace118d..fe7c98907818 100644
> --- a/arch/x86/include/uapi/asm/kvm.h
> +++ b/arch/x86/include/uapi/asm/kvm.h
> @@ -864,6 +864,12 @@ struct kvm_hyperv_eventfd {
> /* for KVM_{GET,SET,HAS}_DEVICE_ATTR */
> #define KVM_VCPU_TSC_CTRL 0 /* control group for the timestamp counter (TSC) */
> #define KVM_VCPU_TSC_OFFSET 0 /* attribute for the TSC offset */
> +#define KVM_VCPU_TSC_SCALE 1 /* attribute for TSC scaling factor */
> +
> +struct kvm_vcpu_tsc_scale {
> + __u64 tsc_ratio;
> + __u64 tsc_frac_bits;
> +};
>
> /* x86-specific KVM_EXIT_HYPERCALL flags. */
> #define KVM_EXIT_HYPERCALL_LONG_MODE _BITULL(0)
> diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
> index 42abce7b4fc9..00a7c1188dec 100644
> --- a/arch/x86/kvm/x86.c
> +++ b/arch/x86/kvm/x86.c
> @@ -5715,6 +5715,7 @@ static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
>
> switch (attr->attr) {
> case KVM_VCPU_TSC_OFFSET:
> + case KVM_VCPU_TSC_SCALE:
> r = 0;
> break;
> default:
> @@ -5737,6 +5738,17 @@ static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
> break;
> r = 0;
> break;
> + case KVM_VCPU_TSC_SCALE: {
> + struct kvm_vcpu_tsc_scale scale;
> +
> + scale.tsc_ratio = vcpu->arch.l1_tsc_scaling_ratio;

I'm pretty sure vcpu->arch.l1_tsc_scaling_ratio is set to the correct value only
if the vCPU is using KVM's default frequency, or TSC scaling is supported in
hardware.

/* TSC scaling supported? */
if (!kvm_caps.has_tsc_control) {
if (user_tsc_khz > tsc_khz) {
vcpu->arch.tsc_catchup = 1;
vcpu->arch.tsc_always_catchup = 1;
return 0;
} else {
pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
return -1;
}
}

I assume the easiest solution is to enumerate support for KVM_VCPU_TSC_SCALE if
and only if kvm_caps.has_tsc_control is true.

> + scale.tsc_frac_bits = kvm_caps.tsc_scaling_ratio_frac_bits;
> + r = -EFAULT;
> + if (copy_to_user(uaddr, &scale, sizeof(scale)))
> + break;
> + r = 0;
> + break;
> + }
> default:
> r = -ENXIO;
> }