Monday, January 27, 2014

Reading Clock Counters in Processors

There are clock counters on x86, MIPS & ARM.

These clock count register can be accessed from userspace and kernel space.

x86
===
__asm__ __volatile__("rdtsc" : "=A" (tsc));

ARM 11 & higher  (mcr and mrc register)
==============
 __asm__ __volatile__("mcr p15, 0, %0, c15, c9, 0" ::"r"(0x1));  // Access validation

__asm__ __volatile__("mrc p15, 0, %0, c15, c12, 1" : "=r"(tsc));  //Read Clock Counter

MIPS (mtc & rdhwr  register)
====
__asm__ __volatile__("mtc0 %0, $7" :: "r"(0x40000000)); //Enable hw register

__asm__ __volatile__("rdhwr %0, $2" : "=r"(tsc));   //Read Clock Counter