xref: /openbmc/u-boot/arch/arm/cpu/arm920t/ep93xx/timer.c (revision 8d773c4a)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Cirrus Logic EP93xx timer support.
4  *
5  * Copyright (C) 2009, 2010 Matthias Kaehlcke <matthias@kaehlcke.net>
6  *
7  * Copyright (C) 2004, 2005
8  * Cory T. Tusar, Videon Central, Inc., <ctusar@videon-central.com>
9  *
10  * Based on the original intr.c Cirrus Logic EP93xx Rev D. interrupt support,
11  * author unknown.
12  */
13 
14 #include <common.h>
15 #include <linux/types.h>
16 #include <asm/arch/ep93xx.h>
17 #include <asm/io.h>
18 #include <div64.h>
19 
20 #define TIMER_CLKSEL	(1 << 3)
21 #define TIMER_ENABLE	(1 << 7)
22 
23 #define TIMER_FREQ			508469		/* ticks / second */
24 #define TIMER_MAX_VAL			0xFFFFFFFF
25 
26 static struct ep93xx_timer
27 {
28 	unsigned long long ticks;
29 	unsigned long last_read;
30 } timer;
31 
32 static inline unsigned long long usecs_to_ticks(unsigned long usecs)
33 {
34 	unsigned long long ticks = (unsigned long long)usecs * TIMER_FREQ;
35 	do_div(ticks, 1000 * 1000);
36 
37 	return ticks;
38 }
39 
40 static inline void read_timer(void)
41 {
42 	struct timer_regs *timer_regs = (struct timer_regs *)TIMER_BASE;
43 	const unsigned long now = TIMER_MAX_VAL - readl(&timer_regs->timer3.value);
44 
45 	if (now >= timer.last_read)
46 		timer.ticks += now - timer.last_read;
47 	else
48 		/* an overflow occurred */
49 		timer.ticks += TIMER_MAX_VAL - timer.last_read + now;
50 
51 	timer.last_read = now;
52 }
53 
54 /*
55  * Get the number of ticks (in CONFIG_SYS_HZ resolution)
56  */
57 unsigned long long get_ticks(void)
58 {
59 	unsigned long long sys_ticks;
60 
61 	read_timer();
62 
63 	sys_ticks = timer.ticks * CONFIG_SYS_HZ;
64 	do_div(sys_ticks, TIMER_FREQ);
65 
66 	return sys_ticks;
67 }
68 
69 unsigned long get_timer(unsigned long base)
70 {
71 	return get_ticks() - base;
72 }
73 
74 void __udelay(unsigned long usec)
75 {
76 	unsigned long long target;
77 
78 	read_timer();
79 
80 	target = timer.ticks + usecs_to_ticks(usec);
81 
82 	while (timer.ticks < target)
83 		read_timer();
84 }
85 
86 int timer_init(void)
87 {
88 	struct timer_regs *timer_regs = (struct timer_regs *)TIMER_BASE;
89 
90 	/* use timer 3 with 508KHz and free running, not enabled now */
91 	writel(TIMER_CLKSEL, &timer_regs->timer3.control);
92 
93 	/* set initial timer value */
94 	writel(TIMER_MAX_VAL, &timer_regs->timer3.load);
95 
96 	/* Enable the timer */
97 	writel(TIMER_ENABLE | TIMER_CLKSEL,
98 		&timer_regs->timer3.control);
99 
100 	/* Reset the timer */
101 	read_timer();
102 	timer.ticks = 0;
103 
104 	return 0;
105 }
106 
107 /*
108  * This function is derived from PowerPC code (timebase clock frequency).
109  * On ARM it returns the number of timer ticks per second.
110  */
111 unsigned long get_tbclk(void)
112 {
113 	return CONFIG_SYS_HZ;
114 }
115