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