blob: 163f4616d3f9f92c96a667e73c1207273eaa09f6 [file] [log] [blame]
rev13@wp.plfec465a2015-03-01 12:44:40 +01001/*
2 * (C) Copyright 2015
Kamil Lulkodecd33b2015-11-29 11:50:53 +01003 * Kamil Lulko, <kamil.lulko@gmail.com>
rev13@wp.plfec465a2015-03-01 12:44:40 +01004 *
5 * SPDX-License-Identifier: GPL-2.0+
6 */
7
8#include <common.h>
Patrice Chotardd11d3912017-11-15 13:14:53 +01009#include <stm32_rcc.h>
rev13@wp.plfec465a2015-03-01 12:44:40 +010010#include <asm/io.h>
11#include <asm/armv7m.h>
12#include <asm/arch/stm32.h>
13
14DECLARE_GLOBAL_DATA_PTR;
15
16#define STM32_TIM2_BASE (STM32_APB1PERIPH_BASE + 0x0000)
17
18#define RCC_APB1ENR_TIM2EN (1 << 0)
19
20struct stm32_tim2_5 {
21 u32 cr1;
22 u32 cr2;
23 u32 smcr;
24 u32 dier;
25 u32 sr;
26 u32 egr;
27 u32 ccmr1;
28 u32 ccmr2;
29 u32 ccer;
30 u32 cnt;
31 u32 psc;
32 u32 arr;
33 u32 reserved1;
34 u32 ccr1;
35 u32 ccr2;
36 u32 ccr3;
37 u32 ccr4;
38 u32 reserved2;
39 u32 dcr;
40 u32 dmar;
41 u32 or;
42};
43
44#define TIM_CR1_CEN (1 << 0)
45
46#define TIM_EGR_UG (1 << 0)
47
48int timer_init(void)
49{
50 struct stm32_tim2_5 *tim = (struct stm32_tim2_5 *)STM32_TIM2_BASE;
51
52 setbits_le32(&STM32_RCC->apb1enr, RCC_APB1ENR_TIM2EN);
53
54 if (clock_get(CLOCK_AHB) == clock_get(CLOCK_APB1))
55 writel((clock_get(CLOCK_APB1) / CONFIG_SYS_HZ_CLOCK) - 1,
56 &tim->psc);
57 else
58 writel(((clock_get(CLOCK_APB1) * 2) / CONFIG_SYS_HZ_CLOCK) - 1,
59 &tim->psc);
60
61 writel(0xFFFFFFFF, &tim->arr);
62 writel(TIM_CR1_CEN, &tim->cr1);
63 setbits_le32(&tim->egr, TIM_EGR_UG);
64
65 gd->arch.tbl = 0;
66 gd->arch.tbu = 0;
67 gd->arch.lastinc = 0;
68
69 return 0;
70}
71
72ulong get_timer(ulong base)
73{
74 return (get_ticks() / (CONFIG_SYS_HZ_CLOCK / CONFIG_SYS_HZ)) - base;
75}
76
77unsigned long long get_ticks(void)
78{
79 struct stm32_tim2_5 *tim = (struct stm32_tim2_5 *)STM32_TIM2_BASE;
80 u32 now;
81
82 now = readl(&tim->cnt);
83
84 if (now >= gd->arch.lastinc)
85 gd->arch.tbl += (now - gd->arch.lastinc);
86 else
87 gd->arch.tbl += (0xFFFFFFFF - gd->arch.lastinc) + now;
88
89 gd->arch.lastinc = now;
90
91 return gd->arch.tbl;
92}
93
94void reset_timer(void)
95{
96 struct stm32_tim2_5 *tim = (struct stm32_tim2_5 *)STM32_TIM2_BASE;
97
98 gd->arch.lastinc = readl(&tim->cnt);
99 gd->arch.tbl = 0;
100}
101
102/* delay x useconds */
103void __udelay(ulong usec)
104{
105 unsigned long long start;
106
107 start = get_ticks(); /* get current timestamp */
108 while ((get_ticks() - start) < usec)
109 ; /* loop till time has passed */
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 */
116ulong get_tbclk(void)
117{
118 return CONFIG_SYS_HZ_CLOCK;
119}