clock_gettime()
clock_gettime()
retrieves the time kept by the kernel starting from the
point when timekeeping module is initialized. A user-space application can also get the
timestamp from a device that is sourced from time stamp counter (TSC) that runs after
reset. To synchronize the system time and readings from TSC, an offset in ns is needed
to be used as below:
clock_gettime(MONOTONIC_RAW) = cycle_ns(TSC) - offset_ns
The offset_ns can be calculated with below
API:
uint64_t readOffsetNs()
{
unsigned long raw_nsec, tsc_ns;
unsigned long cycles, frq;
struct timespec tp;
asm volatile("mrs %0, cntfrq_el0" : "=r"(frq));
asm volatile("mrs %0, cntvct_el0" : "=r"(cycles));
clock_gettime(CLOCK_MONOTONIC_RAW, &tp);
tsc_ns = (cycles / frq) * 1000000000;
raw_nsec = tp.tv_sec * 1000000000 + tp.tv_nsec;
uint64_t offset_ns = llabs(tsc_ns-raw_nsec);
return offset_ns;
}