2 * ARM Cortex M3/M4/M7 SysTick timer driver
3 * (C) Copyright 2017 Renesas Electronics Europe Ltd
5 * Based on arch/arm/mach-stm32/stm32f1/timer.c
7 * Kamil Lulko, <kamil.lulko@gmail.com>
9 * Copyright 2015 ATS Advanced Telematics Systems GmbH
10 * Copyright 2015 Konsulko Group, Matt Porter <mporter@konsulko.com>
12 * SPDX-License-Identifier: GPL-2.0+
14 * The SysTick timer is a 24-bit count down timer. The clock can be either the
15 * CPU clock or a reference clock. Since the timer will wrap around very quickly
16 * when using the CPU clock, and we do not handle the timer interrupts, it is
17 * expected that this driver is only ever used with a slow reference clock.
19 * The number of reference clock ticks that correspond to 10ms is normally
20 * defined in the SysTick Calibration register's TENMS field. However, on some
21 * devices this is wrong, so this driver allows the clock rate to be defined
22 * using CONFIG_SYS_HZ_CLOCK.
28 DECLARE_GLOBAL_DATA_PTR;
30 /* SysTick Base Address - fixed for all Cortex M3, M4 and M7 devices */
31 #define SYSTICK_BASE 0xE000E010
40 #define TIMER_MAX_VAL 0x00FFFFFF
41 #define SYSTICK_CTRL_EN BIT(0)
42 /* Clock source: 0 = Ref clock, 1 = CPU clock */
43 #define SYSTICK_CTRL_CPU_CLK BIT(2)
44 #define SYSTICK_CAL_NOREF BIT(31)
45 #define SYSTICK_CAL_SKEW BIT(30)
46 #define SYSTICK_CAL_TENMS_MASK 0x00FFFFFF
48 /* read the 24-bit timer */
49 static ulong read_timer(void)
51 struct cm3_systick *systick = (struct cm3_systick *)SYSTICK_BASE;
53 /* The timer counts down, therefore convert to an incrementing timer */
54 return TIMER_MAX_VAL - readl(&systick->current_val);
59 struct cm3_systick *systick = (struct cm3_systick *)SYSTICK_BASE;
62 writel(TIMER_MAX_VAL, &systick->reload_val);
63 /* Any write to current_val reg clears it to 0 */
64 writel(0, &systick->current_val);
66 cal = readl(&systick->calibration);
67 if (cal & SYSTICK_CAL_NOREF)
68 /* Use CPU clock, no interrupts */
69 writel(SYSTICK_CTRL_EN | SYSTICK_CTRL_CPU_CLK, &systick->ctrl);
71 /* Use external clock, no interrupts */
72 writel(SYSTICK_CTRL_EN, &systick->ctrl);
75 * If the TENMS field is inexact or wrong, specify the clock rate using
76 * CONFIG_SYS_HZ_CLOCK.
78 #if defined(CONFIG_SYS_HZ_CLOCK)
79 gd->arch.timer_rate_hz = CONFIG_SYS_HZ_CLOCK;
81 gd->arch.timer_rate_hz = (cal & SYSTICK_CAL_TENMS_MASK) * 100;
86 gd->arch.lastinc = read_timer();
91 /* return milli-seconds timer value */
92 ulong get_timer(ulong base)
94 unsigned long long t = get_ticks() * 1000;
96 return (ulong)((t / gd->arch.timer_rate_hz)) - base;
99 unsigned long long get_ticks(void)
101 u32 now = read_timer();
103 if (now >= gd->arch.lastinc)
104 gd->arch.tbl += (now - gd->arch.lastinc);
106 gd->arch.tbl += (TIMER_MAX_VAL - gd->arch.lastinc) + now;
108 gd->arch.lastinc = now;
113 ulong get_tbclk(void)
115 return gd->arch.timer_rate_hz;