1 /*
2  * Copyright (C) 2011 Vladimir Zapolskiy <vz@mleia.com>
3  *
4  * SPDX-License-Identifier:	GPL-2.0+
5  */
6 
7 #include <common.h>
8 #include <asm/arch/cpu.h>
9 #include <asm/arch/clk.h>
10 #include <asm/arch/timer.h>
11 #include <asm/io.h>
12 
13 static struct timer_regs  *timer0 = (struct timer_regs *)TIMER0_BASE;
14 static struct timer_regs  *timer1 = (struct timer_regs *)TIMER1_BASE;
15 static struct clk_pm_regs *clk    = (struct clk_pm_regs *)CLK_PM_BASE;
16 
17 static void lpc32xx_timer_clock(u32 bit, int enable)
18 {
19 	if (enable)
20 		setbits_le32(&clk->timclk_ctrl1, bit);
21 	else
22 		clrbits_le32(&clk->timclk_ctrl1, bit);
23 }
24 
25 static void lpc32xx_timer_reset(struct timer_regs *timer, u32 freq)
26 {
27 	writel(TIMER_TCR_COUNTER_RESET,   &timer->tcr);
28 	writel(TIMER_TCR_COUNTER_DISABLE, &timer->tcr);
29 	writel(0, &timer->tc);
30 	writel(0, &timer->pr);
31 
32 	/* Count mode is every rising PCLK edge */
33 	writel(TIMER_CTCR_MODE_TIMER, &timer->ctcr);
34 
35 	/* Set prescale counter value */
36 	writel((get_periph_clk_rate() / freq) - 1, &timer->pr);
37 }
38 
39 static void lpc32xx_timer_count(struct timer_regs *timer, int enable)
40 {
41 	if (enable)
42 		writel(TIMER_TCR_COUNTER_ENABLE,  &timer->tcr);
43 	else
44 		writel(TIMER_TCR_COUNTER_DISABLE, &timer->tcr);
45 }
46 
47 int timer_init(void)
48 {
49 	lpc32xx_timer_clock(CLK_TIMCLK_TIMER0, 1);
50 	lpc32xx_timer_reset(timer0, CONFIG_SYS_HZ);
51 	lpc32xx_timer_count(timer0, 1);
52 
53 	return 0;
54 }
55 
56 ulong get_timer(ulong base)
57 {
58 	return readl(&timer0->tc) - base;
59 }
60 
61 void __udelay(unsigned long usec)
62 {
63 	lpc32xx_timer_clock(CLK_TIMCLK_TIMER1, 1);
64 	lpc32xx_timer_reset(timer1, CONFIG_SYS_HZ * 1000);
65 	lpc32xx_timer_count(timer1, 1);
66 
67 	while (readl(&timer1->tc) < usec)
68 		/* NOP */;
69 
70 	lpc32xx_timer_count(timer1, 0);
71 	lpc32xx_timer_clock(CLK_TIMCLK_TIMER1, 0);
72 }
73 
74 unsigned long long get_ticks(void)
75 {
76 	return get_timer(0);
77 }
78 
79 ulong get_tbclk(void)
80 {
81 	return CONFIG_SYS_HZ;
82 }
83