# Linux Kernel Module Cheat

#### 29.13.1. x86 RDTSC instruction

Sources:

- userland/arch/x86_64/rdtsc.S

- userland/arch/x86_64/intrinsics/rdtsc.c

Try running the programs multiple times, and watch the value increase, and then try to correlate it with `/proc/cpuinfo` frequency!

    while true; do sleep 1 && ./userland/arch/x86_64/rdtsc.out; done

RDTSC stores its output to EDX:EAX, even in 64-bit mode, top bits are zeroed out.

TODO: review this section, make a more controlled userland experiment with m5ops instrumentation.

Let’s have some fun and try to correlate the gem5 m5out/stats.txt file `system.cpu.numCycles` cycle count with the x86 RDTSC instruction that is supposed to do the same thing:

    ./build-userland userland/arch/x86_64/inline_asm/rdtsc.S
    ./run --eval './arch/x86_64/rdtsc.out;m5 exit;' --emulator gem5
    ./gem5-stat

RDTSC outputs a cycle count which we compare with gem5’s `gem5-stat`:

- `3828578153`: RDTSC

- `3830832635`: `gem5-stat`

which gives pretty close results, and serve as a nice sanity check that the cycle counter is coherent.

It is also nice to see that RDTSC is a bit smaller than the `stats.txt` value, since the latter also includes the exec syscall for `m5`.

Bibliography:

- https://en.wikipedia.org/wiki/Time_Stamp_Counter

- https://stackoverflow.com/questions/13772567/how-to-get-the-cpu-cycle-count-in-x86-64-from-c

- https://stackoverflow.com/questions/9887839/clock-cycle-count-wth-gcc/9887979

- x86 RDTSCP instruction