Search code examples
clinuxtimerlinux-kernel

Why do we have coarse variants of ktime_get in Linux kernel?


I was going through the following link:

https://www.kernel.org/doc/html/latest/core-api/timekeeping.html

We have both coarse (ktime_get_coarse()) and non-coarse (ktime_get()) versions.

Which one should we use and when?

It says coarse versions are faster than non-coarse versions.

Do the non-coarse versions read the hardware counter or not?


Solution

  • Q:

    Which one should we use and when?

    Seems it's well described on your link.
    A:

    These are quicker than the non-coarse versions, but less accurate.

    So if you need to be quick and you don't care about accuracy - use coarse (there will be inaccuracy right up to 10ms with 100HZ and just up to 1ms with 1000HZ). If accuracy is a priority, then use non-coarse API.


    Q:

    Whether the non-coarse versions reads the hardware counter or not?

    A:
    ktime_get() (unlike the ktime_get_coarse()) eventually invokes timekeeping_get_delta() which reads clocksource with tk_clock_read():

    static inline u64 tk_clock_read(const struct tk_read_base *tkr)
    {
        struct clocksource *clock = READ_ONCE(tkr->clock);
    
        return clock->read(clock);
    }
    

    Inside it invokes an appropriate callback for hardware timer to read.
    You can search for such callbacks in your sources grepping through the clocksources: grep -rnI 'read =' drivers/clocksource.
    E.g. here is setting of tpu_clocksource_read().