1 // SPDX-License-Identifier: GPL-2.0+
3 * (C) Copyright 2007-2011
4 * Allwinner Technology Co., Ltd. <www.allwinnertech.com>
5 * Tom Cubie <tangliang@allwinnertech.com>
10 #include <asm/arch/timer.h>
12 DECLARE_GLOBAL_DATA_PTR;
14 #define TIMER_MODE (0x0 << 7) /* continuous mode */
15 #define TIMER_DIV (0x0 << 4) /* pre scale 1 */
16 #define TIMER_SRC (0x1 << 2) /* osc24m */
17 #define TIMER_RELOAD (0x1 << 1) /* reload internal value */
18 #define TIMER_EN (0x1 << 0) /* enable timer */
20 #define TIMER_CLOCK (24 * 1000 * 1000)
21 #define COUNT_TO_USEC(x) ((x) / 24)
22 #define USEC_TO_COUNT(x) ((x) * 24)
23 #define TICKS_PER_HZ (TIMER_CLOCK / CONFIG_SYS_HZ)
24 #define TICKS_TO_HZ(x) ((x) / TICKS_PER_HZ)
26 #define TIMER_LOAD_VAL 0xffffffff
28 #define TIMER_NUM 0 /* we use timer 0 */
30 /* read the 32-bit timer */
31 static ulong read_timer(void)
33 struct sunxi_timer_reg *timers =
34 (struct sunxi_timer_reg *)SUNXI_TIMER_BASE;
35 struct sunxi_timer *timer = &timers->timer[TIMER_NUM];
38 * The hardware timer counts down, therefore we invert to
39 * produce an incrementing timer.
41 return ~readl(&timer->val);
44 /* init timer register */
47 struct sunxi_timer_reg *timers =
48 (struct sunxi_timer_reg *)SUNXI_TIMER_BASE;
49 struct sunxi_timer *timer = &timers->timer[TIMER_NUM];
50 writel(TIMER_LOAD_VAL, &timer->inter);
51 writel(TIMER_MODE | TIMER_DIV | TIMER_SRC | TIMER_RELOAD | TIMER_EN,
57 /* timer without interrupts */
58 static ulong get_timer_masked(void)
60 /* current tick value */
61 ulong now = TICKS_TO_HZ(read_timer());
63 if (now >= gd->arch.lastinc) /* normal (non rollover) */
64 gd->arch.tbl += (now - gd->arch.lastinc);
67 gd->arch.tbl += (TICKS_TO_HZ(TIMER_LOAD_VAL)
68 - gd->arch.lastinc) + now;
70 gd->arch.lastinc = now;
75 ulong get_timer(ulong base)
77 return get_timer_masked() - base;
80 /* delay x useconds */
81 void __udelay(unsigned long usec)
83 long tmo = USEC_TO_COUNT(usec);
84 ulong now, last = read_timer();
88 if (now > last) /* normal (non rollover) */
91 tmo -= TIMER_LOAD_VAL - last + now;
97 * This function is derived from PowerPC code (read timebase as long long).
98 * On ARM it just returns the timer value.
100 unsigned long long get_ticks(void)
106 * This function is derived from PowerPC code (timebase clock frequency).
107 * On ARM it returns the number of timer ticks per second.
109 ulong get_tbclk(void)
111 return CONFIG_SYS_HZ;