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>
12 #include <asm/arch/timer.h>
14 DECLARE_GLOBAL_DATA_PTR;
16 #define TIMER_MODE (0x0 << 7) /* continuous mode */
17 #define TIMER_DIV (0x0 << 4) /* pre scale 1 */
18 #define TIMER_SRC (0x1 << 2) /* osc24m */
19 #define TIMER_RELOAD (0x1 << 1) /* reload internal value */
20 #define TIMER_EN (0x1 << 0) /* enable timer */
22 #define TIMER_CLOCK (24 * 1000 * 1000)
23 #define COUNT_TO_USEC(x) ((x) / 24)
24 #define USEC_TO_COUNT(x) ((x) * 24)
25 #define TICKS_PER_HZ (TIMER_CLOCK / CONFIG_SYS_HZ)
26 #define TICKS_TO_HZ(x) ((x) / TICKS_PER_HZ)
28 #define TIMER_LOAD_VAL 0xffffffff
30 #define TIMER_NUM 0 /* we use timer 0 */
32 /* read the 32-bit timer */
33 static ulong read_timer(void)
35 struct sunxi_timer_reg *timers =
36 (struct sunxi_timer_reg *)SUNXI_TIMER_BASE;
37 struct sunxi_timer *timer = &timers->timer[TIMER_NUM];
40 * The hardware timer counts down, therefore we invert to
41 * produce an incrementing timer.
43 return ~readl(&timer->val);
46 /* init timer register */
49 struct sunxi_timer_reg *timers =
50 (struct sunxi_timer_reg *)SUNXI_TIMER_BASE;
51 struct sunxi_timer *timer = &timers->timer[TIMER_NUM];
52 writel(TIMER_LOAD_VAL, &timer->inter);
53 writel(TIMER_MODE | TIMER_DIV | TIMER_SRC | TIMER_RELOAD | TIMER_EN,
59 /* timer without interrupts */
60 static ulong get_timer_masked(void)
62 /* current tick value */
63 ulong now = TICKS_TO_HZ(read_timer());
65 if (now >= gd->arch.lastinc) /* normal (non rollover) */
66 gd->arch.tbl += (now - gd->arch.lastinc);
69 gd->arch.tbl += (TICKS_TO_HZ(TIMER_LOAD_VAL)
70 - gd->arch.lastinc) + now;
72 gd->arch.lastinc = now;
77 ulong get_timer(ulong base)
79 return get_timer_masked() - base;
82 /* delay x useconds */
83 void __udelay(unsigned long usec)
85 long tmo = USEC_TO_COUNT(usec);
86 ulong now, last = read_timer();
90 if (now > last) /* normal (non rollover) */
93 tmo -= TIMER_LOAD_VAL - last + now;
99 * This function is derived from PowerPC code (read timebase as long long).
100 * On ARM it just returns the timer value.
102 unsigned long long get_ticks(void)
108 * This function is derived from PowerPC code (timebase clock frequency).
109 * On ARM it returns the number of timer ticks per second.
111 ulong get_tbclk(void)
113 return CONFIG_SYS_HZ;