xref: /openbmc/u-boot/arch/arm/cpu/arm920t/ep93xx/timer.c (revision 0a98b28b)
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_masked(void)
70 {
71 	return get_ticks();
72 }
73 
74 unsigned long get_timer(unsigned long base)
75 {
76 	return get_timer_masked() - base;
77 }
78 
79 void __udelay(unsigned long usec)
80 {
81 	unsigned long long target;
82 
83 	read_timer();
84 
85 	target = timer.ticks + usecs_to_ticks(usec);
86 
87 	while (timer.ticks < target)
88 		read_timer();
89 }
90 
91 int timer_init(void)
92 {
93 	struct timer_regs *timer_regs = (struct timer_regs *)TIMER_BASE;
94 
95 	/* use timer 3 with 508KHz and free running, not enabled now */
96 	writel(TIMER_CLKSEL, &timer_regs->timer3.control);
97 
98 	/* set initial timer value */
99 	writel(TIMER_MAX_VAL, &timer_regs->timer3.load);
100 
101 	/* Enable the timer */
102 	writel(TIMER_ENABLE | TIMER_CLKSEL,
103 		&timer_regs->timer3.control);
104 
105 	/* Reset the timer */
106 	read_timer();
107 	timer.ticks = 0;
108 
109 	return 0;
110 }
111 
112 /*
113  * This function is derived from PowerPC code (timebase clock frequency).
114  * On ARM it returns the number of timer ticks per second.
115  */
116 unsigned long get_tbclk(void)
117 {
118 	return CONFIG_SYS_HZ;
119 }
120