anrieff / libcpuid

a small C library for x86 CPU detection and feature extraction
Other
451 stars 106 forks source link

Support TSC frequency from cpuid #124

Closed KUGA2 closed 3 months ago

KUGA2 commented 5 years ago

There is no interface to return it. For new chips its:

Nominal TSC frequency = ( CPUID.15H.ECX[31:0] * CPUID.15H.EBX[31:0] ) ÷ CPUID.15H.EAX[31:0]

See Intel® 64 and IA-32 Architectures Software Developers Manual Volume 3 (3A, 3B, 3C & 3D): Chapter 18.7.3 Determining the Processor Base Frequency

There may be a fallback for old chips to calculate / measure it since we cannot access MSR. Of course this value only makes sense if TSC is invariant.

(Maybe i am wrong, but i did not find it in source code)

foool commented 2 years ago

Hi, the latest CPU I could get is I9-9900K and Xeon Scalable Gold 6146, and their CPUID(15) outpus are:

eax=0x00000002 ebx=0x0000012c ecx=0x00000000 edx=0x00000000 (I9-9900K)
eax=0x00000002 ebx=0x00000100 ecx=0x00000000 edx=0x00000000 (gold 6146)

Although CPUID.15H.ECX (indicates the nominal core crystal clock frequency in Hz according to the Intel manual) is not enumerated, I found the latest Linux kernel has already supported this equation to calculate the TSC frequency (see https://elixir.bootlin.com/linux/v5.18.10/source/arch/x86/kernel/tsc.c#L635 ). Does anyone know any newer Intel CPU that enumerates the nominal core crystal clock frequency correctly?

anrieff commented 2 years ago

Re: @KUGA2 I see no harm in implementing this equation and deciding on whether it should be performed based on the values of ECX and EAX. If both are nonzero (and the equation results in a nonzero result), we'll claim this is the correct TSC frequency. Of course it's best if we can test this on a new enough CPU, but I'm inclined to trust the Linux kernel developers :)

TheTumultuousUnicornOfDarkness commented 3 months ago

Added cpu_clock_by_tsc() in 1ac6898da08b72661935e135dff8dbfaa4749767.