Search code examples
assemblyrdtsc

There is any way to trigger a legacy mode for RDTSC?


I rewrote the entire question, people clearly weren't understanding it.

RDTSC used to count CPU cycles, and it varied with the CPU throttling.

Currently, RDTSC don't vary with CPU throttling.

Some old applications, expect RDTSC to vary with CPU throttling.

How I make RDTSC give them what they expect?

I don't want to profile code, I don't want to rewrite massive amounts of code, I don't want to oblige users to mess with the BIOS or Kernel permissions, I just want to make legacy apps work as they should.


Solution

  • Simply put, you can't do it with a flick of a switch

    Intel Developer Manual 3B, Chapter 17, explicitly reads

    The invariant TSC will run at a constant rate in all ACPI P-, C-. and T-states. This is the architectural behavior moving forward.

    Which is another way to tell you that there is no way to switch back to the previous behavior.


    However if you really feel like it, you can try something.

    rdtsc takes its value from the IA32_TIME_STAMP_COUNTER, which is writable.
    So you can "fake" the read of rdtsc without changing any program, but you need a driver.
    Changing IA32_TIME_STAMP_COUNTER to adjust for internal clock count may not be so easy.

    I don't remember if there is a performance event that count internal clocks since reset, if there is, then in theory you have just to read that value and write in IA32_TIME_STAMP_COUNTER.
    Newer CPU also support IA32_TSC_ADJUST which can be used to adjust the TSC in a relative way: Whatever you add/subtract from IA32_TSC_ADJUST is added/subtracted from IA32_TIME_STAMP_COUNTER. So you can slow down or speed up the counter.

    Either way you need:

    • To create a driver to deliver to your users. Which may not have privileges to install it.
    • To know the exact throttling of the CPU, contrary to the vote count of gudok answer, performance counter registers are the only way to go. Unless you want to hook for OS power manager functions/events and go with educated guesses.
    • To map that throttling into a TSC value.
    • Choose how often to update the TSC (non trivial).