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