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