x86: Try to wrangle PV clocks vs. TSC
Subsystems (15)
Sean Christopherson
maintainerv6 cover x86: Try to wrangle PV clocks vs. TSC
The primary goal of this series to fix flaws with SNP and TDX guests where a PV clock provided by the untrusted hypervisor is used instead of the secure TSC that is controlled by trusted firmware.
The secondary goal is modernize running under KVM. Currently, KVM guests will use TSC for clocksource, but not sched_clock. And Linux-as-a-KVM-guest doesn't support paravirt enumeration of the TSC/APIC frequencies, even though QEMU provides that information by default.
The tertiary goal is to clean up the PV clock code to deduplicate logic across hypervisors, and to hopefully make it all easier to maintain going forward.
The quaternary goal is to clean up the TSC calibration code, which was made stupidly hard to follow by hypervisor code mixing in with the native calibration routines, instead of being implemented as a pure alternative.
Note, the VMware and Xen changes still probably should get acks from those maintainers, as my understanding of what they're trying to do may be flawed.
Lots more background on the SNP/TDX motiviation:
https://lore.kernel.org/all/[email protected]
As before, I deliberately omitted [email protected] from the To/Cc, as those emails bounced on v1, AFAICT nothing has changed.
v5:
- Use cpu_feature_enabled() instead of boot_cpu_has(). [Boris]
- WARN if recalibrate_cpu_khz() runs on a system with TSC_KNOWN_FREQ. [Thomas]
- Opportunistically drop a line break in native_calibrate_tsc(). [Thomas]
- Rely on callers of cpuid_get_tsc_info() to check the result instead of unnecessarily zeroing the structure. [Boris]
- Ignore tsc_early_khz if the TSC frequency is provided by trusted firmware or by the hypervisor. [Thomas, Sashiko]
- Cache CPUID output in acrn_init_platform() to avoid introducing a transient bug where TSC_KNOWN_FREQ could be set even if the ACRN hypervisor didn't actually provide the frequency. [Sashiko]
- Drop kvmclock's useless/dead check_tsc_unstable() call (it occurs before the command line parameter is parsed). [Sashiko]
- Add helpers to set lapic_timer_period, to fix not-so-theoretical overflow in the various "khz * 1000 / HZ" patterns. [Sashiko]
- Drop the "x86/xen: Obtain TSC frequency from CPUID if present" patch as it doesn't have any dependencies/conflicts on/with this series, and Sashiko had concerns about the assumptions it was making. [Sashiko]
- Collect reviews. [David] (Kirill's got dropped because the patch he reviewed got completely rewritten).
v4:
- Use x86_init_noop() to skip save/restore on VMware and Xen instead of nullifying x86_platform.{save,restore}_sched_clock_state. [Sashiko]
- Use '0' to indicate "failure" when getting the CPU frequency from CPUID, to avoid using an out-param and thus make it all but impossible to unintentionally clobber the global cpu_khz (which v3 did). [Sashiko]
- Rename cpuid_get_cpu_freq() => __cpu_khz_from_cpuid() to capture its relationship with cpu_khz_from_cpuid().
- Compute lapic_timer_period in units of ticks, not Khz. [Sashiko]
- Kill off x86_platform_ops.calibrate_{cpu,tsc}(), and instead use dedicated hooks for hypervisor code, and direct calls for TDX and SNP. [David, loosely]
- Drop SNP's secure TSC override of _CPU_ calibration, as there's zero evidence it's justified or a net positive.
- Collect reviews/acks. [David, Wei]
- Decouple getting TSC/APIC frequencies from KVM PV CPUID from kvmclock. [David]
- Fix an amusing number of Opportunistically misspellings. [David]
- Set kvm_sched_clock_offset _before_ registering kvmclock as sched_clock, and add a comment to guard against future goofs. [Sashiko]
- Keep "setup_force_cpu_cap(X86_FEATURE_TSC_RELIABLE)" in Hyper-V's handling of HV_ACCESS_TSC_INVARIANT, as it's technically possible to have a VM with HV_ACCESS_TSC_INVARIANT but not HV_ACCESS_FREQUENCY_MSRS. Though as a _very_ nice side effect of using dedicated sequencing for selecting the TSC frequency source, this would have naturally happened anyways. [Sashiko]
v3:
- https://lore.kernel.org/all/[email protected]
- Collect reviews. [Michael, Thomas]
- Use Hyper-V reference counter / refcounter instead of Hyper-V timer. [Michael]
- Use the paravirt CPUID interface first proposed by VMware for KVM's "official" mechanism for communicating frequency to KVM-aware guests, instead of abusing Intel's CPUID leafs. [David]
- Deal with paravirt code being moved into asm/timers.h and arch/x86/kernel/tsc.c.
v2:
- https://lore.kernel.org/all/[email protected]
- Add struct to hold the TSC CPUID output. [Boris]
- Don't pointlessly inline the TSC CPUID helpers. [Boris]
- Fix a variable goof in a helper, hopefully for real this time. [Dan]
- Collect reviews. [Nikunj]
- Override the sched_clock save/restore hooks if and only if a PV clock is successfully registered.
- During resome, restore clocksources before reading persistent time.
- Clean up more warts created by kvmclock.
- Fix more bugs in kvmclock's suspend/resume handling.
- Try to harden kvmclock against future bugs.
v1: https://lore.kernel.org/all/[email protected]
David Woodhouse (2):
KVM: x86: Officially define CPUID 0x40000010 as PV Timing Info (TSC
and Bus)
x86/kvm: Obtain TSC frequency from PV CPUID if present
Sean Christopherson (49):
x86/apic: Provide helpers to set local APIC timer frequency in hz and
khz
x86/apic: Add CONFIG_X86_LOCAL_APIC=n stubs for APIC timer frequency
APIs
x86/tsc: Ensure that TSC recalibration doesn't run if TSC frequency is
known
x86/tsc: Restrict recalibrate_cpu_khz() export to p4-clockmod and
powernow-k7
x86/sev: Mark TSC as reliable when configuring Secure TSC x86/sev: Don't override CPU frequency calibration for SNP's Secure TSC x86/sev: Move check for SNP Secure TSC support to tsc_early_init() x86/sev: Shove SNP's secure/trusted TSC frequency directly into
"calibration"
x86/tsc: Add a standalone helper for getting TSC info from CPUID.0x15 x86/tdx: Force TSC frequency with CPUID-based info provided by the
TDX-Module
x86/tsc: Add dedicated hypervisor hooks for getting known TSC/CPU
frequencies
x86/acrn: Register TSC/CPU frequency callbacks iff frequency is
actually in CPUID
x86/acrn: Mark TSC frequency as known when using ACRN for calibration x86/tsc: Consolidate forcing of X86_FEATURE_TSC_KNOWN_FREQ for PV code x86/tsc: Kill off x86_platform_ops.calibrate_{cpu,tsc}() hooks x86/tsc: Rename pit_hpet_ptimer_calibrate_cpu() =>
native_calibrate_cpu_late()
x86/tsc: Fold native_calibrate_cpu() into recalibrate_cpu_khz() x86/kvmclock: Rename kvm_get_tsc_khz() to kvmclock_get_tsc_khz() x86/kvmclock: Drop dead check on TSC being unstable during
kvmclock_init()
x86/kvm: Mark TSC as reliable when it's constant and nonstop x86/tsc: Add standalone helper for getting CPU frequency from CPUID x86/kvm: Get CPU base frequency from CPUID when it's available
clocksource: hyper-v: Register sched_clock save/restore iff it's
necessary
clocksource: hyper-v: Drop wrappers to sched_clock save/restore
helpers
clocksource: hyper-v: Don't save/restore TSC offset when using HV
sched_clock
x86/kvmclock: Setup kvmclock for secondary CPUs iff CONFIG_SMP=y x86/kvm: Don't disable kvmclock on BSP in syscore_suspend() x86/paravirt: Remove unnecessary PARAVIRT=n stub for
paravirt_set_sched_clock()
x86/paravirt: Move handling of unstable PV clocks into
paravirt_set_sched_clock()
x86/kvmclock: Move sched_clock save/restore helpers up in kvmclock.c x86/xen/time: NOP-ify x86_platform's sched_clock save/restore hooks x86/vmware: NOP-ify save/restore hooks when using VMware's sched_clock x86/tsc: WARN if TSC sched_clock save/restore used with PV sched_clock x86/paravirt: Pass sched_clock save/restore helpers during
registration
x86/kvmclock: Move kvm_sched_clock_init() down in kvmclock.c x86/xen/time: Mark xen_setup_vsyscall_time_info() as __init x86/pvclock: Mark setup helpers and related various as
__init/__ro_after_init
x86/pvclock: WARN if pvclock's valid_flags are overwritten x86/kvmclock: Refactor handling of PVCLOCK_TSC_STABLE_BIT during
kvmclock_init()
timekeeping: Resume clocksources before reading persistent clock x86/kvmclock: Hook clocksource.suspend/resume when kvmclock isn't
sched_clock
x86/kvmclock: WARN if wall clock is read while kvmclock is suspended x86/paravirt: Mark __paravirt_set_sched_clock() as __init x86/paravirt: Plumb a return code into __paravirt_set_sched_clock() x86/paravirt: Don't use a PV sched_clock in CoCo guests with trusted
TSC
x86/kvmclock: Use TSC for sched_clock if it's constant and non-stop x86/kvmclock: Plumb in AP-online and BSP-resume to kvmlock, for
documentation
x86/paravirt: Move using_native_sched_clock() stub into timer.h x86/kvm: Get local APIC bus frequency from PV CPUID Timing Info
.../admin-guide/kernel-parameters.txt | 5 + Documentation/virt/kvm/x86/cpuid.rst | 12 + arch/x86/coco/sev/core.c | 21 +- arch/x86/coco/tdx/tdx.c | 19 +- arch/x86/include/asm/acrn.h | 5 - arch/x86/include/asm/apic.h | 5 +- arch/x86/include/asm/kvm_para.h | 12 +- arch/x86/include/asm/sev.h | 4 +- arch/x86/include/asm/tdx.h | 2 + arch/x86/include/asm/timer.h | 15 +- arch/x86/include/asm/tsc.h | 10 +- arch/x86/include/asm/x86_init.h | 8 +- arch/x86/include/uapi/asm/kvm_para.h | 11 + arch/x86/kernel/apic/apic.c | 19 +- arch/x86/kernel/cpu/acrn.c | 14 +- arch/x86/kernel/cpu/mshyperv.c | 70 +----- arch/x86/kernel/cpu/vmware.c | 19 +- arch/x86/kernel/jailhouse.c | 9 +- arch/x86/kernel/kvm.c | 101 ++++++-- arch/x86/kernel/kvmclock.c | 208 +++++++++++------ arch/x86/kernel/pvclock.c | 9 +- arch/x86/kernel/tsc.c | 218 +++++++++++------- arch/x86/kernel/tsc_msr.c | 4 +- arch/x86/kernel/x86_init.c | 2 - arch/x86/mm/mem_encrypt_amd.c | 3 - arch/x86/xen/time.c | 14 +- drivers/clocksource/hyperv_timer.c | 38 ++- include/clocksource/hyperv_timer.h | 2 - kernel/time/timekeeping.c | 9 +- 29 files changed, 547 insertions(+), 321 deletions(-)
base-commit: 6949feed6e32823a6628873000602988a4cafe06
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 1/51 x86/apic: Provide helpers to set local APIC timer frequency in hz and khz
Add and use APIs to set the local APIC timer period (given a frequency) instead of open coding the subtle HZ math in all external callers, and make lapic_timer_period local to apic.c. Provide APIs to specify the frequency in both hertz and kilohertz so that Hyper-V and VMware code aren't forced to lose precision.
Opportunistically take the frequency as a u64 to harden against the possibility that the frequency (in Khz) is greater than 4294967, i.e. if the APIC timer runs at ~4.29 GHz. As pointed out by Sashiko, 4294968 * 1000 == 0x1_000002c0, and thus a Khz period of 4294968 would silently overflow the 32-bit unsigned integer used by most callers.
Print out who set the period to maintain equivalent Hyper-V and VMware functionality, and in general to make it easier to triage/debug issues.
--- arch/x86/include/asm/apic.h | 3 ++- arch/x86/kernel/apic/apic.c | 19 ++++++++++++++++++- arch/x86/kernel/cpu/mshyperv.c | 5 +---- arch/x86/kernel/cpu/vmware.c | 4 +--- arch/x86/kernel/jailhouse.c | 2 +- arch/x86/kernel/tsc.c | 2 +- arch/x86/kernel/tsc_msr.c | 2 +- 7 files changed, 25 insertions(+), 12 deletions(-)
arch/x86/include/asm/apic.h +2 -1
@@ -63,7 +63,6 @@ extern int apic_verbosity;extern int local_apic_timer_c2_ok;extern bool apic_is_disabled; -extern unsigned int lapic_timer_period;extern enum apic_intr_mode_id apic_intr_mode;enum apic_intr_mode_id {
@@ -138,6 +137,8 @@ void register_lapic_address(unsigned long address);extern void setup_boot_APIC_clock (void );extern void setup_secondary_APIC_clock (void );extern void lapic_update_tsc_freq (void ); +extern void apic_set_timer_frequency_hz (u64 freq_hz,const char *source); +extern void apic_set_timer_frequency_khz (u64 freq_khz,const char *source);#ifdef CONFIG_X86_64 static inline bool apic_force_enable (unsigned long addr)
arch/x86/kernel/apic/apic.c +18 -1
@@ -37,6 +37,7 @@#include <linux/smp.h> #include <linux/mm.h> #include <linux/kvm_types.h> +#include <linux/units.h> #include <xen/xen.h>
@@ -176,7 +177,7 @@ static struct resource lapic_resource = { };/* Measured in ticks per HZ. */ -unsigned int lapic_timer_period =0 ; +static unsigned int lapic_timer_period;static void apic_pm_activate (void );
@@ -796,6 +797,22 @@ bool __init apic_needs_pit(void)return lapic_timer_period ==0 ; } +void apic_set_timer_frequency_hz (u64 freq_hz,const char *source) +{ +u32 f_remainder; +u64 f_khz =div_u64_rem (freq_hz,HZ_PER_KHZ , &f_remainder); + + lapic_timer_period =div_u64 (freq_hz,HZ ); + +pr_info ("Local APIC Timer Frequency set to %llu.%03u KHz (from '%s').\n" , + f_khz, f_remainder, source); +} + +void apic_set_timer_frequency_khz (u64 freq_khz,const char *source) +{ +apic_set_timer_frequency_hz (freq_khz *HZ_PER_KHZ , source); +} +static int __init calibrate_APIC_clock (void ) {struct clock_event_device *levt =this_cpu_ptr (&lapic_events);
arch/x86/kernel/cpu/mshyperv.c +1 -4
@@ -646,10 +646,7 @@ static void __init ms_hyperv_init_platform(void)u64 hv_lapic_frequency;rdmsrq (HV_X64_MSR_APIC_FREQUENCY , hv_lapic_frequency); - hv_lapic_frequency =div_u64 (hv_lapic_frequency,HZ ); - lapic_timer_period = hv_lapic_frequency; -pr_info ("Hyper-V: LAPIC Timer Frequency: %#x\n" , - lapic_timer_period); +apic_set_timer_frequency_hz (hv_lapic_frequency,"Hyper-V hypervisor" ); } register_nmi_handler(NMI_UNKNOWN, hv_nmi_unknown, NMI_FLAG_FIRST,
arch/x86/kernel/cpu/vmware.c +1 -3
@@ -424,9 +424,7 @@ static void __init vmware_platform_setup(void)#ifdef CONFIG_X86_LOCAL_APIC /* Skip lapic calibration since we know the bus frequency. */ - lapic_timer_period = ecx /HZ ; -pr_info ("Host bus clock speed read from hypervisor : %u Hz\n" , - ecx); +apic_set_timer_frequency_hz (ecx,"VMware hypervisor" );#endif }else {pr_warn ("Failed to get TSC freq from the hypervisor\n" );
arch/x86/kernel/jailhouse.c +1 -1
@@ -65,7 +65,7 @@ static void jailhouse_get_wallclock(struct timespec64 *now)static void __init jailhouse_timer_init (void ) { - lapic_timer_period = setup_data.v1.apic_khz * (1000 /HZ ); +apic_set_timer_frequency_khz (setup_data.v1.apic_khz,"Jailhouse hypervisor" ); }static unsigned long jailhouse_get_tsc (void )
arch/x86/kernel/tsc.c +1 -1
@@ -717,7 +717,7 @@ unsigned long native_calibrate_tsc(void)* lapic_timer_period here to avoid having to calibrate the APIC * timer later. */ - lapic_timer_period = crystal_khz *1000 /HZ ; +apic_set_timer_frequency_khz (crystal_khz,"CPUID 0x15/0x16" );#endif return crystal_khz * ebx_numerator / eax_denominator;
arch/x86/kernel/tsc_msr.c +1 -1
@@ -212,7 +212,7 @@ unsigned long cpu_khz_from_msr(void)pr_err ("Error MSR_FSB_FREQ index %d is unknown\n" , index);#ifdef CONFIG_X86_LOCAL_APIC - lapic_timer_period = (freq *1000 ) /HZ ; +apic_set_timer_frequency_khz (freq,"MSR_FSB_FREQ" );#endif /*
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Re: [PATCH v6 01/51] x86/apic: Provide helpers to set local APIC timer frequency in hz and khz
Quoted 12 lines · Sean Christopherson
Add and use APIs to set the local APIC timer period (given a frequency) instead of open coding the subtle HZ math in all external callers, and make
lapic_timer_periodlocal toapic.c. Provide APIs to specify the frequency in both hertz and kilohertz so that Hyper-V and VMware code aren't forced to lose precision.Opportunistically take the frequency as a u64 to harden against the possibility that the frequency (in Khz) is greater than 4294967, i.e. if the APIC timer runs at ~4.29 GHz. As pointed out by Sashiko, 4294968 * 1000 == 0x1_000002c0, and thus a Khz period of 4294968 would silently overflow the 32-bit unsigned integer used by most callers.
Quoted 5 lines
Print out who set the period to maintain equivalent Hyper-V and VMware functionality, and in general to make it easier to triage/debug issues.
Cc Michael Kelley <[email protected]>Signed-off-by Sean Christopherson <[email protected]>
Sean Christopherson
maintainerPATCH v6 2/51 x86/apic: Add CONFIG_X86_LOCAL_APIC=n stubs for APIC timer frequency APIs
In reply to Sean ChristophersonAdd stubs for the apic_set_timer_frequency_{,k}hz() APIs when the kernel is built without support for a local APIC, and drop #ifdefs in callers that don't need to check CONFIG_X86_LOCAL_APIC for other reasons.
No functional change intended.
--- arch/x86/include/asm/apic.h | 2 ++ arch/x86/kernel/cpu/vmware.c | 2 -- arch/x86/kernel/tsc.c | 2 -- arch/x86/kernel/tsc_msr.c | 2 -- 4 files changed, 2 insertions(+), 6 deletions(-)
arch/x86/include/asm/apic.h +2 -0
@@ -189,6 +189,8 @@ static inline void disable_local_APIC(void) { }# define setup_boot_APIC_clock x86_init_noop# define setup_secondary_APIC_clock x86_init_noopstatic inline void lapic_update_tsc_freq (void ) { } +static inline void apic_set_timer_frequency_hz (u64 freq_hz,const char *source) { } +static inline void apic_set_timer_frequency_khz (u64 freq_khz,const char *source) { }static inline void init_bsp_APIC (void ) { }static inline void apic_intr_mode_select (void ) { }static inline void apic_intr_mode_init (void ) { }
arch/x86/kernel/cpu/vmware.c +0 -2
@@ -422,10 +422,8 @@ static void __init vmware_platform_setup(void) x86_platform.calibrate_tsc = vmware_get_tsc_khz; x86_platform.calibrate_cpu = vmware_get_tsc_khz; -#ifdef CONFIG_X86_LOCAL_APIC /* Skip lapic calibration since we know the bus frequency. */ apic_set_timer_frequency_hz (ecx,"VMware hypervisor" ); -#endif }else {pr_warn ("Failed to get TSC freq from the hypervisor\n" ); }
arch/x86/kernel/tsc.c +0 -2
@@ -710,7 +710,6 @@ unsigned long native_calibrate_tsc(void)if (boot_cpu_data.x86_vfm ==INTEL_ATOM_GOLDMONT )setup_force_cpu_cap (X86_FEATURE_TSC_RELIABLE ); -#ifdef CONFIG_X86_LOCAL_APIC /* * The local APIC appears to be fed by the core crystal clock * (which sounds entirely sensible). We can set the global
@@ -718,7 +717,6 @@ unsigned long native_calibrate_tsc(void)* timer later. */ apic_set_timer_frequency_khz (crystal_khz,"CPUID 0x15/0x16" ); -#endif return crystal_khz * ebx_numerator / eax_denominator; }
arch/x86/kernel/tsc_msr.c +0 -2
@@ -211,9 +211,7 @@ unsigned long cpu_khz_from_msr(void)if (freq ==0 )pr_err ("Error MSR_FSB_FREQ index %d is unknown\n" , index); -#ifdef CONFIG_X86_LOCAL_APIC apic_set_timer_frequency_khz (freq,"MSR_FSB_FREQ" ); -#endif /* * TSC frequency determined by MSR is always considered "known"
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Re: [PATCH v6 02/51] x86/apic: Add CONFIG_X86_LOCAL_APIC=n stubs for APIC timer frequency APIs
Quoted 7 lines · Sean Christopherson
Add stubs for the apic_set_timer_frequency_{,k}hz() APIs when the kernel is built without support for a local APIC, and drop #ifdefs in callers that don't need to check
CONFIG_X86_LOCAL_APICfor other reasons.No functional change intended.
Signed-off-by Sean Christopherson <[email protected]>
Sean Christopherson
maintainerPATCH v6 3/51 x86/tsc: Ensure that TSC recalibration doesn't run if TSC frequency is known
In reply to Sean ChristophersonWhen attempting TSC recalibration post-boot, which is only done for ancient CPUS (P4 and K7) on SMP=n kernels, assert that the TSC frequency isn't known (explicitly provided by hardware) by way of MSR or CPUID, and bail if the impossible happens. In practice, recalibration and TSC_KNOWN_FREQ are mutually exclusive, as TSC_KNOWN_FREQ will only be set when running on hardware that was released decades after recalibration was obsoleted, but but it's hard to see that, especially when looking at just the TSC code.
Note, the WARN can likely be tripped by running in a virtual machine and concocting an impossible CPU model, e.g. by combining a P4 signature with CPUID 0x15. This is working as intended, as such a virtual CPU model is wildly out-of-spec and is not supported.
--- arch/x86/kernel/tsc.c | 3 +++ 1 file changed, 3 insertions(+)
arch/x86/kernel/tsc.c +3 -0
@@ -930,6 +930,9 @@ void recalibrate_cpu_khz(void)if (!boot_cpu_has (X86_FEATURE_TSC ))return ; +if (WARN_ON_ONCE (cpu_feature_enabled (X86_FEATURE_TSC_KNOWN_FREQ ))) +return ; + cpu_khz = x86_platform.calibrate_cpu (); tsc_khz = x86_platform.calibrate_tsc ();if (tsc_khz ==0 )
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
[email protected]
AI reviewRe: [PATCH v6 03/51] x86/tsc: Ensure that TSC recalibration doesn't run if TSC frequency is known
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Valid virtual machine configurations with legacy CPU models will trigger a spurious WARN_ON_ONCE…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Valid virtual machine configurations with legacy CPU models will trigger a spurious WARN_ON_ONCE (and potential kernel panic) due to hypervisor paravirt clocks. --
--- Patch [3]: [PATCH v6 03/51] x86/tsc: Ensure that TSC recalibration doesn't run if TSC frequency is known --- commit dd99d8caeb7628be679eca32563aa6618e548028
Author: Sean Christopherson <[email protected]>
x86/tsc: Ensure that TSC recalibration doesn't run if TSC frequency is known
This commit adds a warning and bails from recalibrate_cpu_khz() if X86_FEATURE_TSC_KNOWN_FREQ is set. This is intended to catch out-of-spec hardware states on ancient CPUs where recalibration is attempted post-boot.
Quoted 3 lines
arch/x86/kernel/tsc.c +0
-0
[ ... ]
arch/x86/kernel/tsc.c void recalibrate_cpu_khz(void) · line 935
Quoted 7 lines
arch/x86/kernel/tsc.c +3
-0@@ -930,6 +930,9 @@ void recalibrate_cpu_khz(void)if (!boot_cpu_has (X86_FEATURE_TSC ))return ; +if (WARN_ON_ONCE (cpu_feature_enabled (X86_FEATURE_TSC_KNOWN_FREQ ))) +return ; +
[Severity: Medium]
Will this trigger spurious warnings on valid virtual machine configurations?
The commit message mentions that hitting this requires concocting an impossible CPU model like combining a P4 signature with CPUID 0x15. However, hypervisor paravirt clocks (like kvmclock, vmware, or mshyperv) unconditionally call setup_force_cpu_cap(X86_FEATURE_TSC_KNOWN_FREQ) during early boot, regardless of the emulated CPU generation.
If a VM is configured with a legacy CPU model (e.g. -cpu athlon) and runs an SMP=n kernel, the powernow-k7 cpufreq driver can successfully load and explicitly call recalibrate_cpu_khz(). Since the paravirt clock already forced the TSC_KNOWN_FREQ feature, cpu_feature_enabled() will evaluate to true and trigger this WARN_ON_ONCE, which can escalate to a fatal kernel panic on systems with panic_on_warn enabled.
Does this warning need to account for paravirtualized clocks setting this feature flag on legacy CPU models?
Quoted 2 lines
arch/x86/kernel/tsc.c +0
-0cpu_khz = x86_platform.calibrate_cpu (); tsc_khz = x86_platform.calibrate_tsc ();
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Sean Christopherson
maintainerPATCH v6 4/51 x86/tsc: Restrict recalibrate_cpu_khz() export to p4-clockmod and powernow-k7
In reply to Sean ChristophersonExport recalibrate_cpu_khz() only for its two users, p4-clockmod.ko and powernow-k7.ko, to help document that recalibration is relevant only to ancient CPUs.
For all intents and purposes, no functional change intended.
--- arch/x86/kernel/tsc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/kernel/tsc.c +1 -1
@@ -943,7 +943,7 @@ void recalibrate_cpu_khz(void) cpu_khz_old, cpu_khz);#endif } -EXPORT_SYMBOL_GPL (recalibrate_cpu_khz); +EXPORT_SYMBOL_FOR_MODULES (recalibrate_cpu_khz,"p4-clockmod,powernow-k7" );static unsigned long long cyc2ns_suspend;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Re: [PATCH v6 04/51] x86/tsc: Restrict recalibrate_cpu_khz() export to p4-clockmod and powernow-k7
Quoted 7 lines · Sean Christopherson
Export
recalibrate_cpu_khz()only for its two users, p4-clockmod.ko and powernow-k7.ko, to help document that recalibration is relevant only to ancient CPUs.For all intents and purposes, no functional change intended.
Signed-off-by Sean Christopherson <[email protected]>
Sean Christopherson
maintainerPATCH v6 5/51 x86/sev: Mark TSC as reliable when configuring Secure TSC
In reply to Sean ChristophersonMove the code to mark the TSC as reliable from sme_early_init() to snp_secure_tsc_init(). The only reader of TSC_RELIABLE is the aptly named check_system_tsc_reliable(), which runs in tsc_init(), i.e. after snp_secure_tsc_init().
This will allow consolidating the handling of TSC_KNOWN_FREQ and TSC_RELIABLE when overriding the TSC calibration routine.
--- arch/x86/coco/sev/core.c | 2 ++ arch/x86/mm/mem_encrypt_amd.c | 3 --- 2 files changed, 2 insertions(+), 3 deletions(-)
arch/x86/coco/sev/core.c +2 -0
@@ -2037,6 +2037,8 @@ void __init snp_secure_tsc_init(void) secrets = (__force struct snp_secrets_page *)mem;setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ ); +setup_force_cpu_cap (X86_FEATURE_TSC_RELIABLE ); +rdmsrq (MSR_AMD64_GUEST_TSC_FREQ , tsc_freq_mhz);/* Extract the GUEST TSC MHZ from BIT[17:0], rest is reserved space */
arch/x86/mm/mem_encrypt_amd.c +0 -3
@@ -535,9 +535,6 @@ void __init sme_early_init(void)*/ x86_init.resources.dmi_setup = snp_dmi_setup; } - -if (sev_status &MSR_AMD64_SNP_SECURE_TSC ) -setup_force_cpu_cap (X86_FEATURE_TSC_RELIABLE ); }void __init mem_encrypt_free_decrypted_mem (void )
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 6/51 x86/sev: Don't override CPU frequency calibration for SNP's Secure TSC
In reply to Sean ChristophersonDon't override the kernel's CPU frequency calibration routine when registering SNP's Secure TSC calibration routine. SNP (the architecture) provides zero guarantees that the CPU runs at the same frequency as the TSC. The justification for clobbering the CPU routine was:
Since the difference between CPU base and TSC frequency does not apply in this case, the same callback is being used.
but that's simply not true. E.g. if APERF/MPERF is exposed to the VM, then the CPU frequency absolutely does matter.
While relying on heuristics and/or the untrusted hypervisor to provide the CPU frequency isn't ideal, it's at least not outright wrong.
--- arch/x86/coco/sev/core.c | 1 - 1 file changed, 1 deletion(-)
arch/x86/coco/sev/core.c +0 -1
@@ -2046,7 +2046,6 @@ void __init snp_secure_tsc_init(void) snp_tsc_freq_khz =SNP_SCALE_TSC_FREQ (tsc_freq_mhz *1000 , secrets->tsc_factor); - x86_platform.calibrate_cpu = securetsc_get_tsc_khz; x86_platform.calibrate_tsc = securetsc_get_tsc_khz;early_memunmap (mem,PAGE_SIZE );
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
[email protected]
AI reviewRe: [PATCH v6 06/51] x86/sev: Don't override CPU frequency calibration for SNP's Secure TSC
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The patch attempts to decouple CPU frequency from Secure TSC frequency for SNP guests, but a…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The patch attempts to decouple CPU frequency from Secure TSC frequency for SNP guests, but a downstream core x86 check defeats this logic if the frequencies differ by more than 10%. --
--- Patch [6]: [PATCH v6 06/51] x86/sev: Don't override CPU frequency calibration for SNP's Secure TSC --- commit fde9a60ee57bc9ae26f0e19e9b9a2405fdf1fe11
Author: Sean Christopherson <[email protected]>
x86/sev: Don't override CPU frequency calibration for SNP's Secure TSC
This commit removes the override of the kernel's CPU frequency calibration routine for SNP guests with Secure TSC. It aims to allow the CPU frequency to be calibrated independently of the TSC frequency.
arch/x86/coco/sev/core.c void __init snp_secure_tsc_init(void) · line 2049
Quoted 9 lines
arch/x86/coco/sev/core.c +0
-1@@ -2046,7 +2046,6 @@ void __init snp_secure_tsc_init(void) snp_tsc_freq_khz =SNP_SCALE_TSC_FREQ (tsc_freq_mhz *1000 , secrets->tsc_factor); - x86_platform.calibrate_cpu = securetsc_get_tsc_khz;
[Severity: Medium]
Does this actually decouple the frequencies if they differ significantly?
If the independent CPU calibration determines a frequency that differs from the Secure TSC frequency by more than 10%, the core x86 code will still overwrite it.
Looking at determine_cpu_tsc_frequencies() in arch/x86/kernel/tsc.c:
if (cpu_khz == 0)
cpu_khz = tsc_khz;
else if (abs(cpu_khz - tsc_khz) * 10 > tsc_khz)
cpu_khz = tsc_khz;Will this downstream sanity check silently clamp cpu_khz back to tsc_khz anyway, defeating the patch's attempt to keep them separate when APERF/MPERF values diverge?
Quoted 3 lines
arch/x86/coco/sev/core.c +0
-0x86_platform.calibrate_tsc = securetsc_get_tsc_khz;early_memunmap (mem,PAGE_SIZE );
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Re: [PATCH v6 06/51] x86/sev: Don't override CPU frequency calibration for SNP's Secure TSC
In reply to Sean ChristophersonQuoted 11 lines · Sean Christopherson
Don't override the kernel's CPU frequency calibration routine when registering SNP's Secure TSC calibration routine. SNP (the architecture) provides zero guarantees that the CPU runs at the same frequency as the TSC. The justification for clobbering the CPU routine was:
Since the difference between CPU base and TSC frequency does not apply in this case, the same callback is being used.
but that's simply not true. E.g. if APERF/MPERF is exposed to the VM, then the CPU frequency absolutely does matter.
Quoted 8 lines
While relying on heuristics and/or the untrusted hypervisor to provide the CPU frequency isn't ideal, it's at least not outright wrong.
Fixes 73bbf3b0fbba ("x86/tsc: Init the TSC for Secure TSC guests")Cc Nikunj A Dadhania <[email protected]>Cc Tom Lendacky <[email protected]>Reviewed-by Nikunj A Dadhania <[email protected]>Signed-off-by Sean Christopherson <[email protected]>
I don't think I care about Sashiko's complaint. Even if we still clamp it in generic code, I think that's better than having those in the platform-specific code.
Sean Christopherson
maintainerPATCH v6 7/51 x86/sev: Move check for SNP Secure TSC support to tsc_early_init()
In reply to Sean ChristophersonMove the check on having a Secure TSC to the common tsc_early_init() so that it's obvious that having a Secure TSC is conditional, and to prepare for adding TDX to the mix (blindly initializing *both* SNP and TDX TSC logic looks especially weird).
No functional change intended.
--- arch/x86/coco/sev/core.c | 3 --- arch/x86/kernel/tsc.c | 3 ++- 2 files changed, 2 insertions(+), 4 deletions(-)
arch/x86/coco/sev/core.c +0 -3
@@ -2025,9 +2025,6 @@ void __init snp_secure_tsc_init(void)unsigned long tsc_freq_mhz;void *mem; -if (!cc_platform_has (CC_ATTR_GUEST_SNP_SECURE_TSC )) -return ; - mem =early_memremap_encrypted (sev_secrets_pa,PAGE_SIZE );if (!mem) {pr_err ("Unable to get TSC_FACTOR: failed to map the SNP secrets page.\n" );
arch/x86/kernel/tsc.c +2 -1
@@ -1509,7 +1509,8 @@ void __init tsc_early_init(void)if (is_early_uv_system ())return ; -snp_secure_tsc_init (); +if (cc_platform_has (CC_ATTR_GUEST_SNP_SECURE_TSC )) +snp_secure_tsc_init ();if (!determine_cpu_tsc_frequencies (true))return ;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 8/51 x86/sev: Shove SNP's secure/trusted TSC frequency directly into "calibration"
In reply to Sean ChristophersonAs a first step towards dropping .calibrate_{cpu,tsc}() and explicitly defining precedence/priority for "calibration" routines, pass the secure TSC frequency obtained from SNP firmware directly to determine_cpu_tsc_frequencies() instead of overriding the .calibrate_tsc() hook.
Unlike the native calibration routines, all of the paravirtual overrides, including SNP and TDX, are constant in the sense that the frequency provided by the hypervisor or trusted firmware is fixed, known, and always available during early boot. More importantly, for CoCo (SNP and TDX) VMs, it's imperative that the kernel uses the frequency provided by the trusted firmware, not by the untrusted hypervisor. Enforcing the priority between sources by carefully ordering seemingly unrelated init calls, so that the trusted override "wins", is brittle and all but impossible to follow.
Explicitly ignore tsc_early_khz if the exact TSC frequency was obtained from trusted firmware, as per commit bd35c77e32e4 ("x86/tsc: Add tsc_early_khz command line parameter"), the goal of the param is to play nice with setups that provide partial frequency information in CPUID, i.e. is NOT intended to be a hard override. Neither SNP's secure TSC nor TDX was supported when commit bd35c77e32e4 landed back in 2020, i.e. lack of consideration for the interaction was purely due to oversight when SNP and TDX support came along.
--- .../admin-guide/kernel-parameters.txt | 4 +++ arch/x86/coco/sev/core.c | 14 +++-------- arch/x86/include/asm/sev.h | 4 +-- arch/x86/kernel/tsc.c | 25 ++++++++++++++----- 4 files changed, 29 insertions(+), 18 deletions(-)
Documentation/admin-guide/kernel-parameters.txt +4 -0
@@ -7946,6 +7946,10 @@ Kernel parameters with CPUID.16h support and partial CPUID.15h support. Format: <unsigned int> + Note, tsc_early_khz is ignored if the TSC frequency is + provided by trusted firmware when running as an SNP + guest. + tsx= [X86] Control Transactional Synchronization Extensions (TSX) feature in Intel processors that support TSX control.
arch/x86/coco/sev/core.c +4 -10
@@ -99,7 +99,6 @@ static const char * const sev_status_feat_names[] = {*/ static u64 snp_tsc_scale__ro_after_init ;static u64 snp_tsc_offset__ro_after_init ; -static unsigned long snp_tsc_freq_khz__ro_after_init ; DEFINE_PER_CPU(struct sev_es_runtime_data*, runtime_data); DEFINE_PER_CPU(struct sev_es_save_area *, sev_vmsa);
@@ -2014,15 +2013,10 @@ void __init snp_secure_tsc_prepare(void)pr_debug ("SecureTSC enabled" ); } -static unsigned long securetsc_get_tsc_khz (void ) -{ -return snp_tsc_freq_khz; -} - -void __init snp_secure_tsc_init (void ) +unsigned int __init snp_secure_tsc_init (void ) { +unsigned long snp_tsc_freq_khz, tsc_freq_mhz;struct snp_secrets_page *secrets; -unsigned long tsc_freq_mhz;void *mem; mem =early_memremap_encrypted (sev_secrets_pa,PAGE_SIZE );
@@ -2043,7 +2037,7 @@ void __init snp_secure_tsc_init(void) snp_tsc_freq_khz =SNP_SCALE_TSC_FREQ (tsc_freq_mhz *1000 , secrets->tsc_factor); - x86_platform.calibrate_tsc = securetsc_get_tsc_khz; -early_memunmap (mem,PAGE_SIZE ); + +return snp_tsc_freq_khz; }
arch/x86/include/asm/sev.h +2 -2
@@ -530,7 +530,7 @@ int snp_send_guest_request(struct snp_msg_desc *mdesc, struct snp_guest_req *reqint snp_svsm_vtpm_send_command (u8 *buffer);void __init snp_secure_tsc_prepare (void ); -void __init snp_secure_tsc_init (void ); +unsigned int snp_secure_tsc_init (void );enum es_result savic_register_gpa (u64 gpa);enum es_result savic_unregister_gpa (u64 *gpa);u64 savic_ghcb_msr_read (u32 reg);
@@ -637,7 +637,7 @@ static inline int snp_send_guest_request(struct snp_msg_desc *mdesc, struct snp_guest_req *req) { return -ENODEV; }static inline int snp_svsm_vtpm_send_command (u8 *buffer) {return -ENODEV ; }static inline void __init snp_secure_tsc_prepare (void ) { } -static inline void __init snp_secure_tsc_init (void ) { } +static inline unsigned int __init snp_secure_tsc_init (void ) {return 0 ; }static inline void sev_evict_cache (void *va,int npages) {}static inline enum es_result savic_register_gpa (u64 gpa) {return ES_UNSUPPORTED ; }static inline enum es_result savic_unregister_gpa (u64 *gpa) {return ES_UNSUPPORTED ; }
arch/x86/kernel/tsc.c +19 -6
@@ -1440,15 +1440,16 @@ static int __init init_tsc_clocksource(void)*/ device_initcall (init_tsc_clocksource); -static bool __init determine_cpu_tsc_frequencies (bool early) +static bool __init determine_cpu_tsc_frequencies (bool early, +unsigned int known_tsc_khz) {/* Make sure that cpu and tsc are not already calibrated */ WARN_ON (cpu_khz || tsc_khz);if (early) { cpu_khz = x86_platform.calibrate_cpu (); -if (tsc_early_khz) - tsc_khz = tsc_early_khz; +if (known_tsc_khz) + tsc_khz = known_tsc_khz;else tsc_khz = x86_platform.calibrate_tsc (); }else {
@@ -1503,6 +1504,8 @@ static void __init tsc_enable_sched_clock(void)void __init tsc_early_init (void ) { +unsigned int known_tsc_khz =0 ; +if (!boot_cpu_has (X86_FEATURE_TSC ))return ;/* Don't change UV TSC multi-chassis synchronization */
@@ -1510,9 +1513,19 @@ void __init tsc_early_init(void)return ;if (cc_platform_has (CC_ATTR_GUEST_SNP_SECURE_TSC )) -snp_secure_tsc_init (); + known_tsc_khz =snp_secure_tsc_init (); -if (!determine_cpu_tsc_frequencies (true)) +/* +* Ignore the user-provided TSC frequency if the exact frequency was +* obtained from trusted firmware, as the user-provided frequency is +* intended as a "starting point", not a known, guaranteed frequency. +*/ +if (!known_tsc_khz) + known_tsc_khz = tsc_early_khz; +else if (tsc_early_khz) +pr_err ("Ignoring 'tsc_early_khz' in favor of trusted firmware.\n" ); + +if (!determine_cpu_tsc_frequencies (true, known_tsc_khz))return ;tsc_enable_sched_clock (); }
@@ -1533,7 +1546,7 @@ void __init tsc_init(void)if (!tsc_khz) {/* We failed to determine frequencies earlier, try again */ -if (!determine_cpu_tsc_frequencies (false)) { +if (!determine_cpu_tsc_frequencies (false,0 )) {mark_tsc_unstable ("could not calculate TSC khz" );setup_clear_cpu_cap (X86_FEATURE_TSC_DEADLINE_TIMER );return ;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Re: [PATCH v6 08/51] x86/sev: Shove SNP's secure/trusted TSC frequency directly into "calibration"
Quoted 24 lines · Sean Christopherson
As a first step towards dropping .calibrate_{cpu,tsc}() and explicitly defining precedence/priority for "calibration" routines, pass the secure TSC frequency obtained from SNP firmware directly to
determine_cpu_tsc_frequencies()instead of overriding the .calibrate_tsc() hook.Unlike the native calibration routines, all of the paravirtual overrides, including SNP and TDX, are constant in the sense that the frequency provided by the hypervisor or trusted firmware is fixed, known, and always available during early boot. More importantly, for CoCo (SNP and TDX) VMs, it's imperative that the kernel uses the frequency provided by the trusted firmware, not by the untrusted hypervisor. Enforcing the priority between sources by carefully ordering seemingly unrelated init calls, so that the trusted override "wins", is brittle and all but impossible to follow.
Explicitly ignore
tsc_early_khzif the exact TSC frequency was obtained from trusted firmware, as per commitbd35c77e32e4("x86/tsc: Addtsc_early_khzcommand line parameter"), the goal of the param is to play nice with setups that provide partial frequency information in CPUID, i.e. is NOT intended to be a hard override. Neither SNP's secure TSC nor TDX was supported when commitbd35c77e32e4landed back in 2020, i.e. lack of consideration for the interaction was purely due to oversight when SNP and TDX support came along.
Quoted 3 lines
Reviewed-by Nikunj A Dadhania <[email protected]>Tested-by Nikunj A Dadhania <[email protected]>Signed-off-by Sean Christopherson <[email protected]>
Sean Christopherson
maintainerPATCH v6 9/51 x86/tsc: Add a standalone helper for getting TSC info from CPUID.0x15
In reply to Sean ChristophersonExtract retrieval of TSC frequency information from CPUID into a standalone helper so that TDX guest support can reuse the logic.
Opportunistically drop native_calibrate_tsc()'s "== 0" and "!= 0" checks in favor of the kernel's preferred style.
No functional change intended.
--- arch/x86/kernel/tsc.c | 61 +++++++++++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 23 deletions(-)
arch/x86/kernel/tsc.c +38 -23
@@ -645,46 +645,62 @@ static unsigned long quick_pit_calibrate(void)return delta; } +struct cpuid_tsc_info { +unsigned int denominator; +unsigned int numerator; +unsigned int crystal_khz; +}; + +static int cpuid_get_tsc_info (struct cpuid_tsc_info *info) +{ +unsigned int ecx_hz, edx; + +if (boot_cpu_data.cpuid_level <CPUID_LEAF_TSC ) +return -ENOENT ; + +/* CPUID 15H TSC/Crystal ratio, plus optionally Crystal Hz */ +cpuid (CPUID_LEAF_TSC , &info->denominator, &info->numerator, &ecx_hz, &edx); + +if (!info->denominator || !info->numerator) +return -ENOENT ; + +/* +* Note: some CPUs provide the multiplier information, but not the core +* crystal frequency. The multiplier information is still useful for +* such CPUs, as the crystal frequency can be gleaned from CPUID.0x16. +*/ + info->crystal_khz = ecx_hz /1000 ; +return 0 ; +} +/** * native_calibrate_tsc - determine TSC frequency * Determine TSC frequency via CPUID, else return 0. */ unsigned long native_calibrate_tsc (void ) { -unsigned int eax_denominator, ebx_numerator, ecx_hz, edx; -unsigned int crystal_khz; +struct cpuid_tsc_info info;if (boot_cpu_data.x86_vendor !=X86_VENDOR_INTEL )return 0 ; -if (boot_cpu_data.cpuid_level <CPUID_LEAF_TSC ) +if (cpuid_get_tsc_info (&info))return 0 ; - eax_denominator = ebx_numerator = ecx_hz = edx =0 ; - -/* CPUID 15H TSC/Crystal ratio, plus optionally Crystal Hz */ -cpuid (CPUID_LEAF_TSC , &eax_denominator, &ebx_numerator, &ecx_hz, &edx); - -if (ebx_numerator ==0 || eax_denominator ==0 ) -return 0 ; - - crystal_khz = ecx_hz /1000 ; -/* * Denverton SoCs don't report crystal clock, and also don't support * CPUID_LEAF_FREQ for the calculation below, so hardcode the 25MHz * crystal clock. */ -if (crystal_khz ==0 && - boot_cpu_data.x86_vfm ==INTEL_ATOM_GOLDMONT_D ) - crystal_khz =25000 ; +if (!info.crystal_khz && boot_cpu_data.x86_vfm ==INTEL_ATOM_GOLDMONT_D ) + info.crystal_khz =25000 ;/* * TSC frequency reported directly by CPUID is a "hardware reported" * frequency and is the most accurate one so far we have. This * is considered a known frequency. */ -if (crystal_khz !=0 ) +if (info.crystal_khz)setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ );/*
@@ -692,15 +708,14 @@ unsigned long native_calibrate_tsc(void)* clock, but we can easily calculate it to a high degree of accuracy * by considering the crystal ratio and the CPU speed. */ -if (crystal_khz ==0 && boot_cpu_data.cpuid_level >=CPUID_LEAF_FREQ ) { +if (!info.crystal_khz && boot_cpu_data.cpuid_level >=CPUID_LEAF_FREQ ) {unsigned int eax_base_mhz, ebx, ecx, edx;cpuid (CPUID_LEAF_FREQ , &eax_base_mhz, &ebx, &ecx, &edx); - crystal_khz = eax_base_mhz *1000 * - eax_denominator / ebx_numerator; + info.crystal_khz = eax_base_mhz *1000 * info.denominator / info.numerator; } -if (crystal_khz ==0 ) +if (!info.crystal_khz)return 0 ;/*
@@ -716,9 +731,9 @@ unsigned long native_calibrate_tsc(void)* lapic_timer_period here to avoid having to calibrate the APIC * timer later. */ -apic_set_timer_frequency_khz (crystal_khz,"CPUID 0x15/0x16" ); +apic_set_timer_frequency_khz (info.crystal_khz,"CPUID 0x15/0x16" ); -return crystal_khz * ebx_numerator / eax_denominator; +return info.crystal_khz * info.numerator / info.denominator; }static unsigned long cpu_khz_from_cpuid (void )
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 10/51 x86/tdx: Force TSC frequency with CPUID-based info provided by the TDX-Module
In reply to Sean ChristophersonWhen running as a TDX guest, explicitly set the TSC frequency to a known value, using CPUID-based information, instead of potentially relying on a hypervisor-controlled PV routine. For TDX guests, CPUID.0x15 is always emulated by the TDX-Module, i.e. the information from CPUID is more trustworthy than the information provided by the hypervisor.
To maintain backwards compatibility with TDX guest kernels that use native calibration, and because it's the least awful option, retain native_calibrate_tsc()'s stuffing of the local APIC bus period using the core crystal frequency. While it's entirely possible for the hypervisor to emulate the APIC timer at a different frequency than the core crystal frequency, the commonly accepted interpretation of Intel's SDM is that APIC timer runs at the core crystal frequency when that latter is enumerated via CPUID:
The APIC timer frequency will be the processor’s bus clock or core crystal clock frequency (when TSC/core crystal clock ratio is enumerated in CPUID leaf 0x15).
If the hypervisor is malicious and deliberately runs the APIC timer at the wrong frequency, nothing would stop the hypervisor from modifying the frequency at any time, i.e. attempting to manually calibrate the frequency out of paranoia would be futile.
Deliberately leave CPU frequency calibration as is, since the TDX-Module doesn't provide any guarantees with respect to CPUID.0x16.
Expose and use cpuid_get_tsc_info() instead of providing a wrapper to get the TSC and core crystal frequency, as TDX is the only anticipated user outside of the TSC code, i.e. adding a helper to dedup the math won't actually dedup anything. Having TDX use "struct cpuid_tsc_info" also avoids the temptation of declaring a local "tsc_khz" variable and thus unintentionally creating a shadow of the global "tsc_khz".
--- .../admin-guide/kernel-parameters.txt | 4 ++-- arch/x86/coco/tdx/tdx.c | 20 ++++++++++++++++--- arch/x86/include/asm/tdx.h | 2 ++ arch/x86/include/asm/tsc.h | 7 +++++++ arch/x86/kernel/tsc.c | 11 ++++------ 5 files changed, 32 insertions(+), 12 deletions(-)
Documentation/admin-guide/kernel-parameters.txt +2 -2
@@ -7947,8 +7947,8 @@ Kernel parameters Format: <unsigned int> Note, tsc_early_khz is ignored if the TSC frequency is - provided by trusted firmware when running as an SNP - guest. + provided by trusted firmware when running as an SNP or + TDX guest. tsx= [X86] Control Transactional Synchronization Extensions (TSX) feature in Intel processors that
arch/x86/coco/tdx/tdx.c +17 -3
@@ -8,6 +8,7 @@#include <linux/export.h> #include <linux/io.h> #include <linux/kexec.h> +#include <asm/apic.h> #include <asm/coco.h> #include <asm/tdx.h> #include <asm/vmx.h>
@@ -1121,9 +1122,6 @@ void __init tdx_early_init(void)setup_force_cpu_cap (X86_FEATURE_TDX_GUEST ); -/* TSC is the only reliable clock in TDX guest */ -setup_force_cpu_cap (X86_FEATURE_TSC_RELIABLE ); - cc_vendor =CC_VENDOR_INTEL ;/* Configure the TD */
@@ -1193,3 +1191,19 @@ void __init tdx_early_init(void)tdx_announce (); } + +unsigned int __init tdx_tsc_init (void ) +{ +struct cpuid_tsc_info info; + +if (WARN_ON_ONCE (cpuid_get_tsc_info (&info) || !info.crystal_khz)) +return 0 ; + +apic_set_timer_frequency_khz (info.crystal_khz,"TDX-Module via CPUID" ); + +/* TSC is the only reliable clock in TDX guest */ +setup_force_cpu_cap (X86_FEATURE_TSC_RELIABLE ); +setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ ); + +return info.crystal_khz * info.numerator / info.denominator; +}
arch/x86/include/asm/tdx.h +2 -0
@@ -68,6 +68,7 @@ struct ve_info {#ifdef CONFIG_INTEL_TDX_GUEST void __init tdx_early_init (void ); +unsigned int __init tdx_tsc_init (void );void tdx_get_ve_info (struct ve_info *ve);
@@ -89,6 +90,7 @@ void __init tdx_dump_td_ctls(u64 td_ctls);#else static inline void tdx_early_init (void ) { }; +static inline unsigned int tdx_tsc_init (void ) {return 0 ; }static inline void tdx_halt (void ) { };static inline bool tdx_early_handle_ve (struct pt_regs *regs) {return false; }
arch/x86/include/asm/tsc.h +7 -0
@@ -82,6 +82,13 @@ static inline cycles_t get_cycles(void) }#define get_cycles get_cycles +struct cpuid_tsc_info { +unsigned int denominator; +unsigned int numerator; +unsigned int crystal_khz; +}; +extern int cpuid_get_tsc_info (struct cpuid_tsc_info *info); +extern void tsc_early_init (void );extern void tsc_init (void );extern void mark_tsc_unstable (char *reason);
arch/x86/kernel/tsc.c +4 -7
@@ -34,6 +34,7 @@#include <asm/topology.h> #include <asm/uv/uv.h> #include <asm/sev.h> +#include <asm/tdx.h> unsigned int __read_mostly cpu_khz;/* TSC clocks / usec, not used here */ EXPORT_SYMBOL (cpu_khz);
@@ -645,13 +646,7 @@ static unsigned long quick_pit_calibrate(void)return delta; } -struct cpuid_tsc_info { -unsigned int denominator; -unsigned int numerator; -unsigned int crystal_khz; -}; - -static int cpuid_get_tsc_info (struct cpuid_tsc_info *info) +int cpuid_get_tsc_info (struct cpuid_tsc_info *info) {unsigned int ecx_hz, edx;
@@ -1529,6 +1524,8 @@ void __init tsc_early_init(void)if (cc_platform_has (CC_ATTR_GUEST_SNP_SECURE_TSC )) known_tsc_khz =snp_secure_tsc_init (); +else if (boot_cpu_has (X86_FEATURE_TDX_GUEST )) + known_tsc_khz =tdx_tsc_init ();/* * Ignore the user-provided TSC frequency if the exact frequency was
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Re: [PATCH v6 10/51] x86/tdx: Force TSC frequency with CPUID-based info provided by the TDX-Module
Quoted 34 lines · Sean Christopherson
When running as a TDX guest, explicitly set the TSC frequency to a known value, using CPUID-based information, instead of potentially relying on a hypervisor-controlled PV routine. For TDX guests, CPUID.0x15 is always emulated by the TDX-Module, i.e. the information from CPUID is more trustworthy than the information provided by the hypervisor.
To maintain backwards compatibility with TDX guest kernels that use native calibration, and because it's the least awful option, retain native_calibrate_tsc()'s stuffing of the local APIC bus period using the core crystal frequency. While it's entirely possible for the hypervisor to emulate the APIC timer at a different frequency than the core crystal frequency, the commonly accepted interpretation of Intel's SDM is that APIC timer runs at the core crystal frequency when that latter is enumerated via CPUID:
The APIC timer frequency will be the processor's bus clock or core crystal clock frequency (when TSC/core crystal clock ratio is enumerated in CPUID leaf
0x15).If the hypervisor is malicious and deliberately runs the APIC timer at the wrong frequency, nothing would stop the hypervisor from modifying the frequency at any time, i.e. attempting to manually calibrate the frequency out of paranoia would be futile.
Deliberately leave CPU frequency calibration as is, since the TDX-Module doesn't provide any guarantees with respect to CPUID.0x16.
Expose and use
cpuid_get_tsc_info()instead of providing a wrapper to get the TSC and core crystal frequency, as TDX is the only anticipated user outside of the TSC code, i.e. adding a helper to dedup the math won't actually dedup anything. Having TDX use "structcpuid_tsc_info" also avoids the temptation of declaring a local "tsc_khz" variable and thus unintentionally creating a shadow of the global "tsc_khz".
Quoted 2 lines
Cc Kiryl Shutsemau (Meta) <[email protected]>Signed-off-by Sean Christopherson <[email protected]>
I don't know if we should set X86_FEATURE_TSC_RELIABLE before bailing out in the case where cpuid_get_tsc_info() fails, or just not care about that because it Can Never Happen™? Previously it was set unconditionally from tdx_early_init().
Whatever...
Sean Christopherson
maintainerRe: [PATCH v6 10/51] x86/tdx: Force TSC frequency with CPUID-based info provided by the TDX-Module
Quoted 38 lines · David Woodhouse
Quoted 34 lines · Sean Christopherson
When running as a TDX guest, explicitly set the TSC frequency to a known value, using CPUID-based information, instead of potentially relying on a hypervisor-controlled PV routine. For TDX guests, CPUID.0x15 is always emulated by the TDX-Module, i.e. the information from CPUID is more trustworthy than the information provided by the hypervisor.
To maintain backwards compatibility with TDX guest kernels that use native calibration, and because it's the least awful option, retain native_calibrate_tsc()'s stuffing of the local APIC bus period using the core crystal frequency. While it's entirely possible for the hypervisor to emulate the APIC timer at a different frequency than the core crystal frequency, the commonly accepted interpretation of Intel's SDM is that APIC timer runs at the core crystal frequency when that latter is enumerated via CPUID:
The APIC timer frequency will be the processor's bus clock or core crystal clock frequency (when TSC/core crystal clock ratio is enumerated in CPUID leaf
0x15).If the hypervisor is malicious and deliberately runs the APIC timer at the wrong frequency, nothing would stop the hypervisor from modifying the frequency at any time, i.e. attempting to manually calibrate the frequency out of paranoia would be futile.
Deliberately leave CPU frequency calibration as is, since the TDX-Module doesn't provide any guarantees with respect to CPUID.0x16.
Expose and use
cpuid_get_tsc_info()instead of providing a wrapper to get the TSC and core crystal frequency, as TDX is the only anticipated user outside of the TSC code, i.e. adding a helper to dedup the math won't actually dedup anything. Having TDX use "structcpuid_tsc_info" also avoids the temptation of declaring a local "tsc_khz" variable and thus unintentionally creating a shadow of the global "tsc_khz".Quoted 2 lines
Cc Kiryl Shutsemau (Meta) <[email protected]>Signed-off-by Sean Christopherson <[email protected]>
Quoted 6 lines
I don't know if we should set
X86_FEATURE_TSC_RELIABLEbefore bailing out in the case wherecpuid_get_tsc_info()fails, or just not care about that because it Can Never Happen™? Previously it was set unconditionally fromtdx_early_init().Whatever...
Heh, yeah, "whatever" is about my thought exactly. I could go either way. I would buy an argument that the TSC itself is still reliable even if the frequency isn't known. On the other hand, the frequency could be computed via calibration, at which point the frequency is no longer reliable and arguably should be sanity checked.
Sean Christopherson
maintainerPATCH v6 11/51 x86/tsc: Add dedicated hypervisor hooks for getting known TSC/CPU frequencies
In reply to Sean ChristophersonAdd dedicated hypervisor hooks for getting known TSC/CPU frequencies instead of overriding seemingly generic platform hooks, and explicitly prioritize hypervisor-provided frequencies over native methods, but do NOT clobber the frequency obtained from trusted firmware. While shuffling the hooks around is arguably "six of one, half dozen of the other", scoping them to x86_hyper_init makes their purpose more obvious, and allows for explicitly defining the priority of sources (as is done here).
As is already done when trusted firmware provides the TSC frequency, ignore tsc_early_khz if the exact TSC frequency was obtained from the hypervisor, as attempting to refine the TSC frequency when running in a VM is all but guaranteed to cause problems sooner or later due to the calibration sources being emulated devices in the vast majority of setups.
--- .../admin-guide/kernel-parameters.txt | 3 +- arch/x86/include/asm/acrn.h | 5 ---- arch/x86/include/asm/x86_init.h | 4 +++ arch/x86/kernel/cpu/acrn.c | 10 +++++-- arch/x86/kernel/cpu/mshyperv.c | 6 ++-- arch/x86/kernel/cpu/vmware.c | 8 ++--- arch/x86/kernel/jailhouse.c | 6 ++-- arch/x86/kernel/kvmclock.c | 6 ++-- arch/x86/kernel/tsc.c | 29 ++++++++++++++----- arch/x86/xen/time.c | 4 +-- 10 files changed, 50 insertions(+), 31 deletions(-)
Documentation/admin-guide/kernel-parameters.txt +2 -1
@@ -7948,7 +7948,8 @@ Kernel parameters Note, tsc_early_khz is ignored if the TSC frequency is provided by trusted firmware when running as an SNP or - TDX guest. + TDX guest, or when the hypervisor provides the exact + frequency via a paravirtual interface. tsx= [X86] Control Transactional Synchronization Extensions (TSX) feature in Intel processors that
arch/x86/include/asm/acrn.h +0 -5
@@ -32,11 +32,6 @@ static inline u32 acrn_cpuid_base(void)return 0 ; } -static inline unsigned long acrn_get_tsc_khz (void ) -{ -return cpuid_eax (ACRN_CPUID_TIMING_INFO ); -} -/* * Hypercalls for ACRN *
arch/x86/include/asm/x86_init.h +4 -0
@@ -123,6 +123,8 @@ struct x86_init_pci {* @msi_ext_dest_id: MSI supports 15-bit APIC IDs * @init_mem_mapping: setup early mappings during init_mem_mapping() * @init_after_bootmem: guest init after boot allocator is finished +* @get_tsc_khz: get the TSC frequency (returns 0 if frequency is unknown) +* @get_cpu_khz: get the CPU frequency (returns 0 if frequency is unknown) */ struct x86_hyper_init {void (*init_platform)(void );
@@ -131,6 +133,8 @@ struct x86_hyper_init {bool (*msi_ext_dest_id)(void );void (*init_mem_mapping)(void );void (*init_after_bootmem)(void ); +unsigned int (*get_tsc_khz)(void ); +unsigned int (*get_cpu_khz)(void ); };/**
arch/x86/kernel/cpu/acrn.c +7 -3
@@ -24,13 +24,15 @@ static u32 __init acrn_detect(void)return acrn_cpuid_base (); } +static unsigned int __init acrn_get_tsc_khz (void ) +{ +return cpuid_eax (ACRN_CPUID_TIMING_INFO ); +} +static void __init acrn_init_platform (void ) {/* Install system interrupt handler for ACRN hypervisor callback */ sysvec_install (HYPERVISOR_CALLBACK_VECTOR , sysvec_acrn_hv_callback); - - x86_platform.calibrate_tsc = acrn_get_tsc_khz; - x86_platform.calibrate_cpu = acrn_get_tsc_khz; }static bool acrn_x2apic_available (void )
@@ -78,4 +80,6 @@ const __initconst struct hypervisor_x86 x86_hyper_acrn = { .type = X86_HYPER_ACRN, .init.init_platform = acrn_init_platform, .init.x2apic_available = acrn_x2apic_available, + .init.get_tsc_khz = acrn_get_tsc_khz, + .init.get_cpu_khz = acrn_get_tsc_khz, };
arch/x86/kernel/cpu/mshyperv.c +3 -3
@@ -395,7 +395,7 @@ static int hv_nmi_unknown(unsigned int val, struct pt_regs *regs) }#endif -static unsigned long hv_get_tsc_khz (void ) +static unsigned int __init hv_get_tsc_khz (void ) {unsigned long freq;
@@ -573,8 +573,8 @@ static void __init ms_hyperv_init_platform(void)if (ms_hyperv.features &HV_ACCESS_FREQUENCY_MSRS && ms_hyperv.misc_features &HV_FEATURE_FREQUENCY_MSRS_AVAILABLE ) { - x86_platform.calibrate_tsc = hv_get_tsc_khz; - x86_platform.calibrate_cpu = hv_get_tsc_khz; + x86_init.hyper.get_tsc_khz = hv_get_tsc_khz; + x86_init.hyper.get_cpu_khz = hv_get_tsc_khz;setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ ); }
arch/x86/kernel/cpu/vmware.c +4 -4
@@ -64,7 +64,7 @@ struct vmware_steal_time {u64 reserved[7 ]; }; -static unsigned long vmware_tsc_khz__ro_after_init ; +static unsigned long vmware_tsc_khz__initdata ;static u8 vmware_hypercall_mode__ro_after_init ; unsigned long vmware_hypercall_slow(unsigned long cmd,
@@ -137,7 +137,7 @@ static inline int __vmware_platform(void)return eax !=UINT_MAX && ebx ==VMWARE_HYPERVISOR_MAGIC ; } -static unsigned long vmware_get_tsc_khz (void ) +static unsigned int __init vmware_get_tsc_khz (void ) {return vmware_tsc_khz; }
@@ -419,8 +419,8 @@ static void __init vmware_platform_setup(void) } vmware_tsc_khz = tsc_khz; - x86_platform.calibrate_tsc = vmware_get_tsc_khz; - x86_platform.calibrate_cpu = vmware_get_tsc_khz; + x86_init.hyper.get_tsc_khz = vmware_get_tsc_khz; + x86_init.hyper.get_cpu_khz = vmware_get_tsc_khz;/* Skip lapic calibration since we know the bus frequency. */ apic_set_timer_frequency_hz (ecx,"VMware hypervisor" );
arch/x86/kernel/jailhouse.c +3 -3
@@ -68,7 +68,7 @@ static void __init jailhouse_timer_init(void)apic_set_timer_frequency_khz (setup_data.v1.apic_khz,"Jailhouse hypervisor" ); } -static unsigned long jailhouse_get_tsc (void ) +static unsigned int __init jailhouse_get_tsc (void ) {return precalibrated_tsc_khz; }
@@ -210,8 +210,6 @@ static void __init jailhouse_init_platform(void) x86_init.mpparse.parse_smp_cfg = jailhouse_parse_smp_config; x86_init.pci.arch_init = jailhouse_pci_arch_init; - x86_platform.calibrate_cpu = jailhouse_get_tsc; - x86_platform.calibrate_tsc = jailhouse_get_tsc; x86_platform.get_wallclock = jailhouse_get_wallclock; x86_platform.legacy.rtc =0 ; x86_platform.legacy.warm_reset =0 ;
@@ -293,5 +291,7 @@ const struct hypervisor_x86 x86_hyper_jailhouse __refconst = { .detect = jailhouse_detect, .init.init_platform = jailhouse_init_platform, .init.x2apic_available = jailhouse_x2apic_available, + .init.get_tsc_khz = jailhouse_get_tsc, + .init.get_cpu_khz = jailhouse_get_tsc, .ignore_nopv = true, };
arch/x86/kernel/kvmclock.c +3 -3
@@ -136,7 +136,7 @@ static inline void kvm_sched_clock_init(bool stable)* poll of guests can be running and trouble each other. So we preset * lpj here */ -static unsigned long kvm_get_tsc_khz (void ) +static unsigned int __init kvm_get_tsc_khz (void ) {setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ );return pvclock_tsc_khz (this_cpu_pvti ());
@@ -343,8 +343,8 @@ void __init kvmclock_init(void) flags =pvclock_read_flags (&hv_clock_boot[0 ].pvti);kvm_sched_clock_init (flags &PVCLOCK_TSC_STABLE_BIT ); - x86_platform.calibrate_tsc = kvm_get_tsc_khz; - x86_platform.calibrate_cpu = kvm_get_tsc_khz; + x86_init.hyper.get_tsc_khz = kvm_get_tsc_khz; + x86_init.hyper.get_cpu_khz = kvm_get_tsc_khz; x86_platform.get_wallclock = kvm_get_wallclock; x86_platform.set_wallclock = kvm_set_wallclock;#ifdef CONFIG_X86_LOCAL_APIC
arch/x86/kernel/tsc.c +22 -7
@@ -1451,13 +1451,17 @@ static int __init init_tsc_clocksource(void)device_initcall (init_tsc_clocksource);static bool __init determine_cpu_tsc_frequencies (bool early, +unsigned int known_cpu_khz,unsigned int known_tsc_khz) {/* Make sure that cpu and tsc are not already calibrated */ WARN_ON (cpu_khz || tsc_khz);if (early) { - cpu_khz = x86_platform.calibrate_cpu (); +if (known_cpu_khz) + cpu_khz = known_cpu_khz; +else + cpu_khz = x86_platform.calibrate_cpu ();if (known_tsc_khz) tsc_khz = known_tsc_khz;else
@@ -1514,7 +1518,7 @@ static void __init tsc_enable_sched_clock(void)void __init tsc_early_init (void ) { -unsigned int known_tsc_khz =0 ; +unsigned int known_cpu_khz =0 , known_tsc_khz =0 ;if (!boot_cpu_has (X86_FEATURE_TSC ))return ;
@@ -1522,22 +1526,33 @@ void __init tsc_early_init(void)if (is_early_uv_system ())return ; +if (x86_init.hyper.get_cpu_khz) + known_cpu_khz = x86_init.hyper.get_cpu_khz (); +if (cc_platform_has (CC_ATTR_GUEST_SNP_SECURE_TSC )) known_tsc_khz =snp_secure_tsc_init ();else if (boot_cpu_has (X86_FEATURE_TDX_GUEST )) known_tsc_khz =tdx_tsc_init (); +/* +* If the TSC frequency wasn't provided by trusted firmware, try to get +* it from the hypervisor (which is untrusted when running as a CoCo guest). +*/ +if (!known_tsc_khz && x86_init.hyper.get_tsc_khz) + known_tsc_khz = x86_init.hyper.get_tsc_khz (); +/* * Ignore the user-provided TSC frequency if the exact frequency was -* obtained from trusted firmware, as the user-provided frequency is -* intended as a "starting point", not a known, guaranteed frequency. +* obtained from trusted firmware or the hypervisor, as the user- +* provided frequency is intended as a "starting point", not a known, +* guaranteed frequency. */ if (!known_tsc_khz) known_tsc_khz = tsc_early_khz;else if (tsc_early_khz) -pr_err ("Ignoring 'tsc_early_khz' in favor of trusted firmware.\n" ); +pr_err ("Ignoring 'tsc_early_khz' in favor of firmware/hypervisor.\n" ); -if (!determine_cpu_tsc_frequencies (true, known_tsc_khz)) +if (!determine_cpu_tsc_frequencies (true, known_cpu_khz, known_tsc_khz))return ;tsc_enable_sched_clock (); }
@@ -1558,7 +1573,7 @@ void __init tsc_init(void)if (!tsc_khz) {/* We failed to determine frequencies earlier, try again */ -if (!determine_cpu_tsc_frequencies (false,0 )) { +if (!determine_cpu_tsc_frequencies (false,0 ,0 )) {mark_tsc_unstable ("could not calculate TSC khz" );setup_clear_cpu_cap (X86_FEATURE_TSC_DEADLINE_TIMER );return ;
arch/x86/xen/time.c +2 -2
@@ -38,7 +38,7 @@static u64 xen_sched_clock_offset__read_mostly ;/* Get the TSC speed from Xen */ -static unsigned long xen_tsc_khz (void ) +static unsigned int __init xen_tsc_khz (void ) {struct pvclock_vcpu_time_info *info = &HYPERVISOR_shared_info->vcpu_info[0 ].time;
@@ -569,7 +569,7 @@ static void __init xen_init_time_common(void)static_call_update (pv_steal_clock, xen_steal_clock);paravirt_set_sched_clock (xen_sched_clock); - x86_platform.calibrate_tsc = xen_tsc_khz; + x86_init.hyper.get_tsc_khz = xen_tsc_khz; x86_platform.get_wallclock = xen_get_wallclock; }
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Re: [PATCH v6 11/51] x86/tsc: Add dedicated hypervisor hooks for getting known TSC/CPU frequencies
Quoted 14 lines · Sean Christopherson
Add dedicated hypervisor hooks for getting known TSC/CPU frequencies instead of overriding seemingly generic platform hooks, and explicitly prioritize hypervisor-provided frequencies over native methods, but do NOT clobber the frequency obtained from trusted firmware. While shuffling the hooks around is arguably "six of one, half dozen of the other", scoping them to
x86_hyper_initmakes their purpose more obvious, and allows for explicitly defining the priority of sources (as is done here).As is already done when trusted firmware provides the TSC frequency, ignore
tsc_early_khzif the exact TSC frequency was obtained from the hypervisor, as attempting to refine the TSC frequency when running in a VM is all but guaranteed to cause problems sooner or later due to the calibration sources being emulated devices in the vast majority of setups.
Quoted 3 lines
Cc David Woodhouse <[email protected]>Reviewed-by Michael Kelley <[email protected]>Signed-off-by Sean Christopherson <[email protected]>
Sean Christopherson
maintainerPATCH v6 12/51 x86/acrn: Register TSC/CPU frequency callbacks iff frequency is actually in CPUID
In reply to Sean ChristophersonRegister ACRN's TSC/CPU frequency overrides if and only if the exact TSC frequency is actually provided in CPUID. This will allow marking the TSC as reliable as appropriate, and avoids relying on the caller to handle "failure".
For all intents and purposes, no functional change intended.
--- arch/x86/kernel/cpu/acrn.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
arch/x86/kernel/cpu/acrn.c +9 -3
@@ -19,6 +19,8 @@#include <asm/idtentry.h> #include <asm/irq_regs.h> +static unsigned int acrn_tsc_khz_cpuid__initdata ; +static u32 __init acrn_detect (void ) {return acrn_cpuid_base ();
@@ -26,13 +28,19 @@ static u32 __init acrn_detect(void)static unsigned int __init acrn_get_tsc_khz (void ) { -return cpuid_eax (ACRN_CPUID_TIMING_INFO ); +return acrn_tsc_khz_cpuid; }static void __init acrn_init_platform (void ) {/* Install system interrupt handler for ACRN hypervisor callback */ sysvec_install (HYPERVISOR_CALLBACK_VECTOR , sysvec_acrn_hv_callback); + + acrn_tsc_khz_cpuid =cpuid_eax (ACRN_CPUID_TIMING_INFO ); +if (acrn_tsc_khz_cpuid) { + x86_init.hyper.get_tsc_khz = acrn_get_tsc_khz; + x86_init.hyper.get_cpu_khz = acrn_get_tsc_khz; + } }static bool acrn_x2apic_available (void )
@@ -80,6 +88,4 @@ const __initconst struct hypervisor_x86 x86_hyper_acrn = { .type = X86_HYPER_ACRN, .init.init_platform = acrn_init_platform, .init.x2apic_available = acrn_x2apic_available, - .init.get_tsc_khz = acrn_get_tsc_khz, - .init.get_cpu_khz = acrn_get_tsc_khz, };
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Re: [PATCH v6 12/51] x86/acrn: Register TSC/CPU frequency callbacks iff frequency is actually in CPUID
Quoted 8 lines · Sean Christopherson
Register ACRN's TSC/CPU frequency overrides if and only if the exact TSC frequency is actually provided in CPUID. This will allow marking the TSC as reliable as appropriate, and avoids relying on the caller to handle "failure".
For all intents and purposes, no functional change intended.
Signed-off-by Sean Christopherson <[email protected]>
Sean Christopherson
maintainerPATCH v6 13/51 x86/acrn: Mark TSC frequency as known when using ACRN for calibration
In reply to Sean ChristophersonMark the TSC frequency as known when using ACRN's PV CPUID information. Per commit 81a71f51b89e ("x86/acrn: Set up timekeeping") and common sense, the TSC freq is explicitly provided by the hypervisor.
--- arch/x86/kernel/cpu/acrn.c | 1 + 1 file changed, 1 insertion(+)
arch/x86/kernel/cpu/acrn.c +1 -0
@@ -40,6 +40,7 @@ static void __init acrn_init_platform(void)if (acrn_tsc_khz_cpuid) { x86_init.hyper.get_tsc_khz = acrn_get_tsc_khz; x86_init.hyper.get_cpu_khz = acrn_get_tsc_khz; +setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ ); } }
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Re: [PATCH v6 13/51] x86/acrn: Mark TSC frequency as known when using ACRN for calibration
Quoted 5 lines · Sean Christopherson
Mark the TSC frequency as known when using ACRN's PV CPUID information. Per commit
81a71f51b89e("x86/acrn: Set up timekeeping") and common sense, the TSC freq is explicitly provided by the hypervisor.Signed-off-by Sean Christopherson <[email protected]>
Huh... does this literally get reverted completely in the very *next* patch in the series? Kind of weird, but I guess in some ways it makes sense...
Sean Christopherson
maintainerRe: [PATCH v6 13/51] x86/acrn: Mark TSC frequency as known when using ACRN for calibration
Quoted 10 lines · David Woodhouse
Quoted 5 lines · Sean Christopherson
Mark the TSC frequency as known when using ACRN's PV CPUID information. Per commit
81a71f51b89e("x86/acrn: Set up timekeeping") and common sense, the TSC freq is explicitly provided by the hypervisor.Signed-off-by Sean Christopherson <[email protected]>Huh... does this literally get reverted completely in the very *next* patch in the series? Kind of weird, but I guess in some ways it makes sense...
The literal code gets reverted, but the functional change does not. Before this change, ACRN is the only guest-side PV code that doesn't set X86_FEATURE_TSC_KNOWN_FREQ when the hypervisor provides the exact frequency. I.e. this patch allows for making the "No functional change intended" claim in the next patch.
Sean Christopherson
maintainerPATCH v6 14/51 x86/tsc: Consolidate forcing of X86_FEATURE_TSC_KNOWN_FREQ for PV code
In reply to Sean ChristophersonNow that all paravirt code that explicitly specifies the TSC frequency also sets X86_FEATURE_TSC_KNOWN_FREQ, replace all of the one-off code and simply set X86_FEATURE_TSC_KNOWN_FREQ if the TSC frequency is known.
Do NOT force set TSC_KNOWN_FREQ if the "known" TSC frequency was provided by the user. Per commit bd35c77e32e4 ("x86/tsc: Add tsc_early_khz command line parameter"), one of the goals of the param is to allow the refined calibration work "to do meaningful error checking".
No functional change intended.
--- arch/x86/coco/sev/core.c | 1 - arch/x86/coco/tdx/tdx.c | 1 - arch/x86/kernel/cpu/acrn.c | 1 - arch/x86/kernel/cpu/mshyperv.c | 1 - arch/x86/kernel/cpu/vmware.c | 2 -- arch/x86/kernel/jailhouse.c | 1 - arch/x86/kernel/kvmclock.c | 1 - arch/x86/kernel/tsc.c | 13 ++++++++++--- arch/x86/xen/time.c | 1 - 9 files changed, 10 insertions(+), 12 deletions(-)
arch/x86/coco/sev/core.c +0 -1
@@ -2027,7 +2027,6 @@ unsigned int __init snp_secure_tsc_init(void) secrets = (__force struct snp_secrets_page *)mem; -setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ );setup_force_cpu_cap (X86_FEATURE_TSC_RELIABLE );rdmsrq (MSR_AMD64_GUEST_TSC_FREQ , tsc_freq_mhz);
arch/x86/coco/tdx/tdx.c +0 -1
@@ -1203,7 +1203,6 @@ unsigned int __init tdx_tsc_init(void)/* TSC is the only reliable clock in TDX guest */ setup_force_cpu_cap (X86_FEATURE_TSC_RELIABLE ); -setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ );return info.crystal_khz * info.numerator / info.denominator; }
arch/x86/kernel/cpu/acrn.c +0 -1
@@ -40,7 +40,6 @@ static void __init acrn_init_platform(void)if (acrn_tsc_khz_cpuid) { x86_init.hyper.get_tsc_khz = acrn_get_tsc_khz; x86_init.hyper.get_cpu_khz = acrn_get_tsc_khz; -setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ ); } }
arch/x86/kernel/cpu/mshyperv.c +0 -1
@@ -575,7 +575,6 @@ static void __init ms_hyperv_init_platform(void) ms_hyperv.misc_features & HV_FEATURE_FREQUENCY_MSRS_AVAILABLE) { x86_init.hyper.get_tsc_khz = hv_get_tsc_khz; x86_init.hyper.get_cpu_khz = hv_get_tsc_khz; -setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ ); }if (ms_hyperv.priv_high &HV_ISOLATION ) {
arch/x86/kernel/cpu/vmware.c +0 -2
@@ -390,8 +390,6 @@ static void __init vmware_set_capabilities(void) {setup_force_cpu_cap (X86_FEATURE_CONSTANT_TSC );setup_force_cpu_cap (X86_FEATURE_TSC_RELIABLE ); -if (vmware_tsc_khz) -setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ );if (vmware_hypercall_mode ==CPUID_VMWARE_FEATURES_ECX_VMCALL )setup_force_cpu_cap (X86_FEATURE_VMCALL );else if (vmware_hypercall_mode ==CPUID_VMWARE_FEATURES_ECX_VMMCALL )
arch/x86/kernel/jailhouse.c +0 -1
@@ -255,7 +255,6 @@ static void __init jailhouse_init_platform(void)pr_debug ("Jailhouse: PM-Timer IO Port: %#x\n" , pmtmr_ioport); precalibrated_tsc_khz = setup_data.v1.tsc_khz; -setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ ); pci_probe =0 ;
arch/x86/kernel/kvmclock.c +0 -1
@@ -138,7 +138,6 @@ static inline void kvm_sched_clock_init(bool stable)*/ static unsigned int __init kvm_get_tsc_khz (void ) { -setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ );return pvclock_tsc_khz (this_cpu_pvti ()); }
arch/x86/kernel/tsc.c +10 -3
@@ -1541,11 +1541,18 @@ void __init tsc_early_init(void)if (!known_tsc_khz && x86_init.hyper.get_tsc_khz) known_tsc_khz = x86_init.hyper.get_tsc_khz (); +/* +* Mark the TSC frequency as known if it was obtained from a hypervisor +* or trusted firmware. +*/ +if (known_tsc_khz) +setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ ); +/* * Ignore the user-provided TSC frequency if the exact frequency was -* obtained from trusted firmware or the hypervisor, as the user- -* provided frequency is intended as a "starting point", not a known, -* guaranteed frequency. +* obtained from trusted firmware or the hypervisor, and don't mark the +* frequency as known, as the user-provided frequency is intended as a +* "starting point", not a known, guaranteed frequency */ if (!known_tsc_khz) known_tsc_khz = tsc_early_khz;
arch/x86/xen/time.c +0 -1
@@ -43,7 +43,6 @@ static unsigned int __init xen_tsc_khz(void)struct pvclock_vcpu_time_info *info = &HYPERVISOR_shared_info->vcpu_info[0 ].time; -setup_force_cpu_cap (X86_FEATURE_TSC_KNOWN_FREQ );return pvclock_tsc_khz (info); }
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Re: [PATCH v6 14/51] x86/tsc: Consolidate forcing of X86_FEATURE_TSC_KNOWN_FREQ for PV code
Quoted 9 lines · Sean Christopherson
Now that all paravirt code that explicitly specifies the TSC frequency also sets
X86_FEATURE_TSC_KNOWN_FREQ, replace all of the one-off code and simply setX86_FEATURE_TSC_KNOWN_FREQif the TSC frequency is known.Do NOT force set
TSC_KNOWN_FREQif the "known" TSC frequency was provided by the user. Per commitbd35c77e32e4("x86/tsc: Addtsc_early_khzcommand line parameter"), one of the goals of the param is to allow the refined calibration work "to do meaningful error checking".
Quoted 4 lines
No functional change intended.
Reviewed-by Michael Kelley <[email protected]>Signed-off-by Sean Christopherson <[email protected]>
Sean Christopherson
maintainerPATCH v6 15/51 x86/tsc: Kill off x86_platform_ops.calibrate_{cpu,tsc}() hooks
In reply to Sean ChristophersonNow that getting the CPU and/or TSC frequencies from the hypervisor uses dedicated hooks, drop x86_platform_ops.calibrate_{cpu,tsc}() and instead directly invoke the correct helper at each phase of (re)calibration. In addition to eliminating unnecessary code, this makes it a bit more obvious when the "late" path invokes pit_hpet_ptimer_calibrate_cpu() instead of x86_platform_ops.calibrate_cpu().
No functional change intended.
--- arch/x86/include/asm/tsc.h | 2 -- arch/x86/include/asm/x86_init.h | 4 ---- arch/x86/kernel/tsc.c | 28 ++++++++++++---------------- arch/x86/kernel/x86_init.c | 2 -- 4 files changed, 12 insertions(+), 24 deletions(-)
arch/x86/include/asm/tsc.h +0 -2
@@ -95,8 +95,6 @@ extern void mark_tsc_unstable(char *reason);extern int unsynchronized_tsc (void );extern int check_tsc_unstable (void );extern void mark_tsc_async_resets (char *reason); -extern unsigned long native_calibrate_cpu_early (void ); -extern unsigned long native_calibrate_tsc (void );extern unsigned long long native_sched_clock_from_tsc (u64 tsc);extern int tsc_clocksource_reliable;
arch/x86/include/asm/x86_init.h +0 -4
@@ -295,8 +295,6 @@ struct x86_hyper_runtime {/** * struct x86_platform_ops - platform specific runtime functions -* @calibrate_cpu: calibrate CPU -* @calibrate_tsc: calibrate TSC, if different from CPU * @get_wallclock: get time from HW clock like RTC etc. * @set_wallclock: set time back to HW clock * @iommu_shutdown: set by an IOMMU driver for shutdown if necessary
@@ -320,8 +318,6 @@ struct x86_hyper_runtime {* @guest: guest incarnations callbacks */ struct x86_platform_ops { -unsigned long (*calibrate_cpu)(void ); -unsigned long (*calibrate_tsc)(void );void (*get_wallclock)(struct timespec64 *ts);int (*set_wallclock)(const struct timespec64 *ts);void (*iommu_shutdown)(void );
arch/x86/kernel/tsc.c +12 -16
@@ -672,7 +672,7 @@ int cpuid_get_tsc_info(struct cpuid_tsc_info *info)* native_calibrate_tsc - determine TSC frequency * Determine TSC frequency via CPUID, else return 0. */ -unsigned long native_calibrate_tsc (void ) +static unsigned long native_calibrate_tsc (void ) {struct cpuid_tsc_info info;
@@ -904,7 +904,7 @@ static unsigned long pit_hpet_ptimer_calibrate_cpu(void)/** * native_calibrate_cpu_early - can calibrate the cpu early in boot */ -unsigned long native_calibrate_cpu_early (void ) +static unsigned long native_calibrate_cpu_early (void ) {unsigned long flags, fast_calibrate =cpu_khz_from_cpuid ();
@@ -918,7 +918,7 @@ unsigned long native_calibrate_cpu_early(void)return fast_calibrate; } - +#ifndef CONFIG_SMP /** * native_calibrate_cpu - calibrate the cpu */
@@ -931,6 +931,7 @@ static unsigned long native_calibrate_cpu(void) return tsc_freq; } +#endif void recalibrate_cpu_khz (void ) {
@@ -943,8 +944,8 @@ void recalibrate_cpu_khz(void)if (WARN_ON_ONCE (cpu_feature_enabled (X86_FEATURE_TSC_KNOWN_FREQ )))return ; - cpu_khz = x86_platform.calibrate_cpu (); - tsc_khz = x86_platform.calibrate_tsc (); + cpu_khz =native_calibrate_cpu (); + tsc_khz =native_calibrate_tsc ();if (tsc_khz ==0 ) tsc_khz = cpu_khz;else if (abs (cpu_khz - tsc_khz) *10 > tsc_khz)
@@ -1458,17 +1459,19 @@ static bool __init determine_cpu_tsc_frequencies(bool early,WARN_ON (cpu_khz || tsc_khz);if (early) { +/* +* Early CPU calibration can only use methods that are available +* early in boot (obviously). +*/ if (known_cpu_khz) cpu_khz = known_cpu_khz;else - cpu_khz = x86_platform.calibrate_cpu (); + cpu_khz =native_calibrate_cpu_early ();if (known_tsc_khz) tsc_khz = known_tsc_khz;else - tsc_khz = x86_platform.calibrate_tsc (); + tsc_khz =native_calibrate_tsc (); }else { -/* We should not be here with non-native cpu calibration */ -WARN_ON (x86_platform.calibrate_cpu != native_calibrate_cpu); cpu_khz =pit_hpet_ptimer_calibrate_cpu (); }
@@ -1571,13 +1574,6 @@ void __init tsc_init(void)return ; } -/* -* native_calibrate_cpu_early can only calibrate using methods that are -* available early in boot. -*/ -if (x86_platform.calibrate_cpu == native_calibrate_cpu_early) - x86_platform.calibrate_cpu = native_calibrate_cpu; -if (!tsc_khz) {/* We failed to determine frequencies earlier, try again */ if (!determine_cpu_tsc_frequencies (false,0 ,0 )) {
arch/x86/kernel/x86_init.c +0 -2
@@ -147,8 +147,6 @@ static void enc_kexec_finish_noop(void) {}static bool is_private_mmio_noop (u64 addr) {return false; }struct x86_platform_ops x86_platform__ro_after_init = { - .calibrate_cpu = native_calibrate_cpu_early, - .calibrate_tsc = native_calibrate_tsc, .get_wallclock = mach_get_cmos_time, .set_wallclock = mach_set_cmos_time, .iommu_shutdown = iommu_shutdown_noop,
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Re: [PATCH v6 15/51] x86/tsc: Kill off x86_platform_ops.calibrate_{cpu,tsc}() hooks
Quoted 10 lines · Sean Christopherson
Now that getting the CPU and/or TSC frequencies from the hypervisor uses dedicated hooks, drop x86_platform_ops.calibrate_{cpu,tsc}() and instead directly invoke the correct helper at each phase of (re)calibration. In addition to eliminating unnecessary code, this makes it a bit more obvious when the "late" path invokes
pit_hpet_ptimer_calibrate_cpu()instead ofx86_platform_ops.calibrate_cpu().No functional change intended.
Signed-off-by Sean Christopherson <[email protected]>
Sean Christopherson
maintainerPATCH v6 16/51 x86/tsc: Rename pit_hpet_ptimer_calibrate_cpu() => native_calibrate_cpu_late()
In reply to Sean ChristophersonRename the late CPU calibration routine so that its relationship to the early routine is more obvious and intuitive.
No functional change intended.
--- arch/x86/kernel/tsc.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
arch/x86/kernel/tsc.c +3 -3
@@ -752,7 +752,7 @@ static unsigned long cpu_khz_from_cpuid(void)* calibrate cpu using pit, hpet, and ptimer methods. They are available * later in boot after acpi is initialized. */ -static unsigned long pit_hpet_ptimer_calibrate_cpu (void ) +static unsigned long native_calibrate_cpu_late (void ) {u64 tsc1, tsc2, delta, ref1, ref2;unsigned long tsc_pit_min =ULONG_MAX , tsc_ref_min =ULONG_MAX ;
@@ -927,7 +927,7 @@ static unsigned long native_calibrate_cpu(void)unsigned long tsc_freq =native_calibrate_cpu_early ();if (!tsc_freq) - tsc_freq =pit_hpet_ptimer_calibrate_cpu (); + tsc_freq =native_calibrate_cpu_late ();return tsc_freq; }
@@ -1472,7 +1472,7 @@ static bool __init determine_cpu_tsc_frequencies(bool early,else tsc_khz =native_calibrate_tsc (); }else { - cpu_khz =pit_hpet_ptimer_calibrate_cpu (); + cpu_khz =native_calibrate_cpu_late (); }/*
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 17/51 x86/tsc: Fold native_calibrate_cpu() into recalibrate_cpu_khz()
In reply to Sean ChristophersonFold the guts of native_calibrate_cpu() into its sole remaining caller, recalibrate_cpu_khz() to eliminate the extra SMP=n #ifdef, and so that it's more obvious that directly invoking the early vs. late calibration routines in determine_cpu_tsc_frequencies() is intentional.
No functional change intended.
--- arch/x86/kernel/tsc.c | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-)
arch/x86/kernel/tsc.c +3 -16
@@ -918,21 +918,6 @@ static unsigned long native_calibrate_cpu_early(void)return fast_calibrate; } -#ifndef CONFIG_SMP -/** -* native_calibrate_cpu - calibrate the cpu -*/ -static unsigned long native_calibrate_cpu (void ) -{ -unsigned long tsc_freq =native_calibrate_cpu_early (); - -if (!tsc_freq) - tsc_freq =native_calibrate_cpu_late (); - -return tsc_freq; -} -#endif -void recalibrate_cpu_khz (void ) {#ifndef CONFIG_SMP
@@ -944,7 +929,9 @@ void recalibrate_cpu_khz(void)if (WARN_ON_ONCE (cpu_feature_enabled (X86_FEATURE_TSC_KNOWN_FREQ )))return ; - cpu_khz =native_calibrate_cpu (); + cpu_khz =native_calibrate_cpu_early (); +if (!cpu_khz) + cpu_khz =native_calibrate_cpu_late (); tsc_khz =native_calibrate_tsc ();if (tsc_khz ==0 ) tsc_khz = cpu_khz;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Re: [PATCH v6 17/51] x86/tsc: Fold native_calibrate_cpu() into recalibrate_cpu_khz()
Quoted 8 lines · Sean Christopherson
Fold the guts of
native_calibrate_cpu()into its sole remaining caller,recalibrate_cpu_khz()to eliminate the extra SMP=n #ifdef, and so that it's more obvious that directly invoking the early vs. late calibration routines indetermine_cpu_tsc_frequencies()is intentional.No functional change intended.
Signed-off-by Sean Christopherson <[email protected]>
Sean Christopherson
maintainerPATCH v6 18/51 x86/kvmclock: Rename kvm_get_tsc_khz() to kvmclock_get_tsc_khz()
In reply to Sean ChristophersonRename kvm_get_tsc_khz() to kvmclock_get_tsc_khz() in anticipation of adding support for getting TSC info from PV CPUID, i.e. in a KVM specific way, but without non-kvmclock.
No functional change intended.
--- arch/x86/kernel/kvmclock.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
arch/x86/kernel/kvmclock.c +4 -4
@@ -136,7 +136,7 @@ static inline void kvm_sched_clock_init(bool stable)* poll of guests can be running and trouble each other. So we preset * lpj here */ -static unsigned int __init kvm_get_tsc_khz (void ) +static unsigned int __init kvmclock_get_tsc_khz (void ) {return pvclock_tsc_khz (this_cpu_pvti ()); }
@@ -146,7 +146,7 @@ static void __init kvm_get_preset_lpj(void)unsigned long khz;u64 lpj; - khz =kvm_get_tsc_khz (); + khz =kvmclock_get_tsc_khz (); lpj = ((u64 )khz *1000 );do_div (lpj,HZ );
@@ -342,8 +342,8 @@ void __init kvmclock_init(void) flags =pvclock_read_flags (&hv_clock_boot[0 ].pvti);kvm_sched_clock_init (flags &PVCLOCK_TSC_STABLE_BIT ); - x86_init.hyper.get_tsc_khz = kvm_get_tsc_khz; - x86_init.hyper.get_cpu_khz = kvm_get_tsc_khz; + x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz; + x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; x86_platform.get_wallclock = kvm_get_wallclock; x86_platform.set_wallclock = kvm_set_wallclock;#ifdef CONFIG_X86_LOCAL_APIC
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 19/51 x86/kvmclock: Drop dead check on TSC being unstable during kvmclock_init()
In reply to Sean ChristophersonAs pointed out by Sashiko[*], kvmclock_init() runs before __setup() and thus before notsc_setup() or tsc_setup() can mark the TSC unstable. kvmclock_init() also runs well before tsc_init(), and even before tsc_early_init(). Simply delete the check, as it's been dead code since it was introduced.
Note, odds are good the check_tsc_unstable() call was copied from Xen's xen_time_init()+xen_tsc_safe_clocksource() logic (as so much of KVM's PV code was). However, xen_time_init() runs via x86_init.timers.timer_init(), which is invoke from x86_late_time_init(), and thus after params have been parsed.
Alternatively, kvmclock could register itself later on, or tsc_setup() could be parsed as an early param. Given that there's zero evidence there was any meaningful intent or need to actually check for an unstable TSC, go with the simplest option.
--- arch/x86/kernel/kvmclock.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
arch/x86/kernel/kvmclock.c +1 -2
@@ -362,8 +362,7 @@ void __init kvmclock_init(void)* */ if (boot_cpu_has (X86_FEATURE_CONSTANT_TSC ) && -boot_cpu_has (X86_FEATURE_NONSTOP_TSC ) && - !check_tsc_unstable ()) +boot_cpu_has (X86_FEATURE_NONSTOP_TSC )) kvm_clock.rating =299 ;clocksource_register_hz (&kvm_clock,NSEC_PER_SEC );
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Re: [PATCH v6 19/51] x86/kvmclock: Drop dead check on TSC being unstable during kvmclock_init()
Quoted 12 lines · Sean Christopherson
As pointed out by Sashiko[*],
kvmclock_init()runs before__setup()and thus beforenotsc_setup()ortsc_setup()can mark the TSC unstable.kvmclock_init()also runs well beforetsc_init(), and even beforetsc_early_init(). Simply delete the check, as it's been dead code since it was introduced.Note, odds are good the
check_tsc_unstable()call was copied from Xen's xen_time_init()+xen_tsc_safe_clocksource() logic (as so much of KVM's PV code was). However,xen_time_init()runs viax86_init.timers.timer_init(), which is invoke fromx86_late_time_init(), and thus after params have been parsed.
Quoted 8 lines
Alternatively, kvmclock could register itself later on, or
tsc_setup()could be parsed as an early param. Given that there's zero evidence there was any meaningful intent or need to actually check for an unstable TSC, go with the simplest option.Fixes 7539b174aef4 ("x86: kvmguest: use TSC clocksource if invariant TSC is exposed")Signed-off-by Sean Christopherson <[email protected]>
Sean Christopherson
maintainerPATCH v6 20/51 KVM: x86: Officially define CPUID 0x40000010 as PV Timing Info (TSC and Bus)
In reply to Sean ChristophersonFrom: David Woodhouse <[email protected]>
Formally define and document CPUID 0x40000010 as providing TSC and local APIC bus frequency information for KVM's PV CPUID range. Way back in 2008, VMware proposed (https://lkml.org/lkml/2008/10/1/246) carving out a range of CPUID leaves for use by hypervisors. While the broader proposal from VMware was mostly shot down in flames, use of CPUID 0x40000010 to provide TSC and local APIC bus frequency information survived and made it's way into multiple guest operating systems.
XNU unconditionally assumes CPUID 0x40000010 contains the frequency information, if it's present on any hypervisor:
https://github.com/apple/darwin-xnu/blob/main/osfmk/i386/cpuid.c
As does FreeBSD:
https://github.com/freebsd/freebsd-src/commit/4a432614f68
More importantly, QEMU (the de facto "reference" VMM for KVM) has conditionally provided timing information in CPUID 0x40000010 for almost 9 years, since commit 9954a1582e ("x86-KVM: Supply TSC and APIC clock rates to guest like VMWare").
So at this point it would be daft for KVM (or any hypervisor) to expose 0x40000010 for any *other* content. Officially carve out and define the CPUID leaf so that Linux-as-a-guest can follow suit and pull TSC and Local APIC Bus frequency information from CPUID.
Defer providing userspace with the necessary information needed to precisely and accurately enumerate the _actual_ configured TSC frequency to the guest (that exact information, along with the scaled ratio, isn't exposed to userspace). As evidenced by QEMU, providing CPUID 0x40000010 without help from KVM is entirely possible, just not ideal.
--- Documentation/virt/kvm/x86/cpuid.rst | 12 ++++++++++++ arch/x86/include/uapi/asm/kvm_para.h | 11 +++++++++++ 2 files changed, 23 insertions(+)
Documentation/virt/kvm/x86/cpuid.rst +12 -0
@@ -122,3 +122,15 @@ KVM_HINTS_REALTIME 0 guest checks this feature bit to preempted for an unlimited time allowing optimizations ================== ============ ================================= + +function: KVM_CPUID_TIMING_INFO (0x40000010) + +returns:: + + eax = (Virtual) TSC frequency in kHz + ebx = (Virtual) Bus (local APIC timer) frequency in kHz + ecx = 0 (Reserved) + edx = 0 (Reserved) + +Note, KVM only defines the semantics of KVM_CPUID_TIMING_INFO; KVM does NOT +advertise support via KVM_GET_SUPPORTED_CPUID.
arch/x86/include/uapi/asm/kvm_para.h +11 -0
@@ -44,6 +44,17 @@*/ #define KVM_FEATURE_CLOCKSOURCE_STABLE_BIT 24 +/* +* The timing information leaf provides TSC and local APIC timer frequency +* information to the guest. Note, userspace is responsible for filling the +* leaf with the correct information. +* +* # EAX: (Virtual) TSC frequency in kHz. +* # EBX: (Virtual) Bus (local APIC timer) frequency in kHz. +* # ECX, EDX: Reserved (must be zero). +*/ +#define KVM_CPUID_TIMING_INFO 0x40000010 +#define MSR_KVM_WALL_CLOCK 0x11#define MSR_KVM_SYSTEM_TIME 0x12
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 21/51 x86/kvm: Obtain TSC frequency from PV CPUID if present
In reply to Sean ChristophersonFrom: David Woodhouse <[email protected]>
In https://lkml.org/lkml/2008/10/1/246 a proposal was made for generic CPUID conventions across hypervisors. It was mostly shot down in flames, but the leaf at 0x40000010 containing timing information didn't die.
It's used by XNU and FreeBSD guests under all hypervisors¹² to determine the TSC frequency, and also exposed by the EC2 Nitro hypervisor (as well as, presumably, VMware). FreeBSD's Bhyve is probably just about to start exposing it too.
Use it under KVM to obtain the TSC frequency more accurately, instead of reverse-calculating the frequency from the mul/shift values in the KVM clock. Use the information to get the CPU frequency as well (kvmclock feeds in kvm_get_tsc_khz() for both TSC and CPU calibration), as the info from CPUID is superior in every way; whether or not kvmclock should be overriding CPU calibration in the first place is an entirely different question.
Use the info from CPUID even if the user explicitly disables kvmclock, or if it's unsupported. The PV CPUID leaf has no dependency on kvmclock, and is in fact more useful if kvmclock is disabled since the kernel won't be able to use kvmclock to derive a derive the TSC frequency.
Before:
[ 0.000020] tsc: Detected 2900.014 MHz processor
After:
[ 0.000020] tsc: Detected 2900.015 MHz processor
$ cpuid -1 -l 0x40000010
CPU:
hypervisor generic timing information (0x40000010):
TSC frequency (Hz) = 2900015
bus frequency (Hz) = 1000000Note! *Independently* query for non-null get_{cpu,tsc}_khz() overrides so that kvmclock doesn't clobber x86_init.hyper.get_cpu_khz() if/when KVM adds support for getting the CPU frequency separately from the TSC frequency.
¹ https://github.com/apple/darwin-xnu/blob/main/osfmk/i386/cpuid.c
² https://github.com/freebsd/freebsd-src/commit/4a432614f68
--- arch/x86/kernel/kvm.c | 33 +++++++++++++++++++++++++++++++++ arch/x86/kernel/kvmclock.c | 6 ++++-- 2 files changed, 37 insertions(+), 2 deletions(-)
arch/x86/kernel/kvm.c +33 -0
@@ -49,6 +49,8 @@#include <asm/svm.h> #include <asm/e820/api.h> +static unsigned int kvm_tsc_khz_cpuid__initdata ; +DEFINE_STATIC_KEY_FALSE_RO (kvm_async_pf_enabled);static int kvmapf =1 ;
@@ -913,6 +915,21 @@ bool kvm_para_available(void) }EXPORT_SYMBOL_GPL (kvm_para_available); +static u32 __init kvm_cpuid_timing_info_leaf (void ) +{ +u32 base =kvm_cpuid_base (); + +if (!base ||cpuid_eax (base) < (base |KVM_CPUID_TIMING_INFO )) +return 0 ; + +return base |KVM_CPUID_TIMING_INFO ; +} + +static unsigned int __init kvm_get_tsc_khz (void ) +{ +return kvm_tsc_khz_cpuid; +} +unsigned int kvm_arch_para_features (void ) {return cpuid_eax (kvm_cpuid_base () |KVM_CPUID_FEATURES );
@@ -962,6 +979,7 @@ static void __init kvm_init_platform(void) .mask_lo = (u32)(~(SZ_4G - tolud - 1)) | MTRR_PHYSMASK_V, .mask_hi = (BIT_ULL(boot_cpu_data.x86_phys_bits) - 1) >> 32, }; +u32 timing_info_leaf;if (cc_platform_has (CC_ATTR_GUEST_MEM_ENCRYPT ) &&kvm_para_has_feature (KVM_FEATURE_MIGRATION_CONTROL )) {
@@ -1009,6 +1027,21 @@ static void __init kvm_init_platform(void)wrmsrq (MSR_KVM_MIGRATION_CONTROL ,KVM_MIGRATION_READY ); } + +/* +* If KVM advertises the frequency directly in CPUID, use that instead +* of reverse-calculating it from the KVM clock data, or worse, trying +* to calibratate the TSC using an emulated device. +*/ + timing_info_leaf =kvm_cpuid_timing_info_leaf (); +if (timing_info_leaf) { + kvm_tsc_khz_cpuid =cpuid_eax (timing_info_leaf); +if (kvm_tsc_khz_cpuid) { + x86_init.hyper.get_tsc_khz = kvm_get_tsc_khz; + x86_init.hyper.get_cpu_khz = kvm_get_tsc_khz; + } + } +kvmclock_init (); x86_platform.apic_post_init = kvm_apic_init;
arch/x86/kernel/kvmclock.c +4 -2
@@ -342,8 +342,10 @@ void __init kvmclock_init(void) flags =pvclock_read_flags (&hv_clock_boot[0 ].pvti);kvm_sched_clock_init (flags &PVCLOCK_TSC_STABLE_BIT ); - x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz; - x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; +if (!x86_init.hyper.get_tsc_khz) + x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz; +if (!x86_init.hyper.get_cpu_khz) + x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; x86_platform.get_wallclock = kvm_get_wallclock; x86_platform.set_wallclock = kvm_set_wallclock;#ifdef CONFIG_X86_LOCAL_APIC
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Re: [PATCH v6 21/51] x86/kvm: Obtain TSC frequency from PV CPUID if present
Quoted 123 lines · Sean Christopherson
From: David Woodhouse <[email protected]>
In https://lkml.org/lkml/2008/10/1/246 a proposal was made for generic CPUID conventions across hypervisors. It was mostly shot down in flames, but the leaf at
0x40000010containing timing information didn't die.It's used by XNU and FreeBSD guests under all hypervisors¹² to determine the TSC frequency, and also exposed by the EC2 Nitro hypervisor (as well as, presumably, VMware). FreeBSD's Bhyve is probably just about to start exposing it too.
Use it under KVM to obtain the TSC frequency more accurately, instead of reverse-calculating the frequency from the mul/shift values in the KVM clock. Use the information to get the CPU frequency as well (kvmclock feeds in
kvm_get_tsc_khz()for both TSC and CPU calibration), as the info from CPUID is superior in every way; whether or not kvmclock should be overriding CPU calibration in the first place is an entirely different question.Use the info from CPUID even if the user explicitly disables kvmclock, or if it's unsupported. The PV CPUID leaf has no dependency on kvmclock, and is in fact more useful if kvmclock is disabled since the kernel won't be able to use kvmclock to derive a derive the TSC frequency.
Before:
[ 0.000020] tsc: Detected 2900.014 MHz processorAfter:
[ 0.000020] tsc: Detected 2900.015 MHz processor$ cpuid -1 -l 0x40000010 CPU: hypervisor generic timing information (0x40000010): TSC frequency (Hz) = 2900015 bus frequency (Hz) = 1000000Note! *Independently* query for non-null get_{cpu,tsc}_khz() overrides so that kvmclock doesn't clobber
x86_init.hyper.get_cpu_khz()if/when KVM adds support for getting the CPU frequency separately from the TSC frequency.¹ https://github.com/apple/darwin-xnu/blob/main/osfmk/i386/cpuid.c
² https://github.com/freebsd/freebsd-src/commit/4a432614f68Signed-off-by David Woodhouse <[email protected]>Co-developed-by Sean Christopherson <[email protected]>Signed-off-by Sean Christopherson <[email protected]>--- arch/x86/kernel/kvm.c | 33 +++++++++++++++++++++++++++++++++ arch/x86/kernel/kvmclock.c | 6 ++++-- 2 files changed, 37 insertions(+), 2 deletions(-)arch/x86/kernel/kvm.c +33
-0@@ -49,6 +49,8 @@#include <asm/svm.h> #include <asm/e820/api.h> +static unsigned int kvm_tsc_khz_cpuid__initdata ; +DEFINE_STATIC_KEY_FALSE_RO (kvm_async_pf_enabled);static int kvmapf =1 ;@@ -913,6 +915,21 @@ bool kvm_para_available(void) }EXPORT_SYMBOL_GPL (kvm_para_available); +static u32 __init kvm_cpuid_timing_info_leaf (void ) +{ +u32 base =kvm_cpuid_base (); + +if (!base ||cpuid_eax (base) < (base |KVM_CPUID_TIMING_INFO )) +return 0 ; + +return base |KVM_CPUID_TIMING_INFO ; +} + +static unsigned int __init kvm_get_tsc_khz (void ) +{ +return kvm_tsc_khz_cpuid; +} +unsigned int kvm_arch_para_features (void ) {return cpuid_eax (kvm_cpuid_base () |KVM_CPUID_FEATURES );@@ -962,6 +979,7 @@ static void __init kvm_init_platform(void) .mask_lo = (u32)(~(SZ_4G - tolud - 1)) | MTRR_PHYSMASK_V, .mask_hi = (BIT_ULL(boot_cpu_data.x86_phys_bits) - 1) >> 32, }; +u32 timing_info_leaf;if (cc_platform_has (CC_ATTR_GUEST_MEM_ENCRYPT ) &&kvm_para_has_feature (KVM_FEATURE_MIGRATION_CONTROL )) {@@ -1009,6 +1027,21 @@ static void __init kvm_init_platform(void)wrmsrq (MSR_KVM_MIGRATION_CONTROL ,KVM_MIGRATION_READY ); } + +/* +* If KVM advertises the frequency directly in CPUID, use that instead +* of reverse-calculating it from the KVM clock data, or worse, trying +* to calibratate the TSC using an emulated device. +*/ + timing_info_leaf =kvm_cpuid_timing_info_leaf (); +if (timing_info_leaf) { + kvm_tsc_khz_cpuid =cpuid_eax (timing_info_leaf); +if (kvm_tsc_khz_cpuid) { + x86_init.hyper.get_tsc_khz = kvm_get_tsc_khz; + x86_init.hyper.get_cpu_khz = kvm_get_tsc_khz; + } + } +kvmclock_init (); x86_platform.apic_post_init = kvm_apic_init;arch/x86/kernel/kvmclock.c +0
-0@@ -342,8 +342,10 @@ void __init kvmclock_init(void) flags =pvclock_read_flags (&hv_clock_boot[0 ].pvti);kvm_sched_clock_init (flags &PVCLOCK_TSC_STABLE_BIT );
arch/x86/kernel/kvmclock.c void __init kvmclock_init(void) · line 351
Quoted 10 lines
arch/x86/kernel/kvmclock.c +4
-2- x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz; - x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; +if (!x86_init.hyper.get_tsc_khz) + x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz; +if (!x86_init.hyper.get_cpu_khz) + x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; x86_platform.get_wallclock = kvm_get_wallclock; x86_platform.set_wallclock = kvm_set_wallclock;#ifdef CONFIG_X86_LOCAL_APIC
I cannot test this right now as I lack two servers with different CPU base frequencies, but it seems that this patch might break something in guests:
After migrating a VM (QEMU + KVM) from a host with one base frequency to another host with a different base frequency, the value in CPUID leaf 0x40000010 EAX changes and becomes the same as the destination host base frequency instead of remaining the source base frequency. The main reason for this behaviour is that setting the TSC frequency via ioctl(KVM_SET_TSC_KHZ) doesn't change the value in CPUID leaf 0x40000010 EAX and these two entities are still not connected.
I saw this behaviour with QEMU 7, but I've checked the code of the latest version and it seems that the described behaviour still exists. So, in that case, it's possible that with these changes a VM will use the wrong TSC frequency from CPUID leaf 0x40000010 EAX if it's migrated and then rebooted.
Putting it all together, after the previous patch ("KVM: x86: Officially define CPUID 0x40000010 as PV Timing Info (TSC and Bus)") a new way to show the guest that CPUID leaf 0x40000010 is valid should be implemented and only then this leaf can be used to get the TSC frequency.
Signature · 2 lines
Best regards, Maksim Davydov
Sean Christopherson
maintainerRe: [PATCH v6 21/51] x86/kvm: Obtain TSC frequency from PV CPUID if present
Quoted 20 lines · Maksim Davydov
Quoted 7 lines · Sean Christopherson
arch/x86/kernel/kvmclock.c +0
-0@@ -342,8 +342,10 @@ void __init kvmclock_init(void) flags =pvclock_read_flags (&hv_clock_boot[0 ].pvti);kvm_sched_clock_init (flags &PVCLOCK_TSC_STABLE_BIT );arch/x86/kernel/kvmclock.c void __init kvmclock_init(void) · line 351
Quoted 10 lines
arch/x86/kernel/kvmclock.c +4
-2- x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz; - x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; +if (!x86_init.hyper.get_tsc_khz) + x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz; +if (!x86_init.hyper.get_cpu_khz) + x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; x86_platform.get_wallclock = kvm_get_wallclock; x86_platform.set_wallclock = kvm_set_wallclock;#ifdef CONFIG_X86_LOCAL_APIC
Quoted 7 lines
I cannot test this right now as I lack two servers with different CPU base frequencies, but it seems that this patch might break something in guests:
After migrating a VM (QEMU + KVM) from a host with one base frequency to another host with a different base frequency, the value in CPUID leaf0x40000010EAX changes and becomes the same as the destination host base frequency instead of remaining the source base frequency.
That's a bug in whatever is orchestrating the migration, and/or QEMU if QEMU is handing the upper layers a loaded footgun.
Quoted 3 lines
The main reason for this behaviour is that setting the TSC frequency via
ioctl(KVM_SET_TSC_KHZ)doesn't change the value in CPUID leaf0x40000010EAX and these two entities are still not connected.
And they never will be. It's userspace's responsibility to fill the correct values for 0x40000010.
But AFAICT, QEMU does the right thing. env->tsc_khz is used for both the CPUID leaf and for KVM_SET_TSC_KHZ.
kvm_arch_init_vcpu():
c = &cpuid_data.entries[cpuid_i++];
c->function = KVM_CPUID_SIGNATURE | 0x10;
c->eax = env->tsc_khz;
c->ebx = env->apic_bus_freq / 1000; /* Hz to KHz */
c->ecx = c->edx = 0;kvm_arch_set_tsc_khz():
r = set_ioctl ?
kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
-ENOTSUP;Quoted 10 lines
I saw this behaviour with QEMU 7, but I've checked the code of the latest version and it seems that the described behaviour still exists. So, in that case, it's possible that with these changes a VM will use the wrong TSC frequency from CPUID leaf
0x40000010EAX if it's migrated and then rebooted.Putting it all together, after the previous patch ("KVM: x86: Officially define CPUID
0x40000010as PV Timing Info (TSC and Bus)") a new way to show the guest that CPUID leaf0x40000010is valid should be implemented and only then this leaf can be used to get the TSC frequency.
No, there are already non-Linux kernels that consume 0x40000010, e.g. FreeBSD. In my very strong opinion, if this problematic for a deployment, then that deployment needs to urgently fix their broken setup.
Re: [PATCH v6 21/51] x86/kvm: Obtain TSC frequency from PV CPUID if present
Quoted 50 lines · Sean Christopherson
Quoted 20 lines · Maksim Davydov
Quoted 7 lines · Sean Christopherson
arch/x86/kernel/kvmclock.c +0
-0@@ -342,8 +342,10 @@ void __init kvmclock_init(void) flags =pvclock_read_flags (&hv_clock_boot[0 ].pvti);kvm_sched_clock_init (flags &PVCLOCK_TSC_STABLE_BIT );arch/x86/kernel/kvmclock.c void __init kvmclock_init(void) · line 351
Quoted 10 lines
arch/x86/kernel/kvmclock.c +4
-2- x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz; - x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; +if (!x86_init.hyper.get_tsc_khz) + x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz; +if (!x86_init.hyper.get_cpu_khz) + x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; x86_platform.get_wallclock = kvm_get_wallclock; x86_platform.set_wallclock = kvm_set_wallclock;#ifdef CONFIG_X86_LOCAL_APIC Quoted 7 lines
I cannot test this right now as I lack two servers with different CPU base frequencies, but it seems that this patch might break something in guests:
After migrating a VM (QEMU + KVM) from a host with one base frequency to another host with a different base frequency, the value in CPUID leaf0x40000010EAX changes and becomes the same as the destination host base frequency instead of remaining the source base frequency.That's a bug in whatever is orchestrating the migration, and/or QEMU if QEMU is handing the upper layers a loaded footgun.
Quoted 3 lines
The main reason for this behaviour is that setting the TSC frequency via
ioctl(KVM_SET_TSC_KHZ)doesn't change the value in CPUID leaf0x40000010EAX and these two entities are still not connected.And they never will be. It's userspace's responsibility to fill the correct values for
0x40000010.But AFAICT, QEMU does the right thing.
env->tsc_khzis used for both the CPUID leaf and forKVM_SET_TSC_KHZ.
kvm_arch_init_vcpu():c = &cpuid_data.entries[cpuid_i++]; c->function = KVM_CPUID_SIGNATURE | 0x10; c->eax = env->tsc_khz; c->ebx = env->apic_bus_freq / 1000; /* Hz to KHz */ c->ecx = c->edx = 0;
Quoted 6 lines
kvm_arch_set_tsc_khz():r = set_ioctl ? kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) : -ENOTSUP;
Agreed.
However, kvm_arch_set_tsc_khz() is also used at the end of migration (qemu_loadvm_state -> cpu_synchronize_post_init).
So, the new value of env->tsc_khz from the source host can be loaded during migration via KVM_SET_TSC_KHZ. However, the frequency in CPUID leaf 0x40000010 remains the same as on the destination host (the TSC frequency can differ from the source host's frequency). Thus, it's possible to have unsynchronized CPUID leaf 0x40000010 when using default QEMU parameters.
Quoted 14 lines
Quoted 10 lines
I saw this behaviour with QEMU 7, but I've checked the code of the latest version and it seems that the described behaviour still exists. So, in that case, it's possible that with these changes a VM will use the wrong TSC frequency from CPUID leaf
0x40000010EAX if it's migrated and then rebooted.Putting it all together, after the previous patch ("KVM: x86: Officially define CPUID
0x40000010as PV Timing Info (TSC and Bus)") a new way to show the guest that CPUID leaf0x40000010is valid should be implemented and only then this leaf can be used to get the TSC frequency.No, there are already non-Linux kernels that consume
0x40000010, e.g. FreeBSD. In my very strong opinion, if this problematic for a deployment, then that deployment needs to urgently fix their broken setup.
Signature · 2 lines
Best regards, Maksim Davydov
Re: [PATCH v6 21/51] x86/kvm: Obtain TSC frequency from PV CPUID if present
Quoted 61 lines · Maksim Davydov
Quoted 50 lines · Sean Christopherson
Quoted 20 lines · Maksim Davydov
Quoted 7 lines · Sean Christopherson
arch/x86/kernel/kvmclock.c +0
-0@@ -342,8 +342,10 @@ void __init kvmclock_init(void) flags =pvclock_read_flags (&hv_clock_boot[0 ].pvti);kvm_sched_clock_init (flags &PVCLOCK_TSC_STABLE_BIT );arch/x86/kernel/kvmclock.c void __init kvmclock_init(void) · line 351
Quoted 10 lines
arch/x86/kernel/kvmclock.c +4
-2- x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz; - x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; +if (!x86_init.hyper.get_tsc_khz) + x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz; +if (!x86_init.hyper.get_cpu_khz) + x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; x86_platform.get_wallclock = kvm_get_wallclock; x86_platform.set_wallclock = kvm_set_wallclock;#ifdef CONFIG_X86_LOCAL_APIC Quoted 7 lines
I cannot test this right now as I lack two servers with different CPU base frequencies, but it seems that this patch might break something in guests:
After migrating a VM (QEMU + KVM) from a host with one base frequency to another host with a different base frequency, the value in CPUID leaf0x40000010EAX changes and becomes the same as the destination host base frequency instead of remaining the source base frequency.That's a bug in whatever is orchestrating the migration, and/or QEMU if QEMU is handing the upper layers a loaded footgun.
Quoted 3 lines
The main reason for this behaviour is that setting the TSC frequency via
ioctl(KVM_SET_TSC_KHZ)doesn't change the value in CPUID leaf0x40000010EAX and these two entities are still not connected.And they never will be. It's userspace's responsibility to fill the correct values for
0x40000010.But AFAICT, QEMU does the right thing.
env->tsc_khzis used for both the CPUID leaf and forKVM_SET_TSC_KHZ.
kvm_arch_init_vcpu():c = &cpuid_data.entries[cpuid_i++]; c->function = KVM_CPUID_SIGNATURE | 0x10; c->eax = env->tsc_khz; c->ebx = env->apic_bus_freq / 1000; /* Hz to KHz */ c->ecx = c->edx = 0;Quoted 6 lines
kvm_arch_set_tsc_khz():r = set_ioctl ? kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) : -ENOTSUP;
Quoted 9 lines
Agreed.
However,kvm_arch_set_tsc_khz()is also used at the end of migration (qemu_loadvm_state->cpu_synchronize_post_init).
So, the new value ofenv->tsc_khzfrom the source host can be loaded during migration viaKVM_SET_TSC_KHZ. However, the frequency in CPUID leaf0x40000010remains the same as on the destination host (the TSC frequency can differ from the source host's frequency). Thus, it's possible to have unsynchronized CPUID leaf0x40000010when using default QEMU parameters.
I don't use qemu, but isn't the qemu solution for this general situation to mark leaf 40000010H as 'unmigratable'?
Re: [PATCH v6 21/51] x86/kvm: Obtain TSC frequency from PV CPUID if present
Quoted 73 lines · Jim Mattson
Quoted 61 lines · Maksim Davydov
Quoted 50 lines · Sean Christopherson
Quoted 20 lines · Maksim Davydov
Quoted 7 lines · Sean Christopherson
arch/x86/kernel/kvmclock.c +0
-0@@ -342,8 +342,10 @@ void __init kvmclock_init(void) flags =pvclock_read_flags (&hv_clock_boot[0 ].pvti);kvm_sched_clock_init (flags &PVCLOCK_TSC_STABLE_BIT );arch/x86/kernel/kvmclock.c void __init kvmclock_init(void) · line 351
Quoted 10 lines
arch/x86/kernel/kvmclock.c +4
-2- x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz; - x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; +if (!x86_init.hyper.get_tsc_khz) + x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz; +if (!x86_init.hyper.get_cpu_khz) + x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; x86_platform.get_wallclock = kvm_get_wallclock; x86_platform.set_wallclock = kvm_set_wallclock;#ifdef CONFIG_X86_LOCAL_APIC Quoted 7 lines
I cannot test this right now as I lack two servers with different CPU base frequencies, but it seems that this patch might break something in guests:
After migrating a VM (QEMU + KVM) from a host with one base frequency to another host with a different base frequency, the value in CPUID leaf0x40000010EAX changes and becomes the same as the destination host base frequency instead of remaining the source base frequency.That's a bug in whatever is orchestrating the migration, and/or QEMU if QEMU is handing the upper layers a loaded footgun.
Quoted 3 lines
The main reason for this behaviour is that setting the TSC frequency via
ioctl(KVM_SET_TSC_KHZ)doesn't change the value in CPUID leaf0x40000010EAX and these two entities are still not connected.And they never will be. It's userspace's responsibility to fill the correct values for
0x40000010.But AFAICT, QEMU does the right thing.
env->tsc_khzis used for both the CPUID leaf and forKVM_SET_TSC_KHZ.
kvm_arch_init_vcpu():c = &cpuid_data.entries[cpuid_i++]; c->function = KVM_CPUID_SIGNATURE | 0x10; c->eax = env->tsc_khz; c->ebx = env->apic_bus_freq / 1000; /* Hz to KHz */ c->ecx = c->edx = 0;Quoted 6 lines
kvm_arch_set_tsc_khz():r = set_ioctl ? kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) : -ENOTSUP;Quoted 9 lines
Agreed.
However,kvm_arch_set_tsc_khz()is also used at the end of migration (qemu_loadvm_state->cpu_synchronize_post_init).
So, the new value ofenv->tsc_khzfrom the source host can be loaded during migration viaKVM_SET_TSC_KHZ. However, the frequency in CPUID leaf0x40000010remains the same as on the destination host (the TSC frequency can differ from the source host's frequency). Thus, it's possible to have unsynchronized CPUID leaf0x40000010when using default QEMU parameters.
Quoted 2 lines
I don't use qemu, but isn't the qemu solution for this general situation to mark leaf 40000010H as 'unmigratable'?
I don't think this leaf should be unmigratable by default. I think the same logic as for invtsc can be implemented:
If the TSC frequency is explicitly specified via -cpu, CPUID leaf 0x40000010 is migratable because env->tsc_khz during kvm_arch_init_vcpu() on the destination host will be the same as on the source host. But if the TSC frequency isn't specified, CPUID leaf 0x40000010 has to be omitted from KVM_SET_CPUID2.
Sean Christopherson
maintainerPATCH v6 22/51 x86/kvm: Mark TSC as reliable when it's constant and nonstop
In reply to Sean ChristophersonMark the TSC as reliable if the hypervisor (KVM) has enumerated the TSC as constant and nonstop. Like most (all?) virtualization setups, any secondary clocksource that's used as a watchdog is guaranteed to be less reliable than a constant, nonstop TSC, as all clocksources the kernel uses as a watchdog are all but guaranteed to be emulated when running as a KVM guest. I.e. any observed discrepancies between the TSC and watchdog will be due to jitter in the watchdog.
This is especially true for KVM, as the watchdog clocksource is usually emulated in host userspace, i.e. reading the clock incurs a roundtrip cost of thousands of cycles.
Marking the TSC reliable addresses a flaw where the TSC will occasionally be marked unstable if the host is under moderate/heavy load.
--- arch/x86/include/asm/kvm_para.h | 2 +- arch/x86/kernel/kvm.c | 12 +++++++++++- arch/x86/kernel/kvmclock.c | 14 +++++--------- 3 files changed, 17 insertions(+), 11 deletions(-)
arch/x86/include/asm/kvm_para.h +1 -1
@@ -118,7 +118,7 @@ static inline long kvm_sev_hypercall3(unsigned int nr, unsigned long p1, }#ifdef CONFIG_KVM_GUEST -void kvmclock_init (void ); +void kvmclock_init (bool prefer_tsc);void kvmclock_disable (void );bool kvm_para_available (void );unsigned int kvm_arch_para_features (void );
arch/x86/kernel/kvm.c +11 -1
@@ -980,6 +980,7 @@ static void __init kvm_init_platform(void) .mask_hi = (BIT_ULL(boot_cpu_data.x86_phys_bits) - 1) >> 32, };u32 timing_info_leaf; +bool tsc_is_reliable;if (cc_platform_has (CC_ATTR_GUEST_MEM_ENCRYPT ) &&kvm_para_has_feature (KVM_FEATURE_MIGRATION_CONTROL )) {
@@ -1042,7 +1043,16 @@ static void __init kvm_init_platform(void) } } -kvmclock_init (); +/* +* If the TSC counts at a constant frequency across P/T states and in +* deep C-states, treat the TSC reliable, as guaranteed by KVM. +*/ + tsc_is_reliable =boot_cpu_has (X86_FEATURE_CONSTANT_TSC ) && +boot_cpu_has (X86_FEATURE_NONSTOP_TSC ); +if (tsc_is_reliable) +setup_force_cpu_cap (X86_FEATURE_TSC_RELIABLE ); + +kvmclock_init (tsc_is_reliable); x86_platform.apic_post_init = kvm_apic_init;/*
arch/x86/kernel/kvmclock.c +5 -9
@@ -307,7 +307,7 @@ static int kvmclock_setup_percpu(unsigned int cpu)return p ?0 : -ENOMEM ; } -void __init kvmclock_init (void ) +void __init kvmclock_init (bool prefer_tsc) {u8 flags;
@@ -356,15 +356,11 @@ void __init kvmclock_init(void)kvm_get_preset_lpj ();/* -* X86_FEATURE_NONSTOP_TSC is TSC runs at constant rate -* with P/T states and does not stop in deep C-states. -* -* Invariant TSC exposed by host means kvmclock is not necessary: -* can use TSC as clocksource. -* +* If TSC is preferred over kvmlock, drop kvmclock's rating so that TSC +* is chosen as the clocksource (but still register kvmclock in case +* the kernel doesn't want to use TSC for whatever reason). */ -if (boot_cpu_has (X86_FEATURE_CONSTANT_TSC ) && -boot_cpu_has (X86_FEATURE_NONSTOP_TSC )) +if (prefer_tsc) kvm_clock.rating =299 ;clocksource_register_hz (&kvm_clock,NSEC_PER_SEC );
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 23/51 x86/tsc: Add standalone helper for getting CPU frequency from CPUID
In reply to Sean ChristophersonExtract the guts of cpu_khz_from_cpuid() to a standalone helper that doesn't restrict the usage to Intel CPUs. This will allow sharing the core logic with KVM-as-a-guest, as KVM generally doesn't restrict CPUID based on vendor.
No functional change intended.
--- arch/x86/include/asm/tsc.h | 1 + arch/x86/kernel/tsc.c | 31 +++++++++++++++---------------- 2 files changed, 16 insertions(+), 16 deletions(-)
arch/x86/include/asm/tsc.h +1 -0
@@ -88,6 +88,7 @@ struct cpuid_tsc_info {unsigned int crystal_khz; };extern int cpuid_get_tsc_info (struct cpuid_tsc_info *info); +extern unsigned int __cpu_khz_from_cpuid (void );extern void tsc_early_init (void );extern void tsc_init (void );
arch/x86/kernel/tsc.c +15 -16
@@ -668,6 +668,18 @@ int cpuid_get_tsc_info(struct cpuid_tsc_info *info)return 0 ; } +unsigned int __cpu_khz_from_cpuid (void ) +{ +unsigned int eax_base_mhz, ebx, ecx, edx; + +if (boot_cpu_data.cpuid_level <CPUID_LEAF_FREQ ) +return 0 ; + +cpuid (CPUID_LEAF_FREQ , &eax_base_mhz, &ebx, &ecx, &edx); + +return eax_base_mhz *1000 ; +} +/** * native_calibrate_tsc - determine TSC frequency * Determine TSC frequency via CPUID, else return 0.
@@ -703,12 +715,8 @@ static unsigned long native_calibrate_tsc(void)* clock, but we can easily calculate it to a high degree of accuracy * by considering the crystal ratio and the CPU speed. */ -if (!info.crystal_khz && boot_cpu_data.cpuid_level >=CPUID_LEAF_FREQ ) { -unsigned int eax_base_mhz, ebx, ecx, edx; - -cpuid (CPUID_LEAF_FREQ , &eax_base_mhz, &ebx, &ecx, &edx); - info.crystal_khz = eax_base_mhz *1000 * info.denominator / info.numerator; - } +if (!info.crystal_khz) + info.crystal_khz =__cpu_khz_from_cpuid () * info.denominator / info.numerator;if (!info.crystal_khz)return 0 ;
@@ -733,19 +741,10 @@ static unsigned long native_calibrate_tsc(void)static unsigned long cpu_khz_from_cpuid (void ) { -unsigned int eax_base_mhz, ebx_max_mhz, ecx_bus_mhz, edx; -if (boot_cpu_data.x86_vendor !=X86_VENDOR_INTEL )return 0 ; -if (boot_cpu_data.cpuid_level <CPUID_LEAF_FREQ ) -return 0 ; - - eax_base_mhz = ebx_max_mhz = ecx_bus_mhz = edx =0 ; - -cpuid (CPUID_LEAF_FREQ , &eax_base_mhz, &ebx_max_mhz, &ecx_bus_mhz, &edx); - -return eax_base_mhz *1000 ; +return __cpu_khz_from_cpuid (); }/*
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 24/51 x86/kvm: Get CPU base frequency from CPUID when it's available
In reply to Sean ChristophersonIf CPUID.0x16 is present and valid, use the CPU frequency provided by CPUID instead of assuming that the virtual CPU runs at the same frequency as TSC and/or kvmclock. Back before constant TSCs were a thing, treating the TSC and CPU frequencies as one and the same was somewhat reasonable, but now it's nonsensical, especially if the hypervisor explicitly enumerates the CPU frequency.
--- arch/x86/kernel/kvm.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+)
arch/x86/kernel/kvm.c +14 -0
@@ -50,6 +50,7 @@#include <asm/e820/api.h> static unsigned int kvm_tsc_khz_cpuid__initdata ; +static unsigned int kvm_cpu_khz_cpuid__initdata ;DEFINE_STATIC_KEY_FALSE_RO (kvm_async_pf_enabled);
@@ -930,6 +931,11 @@ static unsigned int __init kvm_get_tsc_khz(void)return kvm_tsc_khz_cpuid; } +static unsigned int __init kvm_get_cpu_khz (void ) +{ +return kvm_cpu_khz_cpuid; +} +unsigned int kvm_arch_para_features (void ) {return cpuid_eax (kvm_cpuid_base () |KVM_CPUID_FEATURES );
@@ -1043,6 +1049,14 @@ static void __init kvm_init_platform(void) } } +/* +* Prefer CPUID.0x16 over KVM's PV CPUID when possible, as the base CPU +* frequency isn't necessarily the same as the TSC frequency. +*/ + kvm_cpu_khz_cpuid =__cpu_khz_from_cpuid (); +if (kvm_cpu_khz_cpuid) + x86_init.hyper.get_cpu_khz = kvm_get_cpu_khz; +/* * If the TSC counts at a constant frequency across P/T states and in * deep C-states, treat the TSC reliable, as guaranteed by KVM.
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
[email protected]
AI reviewRe: [PATCH v6 24/51] x86/kvm: Get CPU base frequency from CPUID when it's available
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The patch's intent to decouple CPU base frequency from TSC frequency is silently defeated by…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The patch's intent to decouple CPU base frequency from TSC frequency is silently defeated by core x86 timekeeping logic if the explicitly enumerated frequencies diverge by more than 10%. --
--- Patch [24]: [PATCH v6 24/51] x86/kvm: Get CPU base frequency from CPUID when it's available --- commit 950176e6b76f307f2a6acf272049d92426a49766
Author: Sean Christopherson <[email protected]>
x86/kvm: Get CPU base frequency from CPUID when it's available
If CPUID.0x16 is present and valid, use the CPU frequency provided by CPUID instead of assuming that the virtual CPU runs at the same frequency as TSC and/or kvmclock.
Quoted 4 lines
arch/x86/kernel/kvm.c +0
-0
[ ... ]
arch/x86/kernel/kvm.c static void __init kvm_init_platform(void) · line 1059
Quoted 12 lines
arch/x86/kernel/kvm.c +8
-0@@ -1043,6 +1049,14 @@ static void __init kvm_init_platform(void) } } +/* +* Prefer CPUID.0x16 over KVM's PV CPUID when possible, as the base CPU +* frequency isn't necessarily the same as the TSC frequency. +*/ + kvm_cpu_khz_cpuid =__cpu_khz_from_cpuid (); +if (kvm_cpu_khz_cpuid) + x86_init.hyper.get_cpu_khz = kvm_get_cpu_khz; +
[Severity: Medium]
Will this actually decouple the CPU base frequency from the TSC frequency if they diverge by more than 10%?
Looking at determine_cpu_tsc_frequencies() in arch/x86/kernel/tsc.c, it seems there is a legacy sanity check that overrides the explicitly enumerated CPU frequency if it diverges too much from the TSC frequency:
arch/x86/kernel/tsc.c:determine_cpu_tsc_frequencies() {
...
else if (abs(cpu_khz - tsc_khz) * 10 > tsc_khz)
cpu_khz = tsc_khz;...
}
During boot, KVM sets x86_init.hyper.get_cpu_khz to return the CPUID.0x16 frequency. The core x86 tsc_early_init() reads this and passes it to determine_cpu_tsc_frequencies().
Doesn't this mean the core timekeeping logic will silently overwrite the explicitly enumerated CPU frequency with the TSC frequency in these cases, neutralizing the intent of this patch?
Quoted 3 lines
arch/x86/kernel/kvm.c +0
-0/* * If the TSC counts at a constant frequency across P/T states and in * deep C-states, treat the TSC reliable, as guaranteed by KVM.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=24
Re: [PATCH v6 24/51] x86/kvm: Get CPU base frequency from CPUID when it's available
In reply to Sean ChristophersonQuoted 8 lines · Sean Christopherson
If CPUID.0x16 is present and valid, use the CPU frequency provided by CPUID instead of assuming that the virtual CPU runs at the same frequency as TSC and/or kvmclock. Back before constant TSCs were a thing, treating the TSC and CPU frequencies as one and the same was somewhat reasonable, but now it's nonsensical, especially if the hypervisor explicitly enumerates the CPU frequency.
Signed-off-by Sean Christopherson <[email protected]>
I still don't think I care about Sashiko's complaint.
Sean Christopherson
maintainerPATCH v6 25/51 clocksource: hyper-v: Register sched_clock save/restore iff it's necessary
In reply to Sean ChristophersonRegister the Hyper-V reference counter (refcounter) callbacks for saving and restoring its PV sched_clock, if and only if the refcounter is actually being used for sched_clock. Currently, Hyper-V overrides the save/restore hooks if the reference TSC available, whereas the Hyper-V refcounter code only overrides sched_clock if the reference TSC is available *and* it's not invariant. The flaw is effectively papered over by invoking the "old" save/restore callbacks as part of save/restore, but that's unnecessary and fragile.
To avoid introducing more complexity, and to allow for additional cleanups of the PV sched_clock code, move the save/restore hooks and logic into hyperv_timer.c and simply wire up the hooks when overriding sched_clock itself.
Note, while the Hyper-V refcounter code is intended to be architecture neutral, CONFIG_PARAVIRT is firmly x86-only, i.e. adding a small amount of x86 specific code (which will be reduced in future cleanups) doesn't meaningfully pollute generic code.
--- arch/x86/kernel/cpu/mshyperv.c | 58 ------------------------------ drivers/clocksource/hyperv_timer.c | 50 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 58 deletions(-)
arch/x86/kernel/cpu/mshyperv.c +0 -58
@@ -275,63 +275,6 @@ static void hv_guest_crash_shutdown(struct pt_regs *regs) }#endif /* CONFIG_CRASH_DUMP */ -static u64 hv_ref_counter_at_suspend; -static void (*old_save_sched_clock_state)(void ); -static void (*old_restore_sched_clock_state)(void ); - -/* -* Hyper-V clock counter resets during hibernation. Save and restore clock -* offset during suspend/resume, while also considering the time passed -* before suspend. This is to make sure that sched_clock using hv tsc page -* based clocksource, proceeds from where it left off during suspend and -* it shows correct time for the timestamps of kernel messages after resume. -*/ -static void save_hv_clock_tsc_state (void ) -{ - hv_ref_counter_at_suspend =hv_read_reference_counter (); -} - -static void restore_hv_clock_tsc_state (void ) -{ -/* -* Adjust the offsets used by hv tsc clocksource to -* account for the time spent before hibernation. -* adjusted value = reference counter (time) at suspend -* - reference counter (time) now. -*/ -hv_adj_sched_clock_offset (hv_ref_counter_at_suspend -hv_read_reference_counter ()); -} - -/* -* Functions to override save_sched_clock_state and restore_sched_clock_state -* functions of x86_platform. The Hyper-V clock counter is reset during -* suspend-resume and the offset used to measure time needs to be -* corrected, post resume. -*/ -static void hv_save_sched_clock_state (void ) -{ -old_save_sched_clock_state (); -save_hv_clock_tsc_state (); -} - -static void hv_restore_sched_clock_state (void ) -{ -restore_hv_clock_tsc_state (); -old_restore_sched_clock_state (); -} - -static void __init x86_setup_ops_for_tsc_pg_clock (void ) -{ -if (!(ms_hyperv.features &HV_MSR_REFERENCE_TSC_AVAILABLE )) -return ; - - old_save_sched_clock_state = x86_platform.save_sched_clock_state; - x86_platform.save_sched_clock_state = hv_save_sched_clock_state; - - old_restore_sched_clock_state = x86_platform.restore_sched_clock_state; - x86_platform.restore_sched_clock_state = hv_restore_sched_clock_state; -} -#ifdef CONFIG_X86_64 DEFINE_STATIC_CALL (hv_hypercall, hv_std_hypercall);EXPORT_STATIC_CALL_TRAMP_GPL (hv_hypercall);
@@ -736,7 +679,6 @@ static void __init ms_hyperv_init_platform(void)/* Register Hyper-V specific clocksource */ hv_init_clocksource (); -x86_setup_ops_for_tsc_pg_clock ();hv_vtl_init_platform ();#endif /*
drivers/clocksource/hyperv_timer.c +50 -0
60 lines not on this page · raw message
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 26/51 clocksource: hyper-v: Drop wrappers to sched_clock save/restore helpers
In reply to Sean ChristophersonNow that all of the Hyper-V reference counter sched_clock code is located in a single file, drop the superfluous wrappers for the save/restore flows.
No functional change intended.
--- drivers/clocksource/hyperv_timer.c | 34 +++++------------------------- include/clocksource/hyperv_timer.h | 2 -- 2 files changed, 5 insertions(+), 31 deletions(-)
drivers/clocksource/hyperv_timer.c +5 -29
@@ -488,17 +488,6 @@ static void resume_hv_clock_tsc(struct clocksource *arg)hv_set_msr (HV_MSR_REFERENCE_TSC , tsc_msr.as_uint64); } -/* -* Called during resume from hibernation, from overridden -* x86_platform.restore_sched_clock_state routine. This is to adjust offsets -* used to calculate time for hv tsc page based sched_clock, to account for -* time spent before hibernation. -*/ -void hv_adj_sched_clock_offset (u64 offset) -{ - hv_sched_clock_offset -= offset; -} -#ifdef HAVE_VDSO_CLOCKMODE_HVCLOCK static int hv_cs_enable (struct clocksource *cs) {
@@ -565,12 +554,14 @@ static void (*old_restore_sched_clock_state)(void);* based clocksource, proceeds from where it left off during suspend and * it shows correct time for the timestamps of kernel messages after resume. */ -static void save_hv_clock_tsc_state (void ) +static void hv_save_sched_clock_state (void ) { +old_save_sched_clock_state (); + hv_ref_counter_at_suspend =hv_read_reference_counter (); } -static void restore_hv_clock_tsc_state (void ) +static void hv_restore_sched_clock_state (void ) {/* * Adjust the offsets used by hv tsc clocksource to
@@ -578,23 +569,8 @@ static void restore_hv_clock_tsc_state(void)* adjusted value = reference counter (time) at suspend * - reference counter (time) now. */ -hv_adj_sched_clock_offset (hv_ref_counter_at_suspend -hv_read_reference_counter ()); -} -/* -* Functions to override save_sched_clock_state and restore_sched_clock_state -* functions of x86_platform. The Hyper-V clock counter is reset during -* suspend-resume and the offset used to measure time needs to be -* corrected, post resume. -*/ -static void hv_save_sched_clock_state (void ) -{ -old_save_sched_clock_state (); -save_hv_clock_tsc_state (); -} + hv_sched_clock_offset -= (hv_ref_counter_at_suspend -hv_read_reference_counter ()); -static void hv_restore_sched_clock_state (void ) -{ -restore_hv_clock_tsc_state ();old_restore_sched_clock_state (); }
include/clocksource/hyperv_timer.h +0 -2
@@ -38,8 +38,6 @@ extern void hv_remap_tsc_clocksource(void);extern unsigned long hv_get_tsc_pfn (void );extern struct ms_hyperv_tsc_page *hv_get_tsc_page (void ); -extern void hv_adj_sched_clock_offset (u64 offset); - static __always_inline boolhv_read_tsc_page_tsc (const struct ms_hyperv_tsc_page *tsc_pg,u64 *cur_tsc,u64 *time)
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 27/51 clocksource: hyper-v: Don't save/restore TSC offset when using HV sched_clock
In reply to Sean ChristophersonNow that Hyper-V overrides the sched_clock save/restore hooks if and only sched_clock itself is set to the Hyper-V reference counter, drop the invocation of the "old" save/restore callbacks. When the registration of the PV sched_clock was done separately from overriding the save/restore hooks, it was possible for Hyper-V to clobber the TSC save/restore callbacks without actually switching to the Hyper-V refcounter.
Enabling a PV sched_clock is a one-way street, i.e. the kernel will never revert to using TSC for sched_clock, and so there is no need to invoke the TSC save/restore hooks (and if there was, it belongs in common PV code).
--- drivers/clocksource/hyperv_timer.c | 10 ---------- 1 file changed, 10 deletions(-)
drivers/clocksource/hyperv_timer.c +0 -10
@@ -544,9 +544,6 @@ static __always_inline void hv_setup_sched_clock(void *sched_clock)#include <asm/timer.h> static u64 hv_ref_counter_at_suspend; -static void (*old_save_sched_clock_state)(void ); -static void (*old_restore_sched_clock_state)(void ); -/* * Hyper-V clock counter resets during hibernation. Save and restore clock * offset during suspend/resume, while also considering the time passed
@@ -556,8 +553,6 @@ static void (*old_restore_sched_clock_state)(void);*/ static void hv_save_sched_clock_state (void ) { -old_save_sched_clock_state (); - hv_ref_counter_at_suspend =hv_read_reference_counter (); }
@@ -570,8 +565,6 @@ static void hv_restore_sched_clock_state(void)* - reference counter (time) now. */ hv_sched_clock_offset -= (hv_ref_counter_at_suspend -hv_read_reference_counter ()); - -old_restore_sched_clock_state (); } static __always_inline void hv_setup_sched_clock(void *sched_clock)
@@ -579,10 +572,7 @@ static __always_inline void hv_setup_sched_clock(void *sched_clock)/* We're on x86/x64 *and* using PV ops */ paravirt_set_sched_clock (sched_clock); - old_save_sched_clock_state = x86_platform.save_sched_clock_state; x86_platform.save_sched_clock_state = hv_save_sched_clock_state; - - old_restore_sched_clock_state = x86_platform.restore_sched_clock_state; x86_platform.restore_sched_clock_state = hv_restore_sched_clock_state; }#else /* !CONFIG_GENERIC_SCHED_CLOCK && !CONFIG_PARAVIRT */
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 28/51 x86/kvmclock: Setup kvmclock for secondary CPUs iff CONFIG_SMP=y
In reply to Sean ChristophersonGate kvmclock's secondary CPU code on CONFIG_SMP, not CONFIG_X86_LOCAL_APIC. Originally, kvmclock piggybacked PV APIC ops to setup secondary CPUs. When that wart was fixed by commit df156f90a0f9 ("x86: Introduce x86_cpuinit.early_percpu_clock_init hook"), the dependency on a local APIC got carried forward unnecessarily.
--- arch/x86/kernel/kvmclock.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
arch/x86/kernel/kvmclock.c +2 -2
@@ -208,7 +208,7 @@ static void kvm_restore_sched_clock_state(void)kvm_register_clock ("primary cpu clock, resume" ); } -#ifdef CONFIG_X86_LOCAL_APIC +#ifdef CONFIG_SMP static void kvm_setup_secondary_clock (void ) {kvm_register_clock ("secondary cpu clock" );
@@ -348,7 +348,7 @@ void __init kvmclock_init(bool prefer_tsc) x86_init.hyper.get_cpu_khz = kvmclock_get_tsc_khz; x86_platform.get_wallclock = kvm_get_wallclock; x86_platform.set_wallclock = kvm_set_wallclock; -#ifdef CONFIG_X86_LOCAL_APIC +#ifdef CONFIG_SMP x86_cpuinit.early_percpu_clock_init = kvm_setup_secondary_clock;#endif x86_platform.save_sched_clock_state = kvm_save_sched_clock_state;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 29/51 x86/kvm: Don't disable kvmclock on BSP in syscore_suspend()
In reply to Sean ChristophersonDon't disable kvmclock on the BSP during syscore_suspend(), as the BSP's clock is NOT restored during syscore_resume(), but is instead restored earlier via the sched_clock restore callback. If suspend is aborted, e.g. due to a late wakeup, the BSP will run without its clock enabled, which "works" only because KVM-the-hypervisor is kind enough to not clobber the shared memory when the clock is disabled. But over time, the BSP's view of time will drift from APs.
Plumb in an "action" to KVM-as-a-guest and kvmclock code in preparation for additional cleanups to kvmclock's suspend/resume logic.
--- arch/x86/include/asm/kvm_para.h | 8 +++++++- arch/x86/kernel/kvm.c | 15 ++++++++------- arch/x86/kernel/kvmclock.c | 31 +++++++++++++++++++++++++------ 3 files changed, 40 insertions(+), 14 deletions(-)
arch/x86/include/asm/kvm_para.h +7 -1
@@ -118,8 +118,14 @@ static inline long kvm_sev_hypercall3(unsigned int nr, unsigned long p1, }#ifdef CONFIG_KVM_GUEST +enum kvm_guest_cpu_action { +KVM_GUEST_BSP_SUSPEND , +KVM_GUEST_AP_OFFLINE , +KVM_GUEST_SHUTDOWN , +}; +void kvmclock_init (bool prefer_tsc); -void kvmclock_disable (void ); +void kvmclock_cpu_action (enum kvm_guest_cpu_action action);bool kvm_para_available (void );unsigned int kvm_arch_para_features (void );unsigned int kvm_arch_para_hints (void );
arch/x86/kernel/kvm.c +8 -7
@@ -460,7 +460,7 @@ static void __init sev_map_percpu_data(void) } } -static void kvm_guest_cpu_offline (bool shutdown) +static void kvm_guest_cpu_offline (enum kvm_guest_cpu_action action) {kvm_disable_steal_time ();if (kvm_para_has_feature (KVM_FEATURE_PV_EOI ))
@@ -468,9 +468,10 @@ static void kvm_guest_cpu_offline(bool shutdown)if (kvm_para_has_feature (KVM_FEATURE_MIGRATION_CONTROL ))wrmsrq (MSR_KVM_MIGRATION_CONTROL ,0 );kvm_pv_disable_apf (); -if (!shutdown) +if (action !=KVM_GUEST_SHUTDOWN )apf_task_wake_all (); -kvmclock_disable (); + +kvmclock_cpu_action (action); }static int kvm_cpu_online (unsigned int cpu)
@@ -728,7 +729,7 @@ static int kvm_cpu_down_prepare(unsigned int cpu)unsigned long flags;local_irq_save (flags); -kvm_guest_cpu_offline (false); +kvm_guest_cpu_offline (KVM_GUEST_AP_OFFLINE );local_irq_restore (flags);return 0 ; }
@@ -739,7 +740,7 @@ static int kvm_suspend(void *data) {u64 val =0 ; -kvm_guest_cpu_offline (false); +kvm_guest_cpu_offline (KVM_GUEST_BSP_SUSPEND );#ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL if (kvm_para_has_feature (KVM_FEATURE_POLL_CONTROL ))
@@ -770,7 +771,7 @@ static struct syscore kvm_syscore = {static void kvm_pv_guest_cpu_reboot (void *unused) { -kvm_guest_cpu_offline (true); +kvm_guest_cpu_offline (KVM_GUEST_SHUTDOWN ); } static int kvm_pv_reboot_notify(struct notifier_block *nb,
@@ -794,7 +795,7 @@ static struct notifier_block kvm_pv_reboot_nb = {#ifdef CONFIG_CRASH_DUMP static void kvm_crash_shutdown (struct pt_regs *regs) { -kvm_guest_cpu_offline (true); +kvm_guest_cpu_offline (KVM_GUEST_SHUTDOWN );native_machine_crash_shutdown (regs); }#endif
arch/x86/kernel/kvmclock.c +25 -6
@@ -199,8 +199,22 @@ static void kvm_register_clock(char *txt)pr_debug ("kvm-clock: cpu %d, msr %llx, %s" ,smp_processor_id (), pa, txt); } +static void kvmclock_disable (void ) +{ +if (msr_kvm_system_time) +native_write_msr (msr_kvm_system_time,0 ); +} +static void kvm_save_sched_clock_state (void ) { +/* +* Stop host writes to kvmclock immediately prior to suspend/hibernate. +* If the system is hibernating, then kvmclock will likely reside at a +* different physical address when the system awakens, and host writes +* to the old address prior to reconfiguring kvmclock would clobber +* random memory. +*/ +kvmclock_disable (); }static void kvm_restore_sched_clock_state (void )
@@ -208,6 +222,17 @@ static void kvm_restore_sched_clock_state(void)kvm_register_clock ("primary cpu clock, resume" ); } +void kvmclock_cpu_action (enum kvm_guest_cpu_action action) +{ +/* +* Don't disable kvmclock on the BSP during suspend. If kvmclock is +* being used for sched_clock, then it needs to be kept alive until the +* last minute, and restored as quickly as possible after resume. +*/ +if (action !=KVM_GUEST_BSP_SUSPEND ) +kvmclock_disable (); +} +#ifdef CONFIG_SMP static void kvm_setup_secondary_clock (void ) {
@@ -215,12 +240,6 @@ static void kvm_setup_secondary_clock(void) }#endif -void kvmclock_disable (void ) -{ -if (msr_kvm_system_time) -native_write_msr (msr_kvm_system_time,0 ); -} -static void __init kvmclock_init_mem (void ) {unsigned long ncpus;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
[email protected]
AI reviewRe: [PATCH v6 29/51] x86/kvm: Don't disable kvmclock on BSP in syscore_suspend()
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
Pre-existing issues:
- [High] This problem wasn't introduced by this patch, but the KVM migration control MSR (MSR_KVM_MIGRATION_CONTROL) is disabled on suspend or CPU offline and never re-enabled on resume or CPU online, permanently breaking SEV live migration. --
--- Patch [29]: [PATCH v6 29/51] x86/kvm: Don't disable kvmclock on BSP in syscore_suspend() --- commit bb5c379a7a7675001e9cbd3ac5ed082d68cc68ae
Author: Sean Christopherson <[email protected]>
x86/kvm: Don't disable kvmclock on BSP in syscore_suspend()
This commit introduces a kvm_guest_cpu_action enum to avoid disabling kvmclock on the BSP during syscore_suspend. The BSP's clock is restored earlier via sched_clock, and disabling it can cause time drift over time.
Quoted 3 lines
arch/x86/kernel/kvm.c +0
-0
[ ... ]
arch/x86/kernel/kvm.c static void kvm_guest_cpu_offline(bool shutdown) · line 469
Quoted 12 lines
arch/x86/kernel/kvm.c +1
-1@@ -460,7 +460,7 @@ static void __init sev_map_percpu_data(void) } } -static void kvm_guest_cpu_offline (bool shutdown) +static void kvm_guest_cpu_offline (enum kvm_guest_cpu_action action) {kvm_disable_steal_time ();if (kvm_para_has_feature (KVM_FEATURE_PV_EOI ))@@ -468,9 +468,10 @@ static void kvm_guest_cpu_offline(bool shutdown)if (kvm_para_has_feature (KVM_FEATURE_MIGRATION_CONTROL ))wrmsrq (MSR_KVM_MIGRATION_CONTROL ,0 );
[Severity: High]
This is a pre-existing issue, but does this permanently break SEV live migration after a suspend/resume cycle?
When a CPU goes offline or the system suspends, kvm_guest_cpu_offline() clears MSR_KVM_MIGRATION_CONTROL. However, it appears this MSR is never re-enabled when the CPU comes back online.
For example, when the system resumes, kvm_guest_cpu_init() is called to restore other PV state like PV EOI and async PF, but it does not appear to restore MSR_KVM_MIGRATION_CONTROL.
Could this lack of restoration cause a SEV guest to permanently lose the ability to be live-migrated after an AP offline/online event or a suspend/resume?
Quoted 8 lines
arch/x86/kernel/kvm.c +3
-2kvm_pv_disable_apf (); -if (!shutdown) +if (action !=KVM_GUEST_SHUTDOWN )apf_task_wake_all (); -kvmclock_disable (); + +kvmclock_cpu_action (action); }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=29
Sean Christopherson
maintainerPATCH v6 30/51 x86/paravirt: Remove unnecessary PARAVIRT=n stub for paravirt_set_sched_clock()
In reply to Sean ChristophersonRemove the unnecessary paravirt_set_sched_clock() stub for PARAVIRT=n, as all callers are gated by PARAVIRT=y. Eliminating the stub will avoid a pile of pointless churn as the "real" implementation evolves.
No functional change intended.
--- arch/x86/include/asm/timer.h | 3 +++ arch/x86/kernel/tsc.c | 1 - 2 files changed, 3 insertions(+), 1 deletion(-)
arch/x86/include/asm/timer.h +3 -0
@@ -12,7 +12,10 @@ extern void recalibrate_cpu_khz(void);extern int no_timer_check;extern bool using_native_sched_clock (void ); + +#ifdef CONFIG_PARAVIRT void paravirt_set_sched_clock (u64 (*func)(void )); +#endif /* * We use the full linear equation: f(x) = a + b*x, in order to allow
arch/x86/kernel/tsc.c +0 -1
@@ -288,7 +288,6 @@ void paravirt_set_sched_clock(u64 (*func)(void))u64 sched_clock_noinstr (void ) __attribute__((alias ("native_sched_clock" )));bool using_native_sched_clock (void ) {return true; } -void paravirt_set_sched_clock (u64 (*func)(void )) { }#endif notrace u64 sched_clock(void)
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 31/51 x86/paravirt: Move handling of unstable PV clocks into paravirt_set_sched_clock()
In reply to Sean ChristophersonMove the handling of unstable PV clocks, of which kvmclock is the only example, into paravirt_set_sched_clock(). This will allow modifying paravirt_set_sched_clock() to keep using the TSC for sched_clock in certain scenarios without unintentionally marking the TSC-based clock as unstable.
No functional change intended.
--- arch/x86/include/asm/timer.h | 7 ++++++- arch/x86/kernel/kvmclock.c | 5 +---- arch/x86/kernel/tsc.c | 5 ++++- 3 files changed, 11 insertions(+), 6 deletions(-)
arch/x86/include/asm/timer.h +6 -1
@@ -14,7 +14,12 @@ extern int no_timer_check;extern bool using_native_sched_clock (void );#ifdef CONFIG_PARAVIRT -void paravirt_set_sched_clock (u64 (*func)(void )); +void __paravirt_set_sched_clock (u64 (*func)(void ),bool stable); + +static inline void paravirt_set_sched_clock (u64 (*func)(void )) +{ +__paravirt_set_sched_clock (func, true); +}#endif /*
arch/x86/kernel/kvmclock.c +1 -4
@@ -12,7 +12,6 @@#include <linux/hardirq.h> #include <linux/cpuhotplug.h> #include <linux/sched.h> -#include <linux/sched/clock.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/set_memory.h>
@@ -115,10 +114,8 @@ static noinstr u64 kvm_sched_clock_read(void)static inline void kvm_sched_clock_init (bool stable) { -if (!stable) -clear_sched_clock_stable (); kvm_sched_clock_offset =kvm_clock_read (); -paravirt_set_sched_clock (kvm_sched_clock_read); +__paravirt_set_sched_clock (kvm_sched_clock_read, stable);pr_info ("kvm-clock: using sched offset of %llu cycles" , kvm_sched_clock_offset);
arch/x86/kernel/tsc.c +4 -1
@@ -280,8 +280,11 @@ bool using_native_sched_clock(void) return static_call_query(pv_sched_clock) == native_sched_clock; } -void paravirt_set_sched_clock (u64 (*func)(void )) +void __paravirt_set_sched_clock (u64 (*func)(void ),bool stable) { +if (!stable) +clear_sched_clock_stable (); +static_call_update (pv_sched_clock, func); }#else
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 32/51 x86/kvmclock: Move sched_clock save/restore helpers up in kvmclock.c
In reply to Sean ChristophersonMove kvmclock's sched_clock save/restore helper "up" so that they can (eventually) be referenced by kvm_sched_clock_init().
No functional change intended.
--- arch/x86/kernel/kvmclock.c | 108 ++++++++++++++++++------------------- 1 file changed, 54 insertions(+), 54 deletions(-)
arch/x86/kernel/kvmclock.c +54 -54
@@ -71,6 +71,25 @@ static int kvm_set_wallclock(const struct timespec64 *now)return -ENODEV ; } +static void kvm_register_clock (char *txt) +{ +struct pvclock_vsyscall_time_info *src =this_cpu_hvclock (); +u64 pa; + +if (!src) +return ; + + pa =slow_virt_to_phys (&src->pvti) |0x01ULL ; +wrmsrq (msr_kvm_system_time, pa); +pr_debug ("kvm-clock: cpu %d, msr %llx, %s" ,smp_processor_id (), pa, txt); +} + +static void kvmclock_disable (void ) +{ +if (msr_kvm_system_time) +native_write_msr (msr_kvm_system_time,0 ); +} +static u64 kvm_clock_read (void ) {u64 ret;
@@ -112,6 +131,30 @@ static noinstr u64 kvm_sched_clock_read(void)return pvclock_clocksource_read_nowd (this_cpu_pvti ()) - kvm_sched_clock_offset; } +static void kvm_save_sched_clock_state (void ) +{ +/* +* Stop host writes to kvmclock immediately prior to suspend/hibernate. +* If the system is hibernating, then kvmclock will likely reside at a +* different physical address when the system awakens, and host writes +* to the old address prior to reconfiguring kvmclock would clobber +* random memory. +*/ +kvmclock_disable (); +} + +#ifdef CONFIG_SMP +static void kvm_setup_secondary_clock (void ) +{ +kvm_register_clock ("secondary cpu clock" ); +} +#endif + +static void kvm_restore_sched_clock_state (void ) +{ +kvm_register_clock ("primary cpu clock, resume" ); +} +static inline void kvm_sched_clock_init (bool stable) { kvm_sched_clock_offset =kvm_clock_read ();
@@ -124,6 +167,17 @@ static inline void kvm_sched_clock_init(bool stable) sizeof(((struct pvclock_vcpu_time_info *)NULL)->system_time)); } +void kvmclock_cpu_action (enum kvm_guest_cpu_action action) +{ +/* +* Don't disable kvmclock on the BSP during suspend. If kvmclock is +* being used for sched_clock, then it needs to be kept alive until the +* last minute, and restored as quickly as possible after resume. +*/ +if (action !=KVM_GUEST_BSP_SUSPEND ) +kvmclock_disable (); +} +/* * If we don't do that, there is the possibility that the guest * will calibrate under heavy load - thus, getting a lower lpj -
@@ -183,60 +237,6 @@ static struct clocksource kvm_clock = { .enable = kvm_cs_enable, }; -static void kvm_register_clock (char *txt) -{ -struct pvclock_vsyscall_time_info *src =this_cpu_hvclock (); -u64 pa; - -if (!src) -return ; - - pa =slow_virt_to_phys (&src->pvti) |0x01ULL ; -wrmsrq (msr_kvm_system_time, pa); -pr_debug ("kvm-clock: cpu %d, msr %llx, %s" ,smp_processor_id (), pa, txt); -} - -static void kvmclock_disable (void ) -{ -if (msr_kvm_system_time) -native_write_msr (msr_kvm_system_time,0 ); -} - -static void kvm_save_sched_clock_state (void ) -{ -/* -* Stop host writes to kvmclock immediately prior to suspend/hibernate. -* If the system is hibernating, then kvmclock will likely reside at a -* different physical address when the system awakens, and host writes -* to the old address prior to reconfiguring kvmclock would clobber -* random memory. -*/ -kvmclock_disable (); -} - -static void kvm_restore_sched_clock_state (void ) -{ -kvm_register_clock ("primary cpu clock, resume" ); -} - -void kvmclock_cpu_action (enum kvm_guest_cpu_action action) -{ -/* -* Don't disable kvmclock on the BSP during suspend. If kvmclock is -* being used for sched_clock, then it needs to be kept alive until the -* last minute, and restored as quickly as possible after resume. -*/ -if (action !=KVM_GUEST_BSP_SUSPEND ) -kvmclock_disable (); -} - -#ifdef CONFIG_SMP -static void kvm_setup_secondary_clock (void ) -{ -kvm_register_clock ("secondary cpu clock" ); -} -#endif -static void __init kvmclock_init_mem (void ) {unsigned long ncpus;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 33/51 x86/xen/time: NOP-ify x86_platform's sched_clock save/restore hooks
In reply to Sean ChristophersonNOP-ify the x86_platform sched_clock save/restore hooks when setting up Xen's PV clock to make it somewhat obvious the hooks aren't used when running as a Xen guest (Xen uses a paravirtualized suspend/resume flow).
--- arch/x86/xen/time.c | 6 ++++++ 1 file changed, 6 insertions(+)
arch/x86/xen/time.c +6 -0
@@ -567,6 +567,12 @@ static void __init xen_init_time_common(void) xen_sched_clock_offset =xen_clocksource_read ();static_call_update (pv_steal_clock, xen_steal_clock);paravirt_set_sched_clock (xen_sched_clock); +/* +* Xen has paravirtualized suspend/resume and so doesn't use the common +* x86 sched_clock save/restore hooks. +*/ + x86_platform.save_sched_clock_state = x86_init_noop; + x86_platform.restore_sched_clock_state = x86_init_noop; x86_init.hyper.get_tsc_khz = xen_tsc_khz; x86_platform.get_wallclock = xen_get_wallclock;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 34/51 x86/vmware: NOP-ify save/restore hooks when using VMware's sched_clock
In reply to Sean ChristophersonNOP-ify the sched_clock save/restore hooks when using VMware's version of sched_clock. This will allow extending paravirt_set_sched_clock() to set the save/restore hooks, without having to simultaneously change the behavior of VMware guests.
Note, it's not at all obvious that it's safe/correct for VMware guests to do nothing on suspend/resume, but that's a pre-existing problem. Leave it for a VMware expert to sort out.
--- arch/x86/kernel/cpu/vmware.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
arch/x86/kernel/cpu/vmware.c +4 -1
@@ -347,8 +347,11 @@ static void __init vmware_paravirt_ops_setup(void)vmware_cyc2ns_setup (); -if (vmw_sched_clock) +if (vmw_sched_clock) {paravirt_set_sched_clock (vmware_sched_clock); + x86_platform.save_sched_clock_state = x86_init_noop; + x86_platform.restore_sched_clock_state = x86_init_noop; + }if (vmware_is_stealclock_available ()) { has_steal_clock = true;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 35/51 x86/tsc: WARN if TSC sched_clock save/restore used with PV sched_clock
In reply to Sean ChristophersonNow that all PV clocksources override the sched_clock save/restore hooks when overriding sched_clock, WARN if the "default" TSC hooks are invoked when using a PV sched_clock, e.g. to guard against regressions.
--- arch/x86/kernel/tsc.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-)
arch/x86/kernel/tsc.c +10 -2
@@ -947,9 +947,17 @@ EXPORT_SYMBOL_FOR_MODULES(recalibrate_cpu_khz, "p4-clockmod,powernow-k7");static unsigned long long cyc2ns_suspend; +static __always_inline bool tsc_is_save_restore_needed(void) +{ +if (WARN_ON_ONCE (!using_native_sched_clock ())) +return false; + +return static_branch_likely (&__use_tsc) ||sched_clock_stable (); +} +void tsc_save_sched_clock_state (void ) { -if (!static_branch_likely (&__use_tsc) && !sched_clock_stable ()) +if (!tsc_is_save_restore_needed ())return ; cyc2ns_suspend =sched_clock ();
@@ -969,7 +977,7 @@ void tsc_restore_sched_clock_state(void)unsigned long flags;int cpu; -if (!static_branch_likely (&__use_tsc) && !sched_clock_stable ()) +if (!tsc_is_save_restore_needed ())return ;local_irq_save (flags);
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 36/51 x86/paravirt: Pass sched_clock save/restore helpers during registration
In reply to Sean ChristophersonPass in a PV clock's save/restore helpers when configuring sched_clock instead of relying on each PV clock to manually set the save/restore hooks. In addition to bringing sanity to the code, this will allow gracefully "rejecting" a PV sched_clock, e.g. when running as a CoCo guest that has access to a "secure" TSC.
No functional change intended.
--- arch/x86/include/asm/timer.h | 9 ++++++--- arch/x86/kernel/cpu/vmware.c | 8 +++----- arch/x86/kernel/kvmclock.c | 6 +++--- arch/x86/kernel/tsc.c | 5 ++++- arch/x86/xen/time.c | 5 ++--- drivers/clocksource/hyperv_timer.c | 6 ++---- 6 files changed, 20 insertions(+), 19 deletions(-)
arch/x86/include/asm/timer.h +6 -3
@@ -14,11 +14,14 @@ extern int no_timer_check;extern bool using_native_sched_clock (void );#ifdef CONFIG_PARAVIRT -void __paravirt_set_sched_clock (u64 (*func)(void ),bool stable); +void __paravirt_set_sched_clock (u64 (*func)(void ),bool stable, +void (*save)(void ),void (*restore)(void )); -static inline void paravirt_set_sched_clock (u64 (*func)(void )) +static inline void paravirt_set_sched_clock (u64 (*func)(void ), +void (*save)(void ), +void (*restore)(void )) { -__paravirt_set_sched_clock (func, true); +__paravirt_set_sched_clock (func, true, save, restore); }#endif
arch/x86/kernel/cpu/vmware.c +3 -5
@@ -347,11 +347,9 @@ static void __init vmware_paravirt_ops_setup(void)vmware_cyc2ns_setup (); -if (vmw_sched_clock) { -paravirt_set_sched_clock (vmware_sched_clock); - x86_platform.save_sched_clock_state = x86_init_noop; - x86_platform.restore_sched_clock_state = x86_init_noop; - } +if (vmw_sched_clock) +paravirt_set_sched_clock (vmware_sched_clock, + x86_init_noop, x86_init_noop);if (vmware_is_stealclock_available ()) { has_steal_clock = true;
arch/x86/kernel/kvmclock.c +3 -3
@@ -158,7 +158,9 @@ static void kvm_restore_sched_clock_state(void)static inline void kvm_sched_clock_init (bool stable) { kvm_sched_clock_offset =kvm_clock_read (); -__paravirt_set_sched_clock (kvm_sched_clock_read, stable); +__paravirt_set_sched_clock (kvm_sched_clock_read, stable, + kvm_save_sched_clock_state, + kvm_restore_sched_clock_state);pr_info ("kvm-clock: using sched offset of %llu cycles" , kvm_sched_clock_offset);
@@ -367,8 +369,6 @@ void __init kvmclock_init(bool prefer_tsc)#ifdef CONFIG_SMP x86_cpuinit.early_percpu_clock_init = kvm_setup_secondary_clock;#endif - x86_platform.save_sched_clock_state = kvm_save_sched_clock_state; - x86_platform.restore_sched_clock_state = kvm_restore_sched_clock_state;kvm_get_preset_lpj ();/*
arch/x86/kernel/tsc.c +4 -1
@@ -280,12 +280,15 @@ bool using_native_sched_clock(void) return static_call_query(pv_sched_clock) == native_sched_clock; } -void __paravirt_set_sched_clock (u64 (*func)(void ),bool stable) +void __paravirt_set_sched_clock (u64 (*func)(void ),bool stable, +void (*save)(void ),void (*restore)(void )) {if (!stable)clear_sched_clock_stable ();static_call_update (pv_sched_clock, func); + x86_platform.save_sched_clock_state = save; + x86_platform.restore_sched_clock_state = restore; }#else u64 sched_clock_noinstr (void ) __attribute__((alias ("native_sched_clock" )));
arch/x86/xen/time.c +2 -3
@@ -566,13 +566,12 @@ static void __init xen_init_time_common(void) { xen_sched_clock_offset =xen_clocksource_read ();static_call_update (pv_steal_clock, xen_steal_clock); -paravirt_set_sched_clock (xen_sched_clock); +/* * Xen has paravirtualized suspend/resume and so doesn't use the common * x86 sched_clock save/restore hooks. */ - x86_platform.save_sched_clock_state = x86_init_noop; - x86_platform.restore_sched_clock_state = x86_init_noop; +paravirt_set_sched_clock (xen_sched_clock, x86_init_noop, x86_init_noop); x86_init.hyper.get_tsc_khz = xen_tsc_khz; x86_platform.get_wallclock = xen_get_wallclock;
drivers/clocksource/hyperv_timer.c +2 -4
@@ -570,10 +570,8 @@ static void hv_restore_sched_clock_state(void) static __always_inline void hv_setup_sched_clock(void *sched_clock) {/* We're on x86/x64 *and* using PV ops */ -paravirt_set_sched_clock (sched_clock); - - x86_platform.save_sched_clock_state = hv_save_sched_clock_state; - x86_platform.restore_sched_clock_state = hv_restore_sched_clock_state; +paravirt_set_sched_clock (sched_clock, hv_save_sched_clock_state, + hv_restore_sched_clock_state); }#else /* !CONFIG_GENERIC_SCHED_CLOCK && !CONFIG_PARAVIRT */ static __always_inline void hv_setup_sched_clock(void *sched_clock) {}
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 37/51 x86/kvmclock: Move kvm_sched_clock_init() down in kvmclock.c
In reply to Sean ChristophersonMove kvm_sched_clock_init() "down" so that it can reference the global kvm_clock structure without needing a forward declaration.
Opportunistically mark the helper as "__init" instead of "inline" to make its usage more obvious; modern compilers don't need a hint to inline a single-use function, and an extra CALL+RET pair during boot is a complete non-issue. And, if the compiler ignores the hint and does NOT inline the function, the resulting code may not get discarded after boot due lack of an __init annotation.
No functional change intended.
--- arch/x86/kernel/kvmclock.c | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-)
arch/x86/kernel/kvmclock.c +14 -14
@@ -155,20 +155,6 @@ static void kvm_restore_sched_clock_state(void)kvm_register_clock ("primary cpu clock, resume" ); } -static inline void kvm_sched_clock_init (bool stable) -{ - kvm_sched_clock_offset =kvm_clock_read (); -__paravirt_set_sched_clock (kvm_sched_clock_read, stable, - kvm_save_sched_clock_state, - kvm_restore_sched_clock_state); - -pr_info ("kvm-clock: using sched offset of %llu cycles" , - kvm_sched_clock_offset); - -BUILD_BUG_ON (sizeof (kvm_sched_clock_offset) > -sizeof (((struct pvclock_vcpu_time_info *)NULL )->system_time)); -} -void kvmclock_cpu_action (enum kvm_guest_cpu_action action) {/*
@@ -325,6 +311,20 @@ static int kvmclock_setup_percpu(unsigned int cpu)return p ?0 : -ENOMEM ; } +static __init void kvm_sched_clock_init (bool stable) +{ + kvm_sched_clock_offset =kvm_clock_read (); +__paravirt_set_sched_clock (kvm_sched_clock_read, stable, + kvm_save_sched_clock_state, + kvm_restore_sched_clock_state); + +pr_info ("kvm-clock: using sched offset of %llu cycles" , + kvm_sched_clock_offset); + +BUILD_BUG_ON (sizeof (kvm_sched_clock_offset) > +sizeof (((struct pvclock_vcpu_time_info *)NULL )->system_time)); +} +void __init kvmclock_init (bool prefer_tsc) {u8 flags;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 38/51 x86/xen/time: Mark xen_setup_vsyscall_time_info() as __init
In reply to Sean ChristophersonAnnotate xen_setup_vsyscall_time_info() as being used only during kernel initialization; it's called only by xen_time_init(), which is already tagged __init.
--- arch/x86/xen/time.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/xen/time.c +1 -1
@@ -443,7 +443,7 @@ void xen_restore_time_memory_area(void) xen_sched_clock_offset =xen_clocksource_read () - xen_clock_value_saved; } -static void xen_setup_vsyscall_time_info (void ) +static void __init xen_setup_vsyscall_time_info (void ) {struct vcpu_register_time_memory_area t;struct pvclock_vsyscall_time_info *ti;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 39/51 x86/pvclock: Mark setup helpers and related various as __init/__ro_after_init
In reply to Sean ChristophersonNow that Xen PV clock and kvmclock explicitly do setup only during init, tag the common PV clock flags/vsyscall variables and their mutators with __init.
--- arch/x86/kernel/pvclock.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
arch/x86/kernel/pvclock.c +4 -4
@@ -16,10 +16,10 @@#include <asm/pvclock.h> #include <asm/vgtod.h> -static u8 valid_flags__read_mostly =0 ; -static struct pvclock_vsyscall_time_info *pvti_cpu0_va__read_mostly ; +static u8 valid_flags__ro_after_init =0 ; +static struct pvclock_vsyscall_time_info *pvti_cpu0_va__ro_after_init ; -void pvclock_set_flags (u8 flags) +void __init pvclock_set_flags (u8 flags) { valid_flags = flags; }
@@ -153,7 +153,7 @@ void pvclock_read_wallclock(struct pvclock_wall_clock *wall_clock,set_normalized_timespec64 (ts, now.tv_sec, now.tv_nsec); } -void pvclock_set_pvti_cpu0_va (struct pvclock_vsyscall_time_info *pvti) +void __init pvclock_set_pvti_cpu0_va (struct pvclock_vsyscall_time_info *pvti) {WARN_ON (vclock_was_used (VDSO_CLOCKMODE_PVCLOCK )); pvti_cpu0_va = pvti;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 40/51 x86/pvclock: WARN if pvclock's valid_flags are overwritten
In reply to Sean ChristophersonWARN if the common PV clock valid_flags are overwritten; all PV clocks expect that they are the one and only PV clock, i.e. don't guard against another PV clock having modified the flags.
--- arch/x86/kernel/pvclock.c | 1 + 1 file changed, 1 insertion(+)
arch/x86/kernel/pvclock.c +1 -0
@@ -21,6 +21,7 @@ static struct pvclock_vsyscall_time_info *pvti_cpu0_va __ro_after_init;void __init pvclock_set_flags (u8 flags) { +WARN_ON (valid_flags); valid_flags = flags; }
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 41/51 x86/kvmclock: Refactor handling of PVCLOCK_TSC_STABLE_BIT during kvmclock_init()
In reply to Sean ChristophersonClean up the setting of PVCLOCK_TSC_STABLE_BIT during kvmclock init to make it somewhat obvious that pvclock_read_flags() must be called *after* pvclock_set_flags().
Note, in theory, a different PV clock could have set PVCLOCK_TSC_STABLE_BIT in the supported flags, i.e. reading flags only if KVM_FEATURE_CLOCKSOURCE_STABLE_BIT is set could very, very theoretically result in a change in behavior. In practice, the kernel only supports a single PV clock.
--- arch/x86/kernel/kvmclock.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-)
arch/x86/kernel/kvmclock.c +11 -4
@@ -327,7 +327,7 @@ static __init void kvm_sched_clock_init(bool stable)void __init kvmclock_init (bool prefer_tsc) { -u8 flags; +bool stable = false;if (!kvm_para_available () || !kvmclock)return ;
@@ -354,11 +354,18 @@ void __init kvmclock_init(bool prefer_tsc)kvm_register_clock ("primary cpu clock" );pvclock_set_pvti_cpu0_va (hv_clock_boot); -if (kvm_para_has_feature (KVM_FEATURE_CLOCKSOURCE_STABLE_BIT )) +if (kvm_para_has_feature (KVM_FEATURE_CLOCKSOURCE_STABLE_BIT )) {pvclock_set_flags (PVCLOCK_TSC_STABLE_BIT ); - flags =pvclock_read_flags (&hv_clock_boot[0 ].pvti); -kvm_sched_clock_init (flags &PVCLOCK_TSC_STABLE_BIT ); +/* +* Check if the clock is stable *after* marking TSC_STABLE as a +* valid flag. +*/ + stable =pvclock_read_flags (&hv_clock_boot[0 ].pvti) & +PVCLOCK_TSC_STABLE_BIT ; + } + +kvm_sched_clock_init (stable);if (!x86_init.hyper.get_tsc_khz) x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 42/51 timekeeping: Resume clocksources before reading persistent clock
In reply to Sean ChristophersonWhen resuming timekeeping after suspend, restore clocksources prior to reading the persistent clock. Paravirt clocks, e.g. kvmclock, tie the validity of a PV persistent clock to a clocksource, i.e. reading the PV persistent clock will return garbage if the underlying PV clocksource hasn't been enabled. The flaw has gone unnoticed because kvmclock is a mess and uses its own suspend/resume hooks instead of the clocksource suspend/resume hooks, which happens to work by sheer dumb luck (the kvmclock resume hook runs before timekeeping_resume()).
Note, there is no evidence that any clocksource supported by the kernel depends on a persistent clock.
--- kernel/time/timekeeping.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
kernel/time/timekeeping.c +7 -2
@@ -2226,11 +2226,16 @@ void timekeeping_resume(void)u64 cycle_now, nsec;unsigned long flags; -read_persistent_clock64 (&ts_new); -clockevents_resume ();clocksource_resume (); +/* +* Read persistent time after clocksources have been resumed. Paravirt +* clocks have a nasty habit of piggybacking a persistent clock on a +* system clock, and may return garbage if the system clock is suspended. +*/ +read_persistent_clock64 (&ts_new); +raw_spin_lock_irqsave (&tk_core.lock, flags);/*
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 43/51 x86/kvmclock: Hook clocksource.suspend/resume when kvmclock isn't sched_clock
In reply to Sean ChristophersonSave/restore kvmclock across suspend/resume via clocksource hooks when kvmclock isn't being used for sched_clock. This will allow using kvmclock as a clocksource (or for wallclock!) without also using it for sched_clock.
--- arch/x86/kernel/kvmclock.c | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-)
arch/x86/kernel/kvmclock.c +22 -1
@@ -152,7 +152,17 @@ static void kvm_setup_secondary_clock(void)static void kvm_restore_sched_clock_state (void ) { -kvm_register_clock ("primary cpu clock, resume" ); +kvm_register_clock ("primary cpu, sched_clock resume" ); +} + +static void kvmclock_suspend (struct clocksource *cs) +{ +kvmclock_disable (); +} + +static void kvmclock_resume (struct clocksource *cs) +{ +kvm_register_clock ("primary cpu, clocksource resume" ); }void kvmclock_cpu_action (enum kvm_guest_cpu_action action)
@@ -223,6 +233,8 @@ static struct clocksource kvm_clock = { .flags = CLOCK_SOURCE_IS_CONTINUOUS, .id = CSID_X86_KVM_CLK, .enable = kvm_cs_enable, + .suspend = kvmclock_suspend, + .resume = kvmclock_resume, };static void __init kvmclock_init_mem (void )
@@ -318,6 +330,15 @@ static __init void kvm_sched_clock_init(bool stable) kvm_save_sched_clock_state, kvm_restore_sched_clock_state); +/* +* The BSP's clock is managed via dedicated sched_clock save/restore +* hooks when kvmclock is used as sched_clock, as sched_clock needs to +* be kept alive until the very end of suspend entry, and restored as +* quickly as possible after resume. +*/ + kvm_clock.suspend =NULL ; + kvm_clock.resume =NULL ; +pr_info ("kvm-clock: using sched offset of %llu cycles" , kvm_sched_clock_offset);
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 44/51 x86/kvmclock: WARN if wall clock is read while kvmclock is suspended
In reply to Sean ChristophersonWARN if kvmclock is still suspended when its wallclock is read, i.e. when the kernel reads its persistent clock. The wallclock subtly depends on the BSP's kvmclock being enabled, and returns garbage if kvmclock is disabled.
--- arch/x86/kernel/kvmclock.c | 7 +++++++ 1 file changed, 7 insertions(+)
arch/x86/kernel/kvmclock.c +7 -0
@@ -53,6 +53,8 @@ static struct pvclock_vsyscall_time_info *hvclock_mem; DEFINE_PER_CPU(struct pvclock_vsyscall_time_info *, hv_clock_per_cpu);EXPORT_PER_CPU_SYMBOL_GPL (hv_clock_per_cpu); +static bool kvmclock_suspended; +/* * The wallclock is the time of day when we booted. Since then, some time may * have elapsed since the hypervisor wrote the data. So we try to account for
@@ -60,6 +62,7 @@ EXPORT_PER_CPU_SYMBOL_GPL(hv_clock_per_cpu);*/ static void kvm_get_wallclock (struct timespec64 *now) { +WARN_ON_ONCE (kvmclock_suspended);wrmsrq (msr_kvm_wall_clock,slow_virt_to_phys (&wall_clock));preempt_disable ();pvclock_read_wallclock (&wall_clock,this_cpu_pvti (), now);
@@ -140,6 +143,7 @@ static void kvm_save_sched_clock_state(void)* to the old address prior to reconfiguring kvmclock would clobber * random memory. */ + kvmclock_suspended = true;kvmclock_disable (); }
@@ -152,16 +156,19 @@ static void kvm_setup_secondary_clock(void)static void kvm_restore_sched_clock_state (void ) { + kvmclock_suspended = false;kvm_register_clock ("primary cpu, sched_clock resume" ); }static void kvmclock_suspend (struct clocksource *cs) { + kvmclock_suspended = true;kvmclock_disable (); }static void kvmclock_resume (struct clocksource *cs) { + kvmclock_suspended = false;kvm_register_clock ("primary cpu, clocksource resume" ); }
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 45/51 x86/paravirt: Mark __paravirt_set_sched_clock() as __init
In reply to Sean ChristophersonAnnotate __paravirt_set_sched_clock() as __init, and make its wrapper __always_inline to ensure sanitizers don't result in a non-inline version hanging around. All callers run during __init, and changing sched_clock after boot would be all kinds of crazy.
No functional change intended.
--- arch/x86/include/asm/timer.h | 10 +++++----- arch/x86/kernel/tsc.c | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-)
arch/x86/include/asm/timer.h +5 -5
@@ -14,12 +14,12 @@ extern int no_timer_check;extern bool using_native_sched_clock (void );#ifdef CONFIG_PARAVIRT -void __paravirt_set_sched_clock (u64 (*func)(void ),bool stable, -void (*save)(void ),void (*restore)(void )); +void __init __paravirt_set_sched_clock (u64 (*func)(void ),bool stable, +void (*save)(void ),void (*restore)(void )); -static inline void paravirt_set_sched_clock (u64 (*func)(void ), -void (*save)(void ), -void (*restore)(void )) +static __always_inline void paravirt_set_sched_clock(u64 (*func)(void), +void (*save)(void ), +void (*restore)(void )) {__paravirt_set_sched_clock (func, true, save, restore); }
arch/x86/kernel/tsc.c +2 -2
@@ -280,8 +280,8 @@ bool using_native_sched_clock(void)return static_call_query (pv_sched_clock) == native_sched_clock; } -void __paravirt_set_sched_clock (u64 (*func)(void ),bool stable, -void (*save)(void ),void (*restore)(void )) +void __init __paravirt_set_sched_clock (u64 (*func)(void ),bool stable, +void (*save)(void ),void (*restore)(void )) {if (!stable)clear_sched_clock_stable ();
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 46/51 x86/paravirt: Plumb a return code into __paravirt_set_sched_clock()
In reply to Sean ChristophersonAdd a return code to __paravirt_set_sched_clock() so that the kernel can reject attempts to use a PV sched_clock without breaking the caller. E.g. when running as a CoCo VM with a secure TSC, using a PV clock is generally undesirable.
Note, kvmclock is the only PV clock that does anything "extra" beyond simply registering itself as sched_clock, i.e. is the only caller that needs to check the new return value.
--- arch/x86/include/asm/timer.h | 6 +++--- arch/x86/kernel/kvmclock.c | 9 ++++++--- arch/x86/kernel/tsc.c | 5 +++-- 3 files changed, 12 insertions(+), 8 deletions(-)
arch/x86/include/asm/timer.h +3 -3
@@ -14,14 +14,14 @@ extern int no_timer_check;extern bool using_native_sched_clock (void );#ifdef CONFIG_PARAVIRT -void __init __paravirt_set_sched_clock (u64 (*func)(void ),bool stable, -void (*save)(void ),void (*restore)(void )); +int __init __paravirt_set_sched_clock (u64 (*func)(void ),bool stable, +void (*save)(void ),void (*restore)(void )); static __always_inline void paravirt_set_sched_clock(u64 (*func)(void),void (*save)(void ),void (*restore)(void )) { -__paravirt_set_sched_clock (func, true, save, restore); + (void )__paravirt_set_sched_clock (func, true, save, restore); }#endif
arch/x86/kernel/kvmclock.c +6 -3
@@ -332,10 +332,13 @@ static int kvmclock_setup_percpu(unsigned int cpu)static __init void kvm_sched_clock_init (bool stable) { +/* Ensure the offset is configured before making kvmclock visible! */ kvm_sched_clock_offset =kvm_clock_read (); -__paravirt_set_sched_clock (kvm_sched_clock_read, stable, - kvm_save_sched_clock_state, - kvm_restore_sched_clock_state); + +if (__paravirt_set_sched_clock (kvm_sched_clock_read, stable, + kvm_save_sched_clock_state, + kvm_restore_sched_clock_state)) +return ;/* * The BSP's clock is managed via dedicated sched_clock save/restore
arch/x86/kernel/tsc.c +3 -2
@@ -280,8 +280,8 @@ bool using_native_sched_clock(void)return static_call_query (pv_sched_clock) == native_sched_clock; } -void __init __paravirt_set_sched_clock (u64 (*func)(void ),bool stable, -void (*save)(void ),void (*restore)(void )) +int __init __paravirt_set_sched_clock (u64 (*func)(void ),bool stable, +void (*save)(void ),void (*restore)(void )) {if (!stable)clear_sched_clock_stable ();
@@ -289,6 +289,7 @@ void __init __paravirt_set_sched_clock(u64 (*func)(void), bool stable,static_call_update (pv_sched_clock, func); x86_platform.save_sched_clock_state = save; x86_platform.restore_sched_clock_state = restore; + return 0; }#else u64 sched_clock_noinstr (void ) __attribute__((alias ("native_sched_clock" )));
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 47/51 x86/paravirt: Don't use a PV sched_clock in CoCo guests with trusted TSC
In reply to Sean ChristophersonSilently ignore attempts to switch to a paravirt sched_clock when running as a CoCo guest with trusted TSC. In hand-wavy theory, a misbehaving hypervisor could attack the guest by manipulating the PV clock to affect guest scheduling in some weird and/or predictable way. More importantly, reading TSC on such platforms is faster than any PV clock, and sched_clock is all about speed.
--- arch/x86/kernel/tsc.c | 9 +++++++++ 1 file changed, 9 insertions(+)
arch/x86/kernel/tsc.c +9 -0
@@ -283,6 +283,15 @@ bool using_native_sched_clock(void)int __init __paravirt_set_sched_clock (u64 (*func)(void ),bool stable,void (*save)(void ),void (*restore)(void )) { +/* +* Don't replace TSC with a PV clock when running as a CoCo guest and +* the TSC is secure/trusted; PV clocks are emulated by the hypervisor, +* which isn't in the guest's TCB. +*/ +if (cc_platform_has (CC_ATTR_GUEST_SNP_SECURE_TSC ) || +boot_cpu_has (X86_FEATURE_TDX_GUEST )) +return -EPERM ; +if (!stable)clear_sched_clock_stable ();
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 48/51 x86/kvmclock: Use TSC for sched_clock if it's constant and non-stop
In reply to Sean ChristophersonPrefer the TSC over kvmclock for sched_clock if the TSC is constant and nonstop. I.e. use the same criteria as tweaking the clocksource rating so that TSC is preferred over kvmclock. Per the below comment from native_sched_clock(), sched_clock is more tolerant of slop than clocksource; using TSC for clocksource but not sched_clock makes little to no sense, especially now that KVM CoCo guests with a trusted TSC use TSC, not kvmclock.
/*
* Fall back to jiffies if there's no TSC available:
* ( But note that we still use it if the TSC is marked
* unstable. We do this because unlike Time Of Day,
* the scheduler clock tolerates small errors and it's
* very important for it to be as fast as the platform
* can achieve it. )
*/
The only advantage of using kvmclock is that doing so allows for early and common detection of PVCLOCK_GUEST_STOPPED, but that code has been broken for over two years with nary a complaint, i.e. it can't be _that_ valuable. And as above, certain types of KVM guests are losing the functionality regardless, i.e. acknowledging PVCLOCK_GUEST_STOPPED needs to be decoupled from sched_clock() no matter what.
--- arch/x86/kernel/kvmclock.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
arch/x86/kernel/kvmclock.c +2 -1
@@ -396,7 +396,6 @@ void __init kvmclock_init(bool prefer_tsc)PVCLOCK_TSC_STABLE_BIT ; } -kvm_sched_clock_init (stable);if (!x86_init.hyper.get_tsc_khz) x86_init.hyper.get_tsc_khz = kvmclock_get_tsc_khz;
@@ -416,6 +415,8 @@ void __init kvmclock_init(bool prefer_tsc)*/ if (prefer_tsc) kvm_clock.rating =299 ; +else +kvm_sched_clock_init (stable);clocksource_register_hz (&kvm_clock,NSEC_PER_SEC ); pv_info.name ="KVM" ;
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 49/51 x86/kvmclock: Plumb in AP-online and BSP-resume to kvmlock, for documentation
In reply to Sean ChristophersonInvoke kvmclock_cpu_action() with AP_ONLINE and BSP_RESUME, even though kvmclock doesn't need to do anything in either case, so that the asymmetry of kvmclock is a detail buried in kvmclock, and to explicitly document that doing nothing during those phases is intentional and correct.
For all intents and purposes, no functional change intended.
--- arch/x86/include/asm/kvm_para.h | 2 ++ arch/x86/kernel/kvm.c | 22 +++++++++++++------- arch/x86/kernel/kvmclock.c | 37 ++++++++++++++++++++++++++------- 3 files changed, 45 insertions(+), 16 deletions(-)
arch/x86/include/asm/kvm_para.h +2 -0
@@ -120,6 +120,8 @@ static inline long kvm_sev_hypercall3(unsigned int nr, unsigned long p1,#ifdef CONFIG_KVM_GUEST enum kvm_guest_cpu_action {KVM_GUEST_BSP_SUSPEND , +KVM_GUEST_BSP_RESUME , +KVM_GUEST_AP_ONLINE ,KVM_GUEST_AP_OFFLINE ,KVM_GUEST_SHUTDOWN , };
arch/x86/kernel/kvm.c +14 -8
@@ -474,18 +474,24 @@ static void kvm_guest_cpu_offline(enum kvm_guest_cpu_action action)kvmclock_cpu_action (action); } +static void __kvm_cpu_online (unsigned int cpu,enum kvm_guest_cpu_action action) +{ +unsigned long flags; + +local_irq_save (flags); +kvmclock_cpu_action (action); +kvm_guest_cpu_init (); +local_irq_restore (flags); +} + +#ifdef CONFIG_SMP +static int kvm_cpu_online (unsigned int cpu) { -unsigned long flags; - -local_irq_save (flags); -kvm_guest_cpu_init (); -local_irq_restore (flags); +__kvm_cpu_online (cpu,KVM_GUEST_AP_ONLINE );return 0 ; } -#ifdef CONFIG_SMP - static DEFINE_PER_CPU(cpumask_var_t, __pv_cpu_mask);static bool pv_tlb_flush_supported (void )
@@ -752,7 +758,7 @@ static int kvm_suspend(void *data)static void kvm_resume (void *data) { -kvm_cpu_online (raw_smp_processor_id ()); +__kvm_cpu_online (raw_smp_processor_id (),KVM_GUEST_BSP_RESUME );#ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL if (kvm_para_has_feature (KVM_FEATURE_POLL_CONTROL ) && has_guest_poll)
arch/x86/kernel/kvmclock.c +29 -8
@@ -150,7 +150,7 @@ static void kvm_save_sched_clock_state(void)#ifdef CONFIG_SMP static void kvm_setup_secondary_clock (void ) { -kvm_register_clock ("secondary cpu clock" ); +kvm_register_clock ("secondary cpu, startup" ); }#endif
@@ -174,13 +174,34 @@ static void kvmclock_resume(struct clocksource *cs)void kvmclock_cpu_action (enum kvm_guest_cpu_action action) { -/* -* Don't disable kvmclock on the BSP during suspend. If kvmclock is -* being used for sched_clock, then it needs to be kept alive until the -* last minute, and restored as quickly as possible after resume. -*/ -if (action !=KVM_GUEST_BSP_SUSPEND ) +switch (action) { +/* +* The BSP's clock is managed via clocksource suspend/resume, +* to ensure it's enabled/disabled when timekeeping needs it +* to be, e.g. before reading wallclock (which uses kvmclock). +*/ +case KVM_GUEST_BSP_SUSPEND : +case KVM_GUEST_BSP_RESUME : +break ; +case KVM_GUEST_AP_ONLINE : +/* +* Secondary CPUs use a dedicated hook to enable kvmclock early +* during bringup, there's nothing to be done during CPU online +* (which runs at CPUHP_AP_ONLINE_DYN). When kvmclock is being +* used as sched_clock, kvmclock must be enabled *very* early, +* and even when kvmclock is "only" being used for the main +* clocksource, it still needs to be enabled long before the +* dynamic CPUHP calls are made. +*/ +break ; +case KVM_GUEST_AP_OFFLINE : +case KVM_GUEST_SHUTDOWN :kvmclock_disable (); +break ; +default : +WARN_ON_ONCE (1 ); +break ; + } }/*
@@ -382,7 +403,7 @@ void __init kvmclock_init(bool prefer_tsc) msr_kvm_system_time, msr_kvm_wall_clock);this_cpu_write (hv_clock_per_cpu, &hv_clock_boot[0 ]); -kvm_register_clock ("primary cpu clock" ); +kvm_register_clock ("primary cpu, online" );pvclock_set_pvti_cpu0_va (hv_clock_boot);if (kvm_para_has_feature (KVM_FEATURE_CLOCKSOURCE_STABLE_BIT )) {
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 50/51 x86/paravirt: Move using_native_sched_clock() stub into timer.h
In reply to Sean ChristophersonNow that timer.h ended up with CONFIG_PARAVIRT #ifdeffery anyways, move the PARAVIRT=n using_native_sched_clock() stub into timer.h as a "free" optimization.
No functional change intended.
--- arch/x86/include/asm/timer.h | 6 ++++-- arch/x86/kernel/tsc.c | 2 -- 2 files changed, 4 insertions(+), 4 deletions(-)
arch/x86/include/asm/timer.h +4 -2
@@ -11,9 +11,9 @@ extern void recalibrate_cpu_khz(void);extern int no_timer_check; -extern bool using_native_sched_clock (void ); -#ifdef CONFIG_PARAVIRT +extern bool using_native_sched_clock (void ); +int __init __paravirt_set_sched_clock (u64 (*func)(void ),bool stable,void (*save)(void ),void (*restore)(void ));
@@ -23,6 +23,8 @@ static __always_inline void paravirt_set_sched_clock(u64 (*func)(void), { (void )__paravirt_set_sched_clock (func, true, save, restore); } +#else +static inline bool using_native_sched_clock (void ) {return true; }#endif /*
arch/x86/kernel/tsc.c +0 -2
@@ -302,8 +302,6 @@ int __init __paravirt_set_sched_clock(u64 (*func)(void), bool stable, }#else u64 sched_clock_noinstr (void ) __attribute__((alias ("native_sched_clock" ))); - -bool using_native_sched_clock (void ) {return true; }#endif notrace u64 sched_clock(void)
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
Sean Christopherson
maintainerPATCH v6 51/51 x86/kvm: Get local APIC bus frequency from PV CPUID Timing Info
In reply to Sean ChristophersonWhen running as a KVM guest with PV timing info provided by the host, stuff the APIC timer period/frequency with the local APIC bus frequency reported in CPUID.0x40000010.EBX instead of trying to calibrate/guess the frequency.
See Documentation/virt/kvm/x86/cpuid.rst for details.
--- arch/x86/kernel/kvm.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
arch/x86/kernel/kvm.c +6 -1
@@ -992,7 +992,7 @@ static void __init kvm_init_platform(void) .mask_lo = (u32)(~(SZ_4G - tolud - 1)) | MTRR_PHYSMASK_V, .mask_hi = (BIT_ULL(boot_cpu_data.x86_phys_bits) - 1) >> 32, }; -u32 timing_info_leaf; +u32 timing_info_leaf, apic_khz;bool tsc_is_reliable; if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) &&
@@ -1054,6 +1054,11 @@ static void __init kvm_init_platform(void) x86_init.hyper.get_tsc_khz = kvm_get_tsc_khz; x86_init.hyper.get_cpu_khz = kvm_get_tsc_khz; } + +/* The leaf also includes the local APIC bus/timer frequency.*/ + apic_khz =cpuid_ebx (timing_info_leaf); +if (apic_khz) +apic_set_timer_frequency_khz (apic_khz,"KVM hypervisor" ); }/*
Signature · 1 line
2.55.0.679.g6767b8d81c-goog
[email protected]
AI reviewRe: [PATCH v6 51/51] x86/kvm: Get local APIC bus frequency from PV CPUID Timing Info
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Missing validation of the APIC timer frequency provided by an untrusted CPUID leaf allows a…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Missing validation of the APIC timer frequency provided by an untrusted CPUID leaf allows a malicious hypervisor to cause a guest interrupt storm or timer freeze. --
--- Patch [51]: [PATCH v6 51/51] x86/kvm: Get local APIC bus frequency from PV CPUID Timing Info --- commit f6ea787ae688819e70ecd70def270210b8842a87
Author: Sean Christopherson <[email protected]>
x86/kvm: Get local APIC bus frequency from PV CPUID Timing Info
When running as a KVM guest with PV timing info provided by the host, this commit updates the code to use the local APIC bus frequency reported in CPUID.0x40000010.EBX for the APIC timer period instead of calibrating it.
Quoted 4 lines
arch/x86/kernel/kvm.c +0
-0
[ ... ]
arch/x86/kernel/kvm.c static void __init kvm_init_platform(void) · line 1061
Quoted 9 lines
arch/x86/kernel/kvm.c +5
-0@@ -1054,6 +1054,11 @@ static void __init kvm_init_platform(void) x86_init.hyper.get_tsc_khz = kvm_get_tsc_khz; x86_init.hyper.get_cpu_khz = kvm_get_tsc_khz; } + +/* The leaf also includes the local APIC bus/timer frequency.*/ + apic_khz =cpuid_ebx (timing_info_leaf); +if (apic_khz) +apic_set_timer_frequency_khz (apic_khz,"KVM hypervisor" );
[Severity: High]
Does this code allow an untrusted hypervisor to cause a guest interrupt storm or timer freeze?
In a Confidential Computing (CoCo) environment, the hypervisor could provide a maliciously small value for apic_khz in CPUID leaf 0x40000010.EBX. When this value is passed to apic_set_timer_frequency_khz(), it calculates and stores lapic_timer_period.
Later, calibrate_APIC_clock() bypasses its normal safety checks when lapic_timer_period is already set:
arch/x86/kernel/apic/apic.c:calibrate_APIC_clock() {
...
if (!lapic_init_clockevent()) {
apic_pr_verbose("lapic timer already calibrated %d\n", lapic_timer_period);
/*
* Direct calibration methods must have an always running
* local APIC timer, no need for broadcast timer.
*/
lapic_clockevent.features &= ~CLOCK_EVT_FEAT_DUMMY;
return 0;
}
...
}This early return skips the subsequent check:
if (lapic_timer_period < (1000000 / HZ))
Could a malicious hypervisor provide a small enough value that causes the timer interval (TMICT) to become 1 or 0, stopping the local timer entirely or causing an endless interrupt storm?
Quoted 3 lines
arch/x86/kernel/kvm.c +0
-0}/*
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=51
Sean Christopherson
maintainerQuoted 12 lines · Sean Christopherson
The primary goal of this series to fix flaws with SNP and TDX guests where a PV clock provided by the untrusted hypervisor is used instead of the secure TSC that is controlled by trusted firmware.
The secondary goal is modernize running under KVM. Currently, KVM guests will use TSC for clocksource, but not
sched_clock. And Linux-as-a-KVM-guest doesn't support paravirt enumeration of the TSC/APIC frequencies, even though QEMU provides that information by default.The tertiary goal is to clean up the PV clock code to deduplicate logic across hypervisors, and to hopefully make it all easier to maintain going forward.
Quoted 6 lines
The quaternary goal is to clean up the TSC calibration code, which was made stupidly hard to follow by hypervisor code mixing in with the native calibration routines, instead of being implemented as a pure alternative.
Note, the VMware and Xen changes still probably should get acks from those maintainers, as my understanding of what they're trying to do may be flawed.
This (thankfully) still applies cleanly. What can I do to help move this forward?
Quoted 13 lines · Sean Christopherson
Quoted 12 lines · Sean Christopherson
The primary goal of this series to fix flaws with SNP and TDX guests where a PV clock provided by the untrusted hypervisor is used instead of the secure TSC that is controlled by trusted firmware.
The secondary goal is modernize running under KVM. Currently, KVM guests will use TSC for clocksource, but not sched_clock. And Linux-as-a-KVM-guest doesn't support paravirt enumeration of the TSC/APIC frequencies, even though QEMU provides that information by default.
The tertiary goal is to clean up the PV clock code to deduplicate logic across hypervisors, and to hopefully make it all easier to maintain going forward.
Quoted 8 lines
Quoted 6 lines
The quaternary goal is to clean up the TSC calibration code, which was made stupidly hard to follow by hypervisor code mixing in with the native calibration routines, instead of being implemented as a pure alternative.
Note, the VMware and Xen changes still probably should get acks from those maintainers, as my understanding of what they're trying to do may be flawed.
This (thankfully) still applies cleanly. What can I do to help move this forward?
Nudge Thomas to spot that this is guest-side and we want him to pick it up, I guess?
Sean Christopherson
maintainerQuoted 18 lines · David Woodhouse
Quoted 17 lines · Sean Christopherson
Quoted 16 lines · Sean Christopherson
The primary goal of this series to fix flaws with SNP and TDX guests where a PV clock provided by the untrusted hypervisor is used instead of the secure TSC that is controlled by trusted firmware.
The secondary goal is modernize running under KVM. Currently, KVM guests will use TSC for clocksource, but not sched_clock. And Linux-as-a-KVM-guest doesn't support paravirt enumeration of the TSC/APIC frequencies, even though QEMU provides that information by default.
The tertiary goal is to clean up the PV clock code to deduplicate logic across hypervisors, and to hopefully make it all easier to maintain going forward.
The quaternary goal is to clean up the TSC calibration code, which was made stupidly hard to follow by hypervisor code mixing in with the native calibration routines, instead of being implemented as a pure alternative.
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines
Note, the VMware and Xen changes still probably should get acks from those maintainers, as my understanding of what they're trying to do may be flawed.
This (thankfully) still applies cleanly. What can I do to help move this forward?
Nudge Thomas to spot that this is guest-side and we want him to pick it up, I guess?
Amazingly, still applies cleanly on 7.4-rc1 and tip/master. I know we're shortly after the merge window, but this has been sitting idle for months and addresses issues that are impacting a variety of end users.
Note, this also provides meaningful hardening for SNP and TDX. /me stares intently in the direction of Dave and Boris.
Borislav Petkov
maintainerQuoted 24 lines · Sean Christopherson
Quoted 23 lines · David Woodhouse
Quoted 21 lines · Sean Christopherson
Quoted 12 lines · Sean Christopherson
The primary goal of this series to fix flaws with SNP and TDX guests where a PV clock provided by the untrusted hypervisor is used instead of the secure TSC that is controlled by trusted firmware.
The secondary goal is modernize running under KVM. Currently, KVM guests will use TSC for clocksource, but not sched_clock. And Linux-as-a-KVM-guest doesn't support paravirt enumeration of the TSC/APIC frequencies, even though QEMU provides that information by default.
The tertiary goal is to clean up the PV clock code to deduplicate logic across hypervisors, and to hopefully make it all easier to maintain going forward.
Quoted 6 lines
The quaternary goal is to clean up the TSC calibration code, which was made stupidly hard to follow by hypervisor code mixing in with the native calibration routines, instead of being implemented as a pure alternative.
Note, the VMware and Xen changes still probably should get acks from those maintainers, as my understanding of what they're trying to do may be flawed.
This (thankfully) still applies cleanly. What can I do to help move this forward?
Quoted 8 lines
Quoted 1 line
Nudge Thomas to spot that this is guest-side and we want him to pick it up, I guess?
Amazingly, still applies cleanly on 7.4-rc1 and tip/master. I know we're shortly after the merge window, but this has been sitting idle for months and addresses issues that are impacting a variety of end users.
Note, this also provides meaningful hardening for SNP and TDX. /me stares intently in the direction of Dave and Boris.
Would you believe me if I told you you're in the "review" mbox?
The damn thing just keeps growing constantly :-/
I would love it if we had a review scoring thing like the net folks - whoever reviews others' patches, gets looked at first... and no, I don't mean you with that.
:)
Signature · 1 line
Small device. Typos and formatting crap