1 // SPDX-License-Identifier: GPL-2.0+
4 * David Feng <fenghua@phytium.com.cn>
11 #include <asm/system.h>
13 DECLARE_GLOBAL_DATA_PTR;
16 * Generic timer implementation of get_tbclk()
18 unsigned long get_tbclk(void)
21 asm volatile("mrs %0, cntfrq_el0" : "=r" (cntfrq));
25 #ifdef CONFIG_SYS_FSL_ERRATUM_A008585
27 * FSL erratum A-008585 says that the ARM generic timer counter "has the
28 * potential to contain an erroneous value for a small number of core
29 * clock cycles every time the timer value changes".
30 * This sometimes leads to a consecutive counter read returning a lower
31 * value than the previous one, thus reporting the time to go backwards.
32 * The workaround is to read the counter twice and only return when the value
33 * was the same in both reads.
34 * Assumes that the CPU runs in much higher frequency than the timer.
36 unsigned long timer_read_counter(void)
42 asm volatile("mrs %0, cntpct_el0" : "=r" (cntpct));
43 asm volatile("mrs %0, cntpct_el0" : "=r" (temp));
44 while (temp != cntpct) {
45 asm volatile("mrs %0, cntpct_el0" : "=r" (cntpct));
46 asm volatile("mrs %0, cntpct_el0" : "=r" (temp));
51 #elif CONFIG_SUNXI_A64_TIMER_ERRATUM
53 * This erratum sometimes flips the lower 11 bits of the counter value
54 * to all 0's or all 1's, leading to jumps forwards or backwards.
55 * Backwards jumps might be interpreted all roll-overs and be treated as
57 * The workaround is to check whether the lower 11 bits of the counter are
58 * all 0 or all 1, then discard this value and read again.
59 * This occasionally discards valid values, but will catch all erroneous
60 * reads and fixes the problem reliably. Also this mostly requires only a
61 * single read, so does not have any significant overhead.
62 * The algorithm was conceived by Samuel Holland.
64 unsigned long timer_read_counter(void)
70 asm volatile("mrs %0, cntpct_el0" : "=r" (cntpct));
71 } while (((cntpct + 1) & GENMASK(10, 0)) <= 1);
77 * timer_read_counter() using the Arm Generic Timer (aka arch timer).
79 unsigned long timer_read_counter(void)
84 asm volatile("mrs %0, cntpct_el0" : "=r" (cntpct));
90 uint64_t get_ticks(void)
92 unsigned long ticks = timer_read_counter();
99 unsigned long usec2ticks(unsigned long usec)
103 ticks = ((usec * (get_tbclk()/1000)) + 500) / 1000;
105 ticks = ((usec / 10) * (get_tbclk() / 100000));
110 ulong timer_get_boot_us(void)
112 u64 val = get_ticks() * 1000000;
114 return val / get_tbclk();