229e9e959e41d9030be3e3efb5a5af57f7dc55d4
[oweals/u-boot.git] / arch / arm / cpu / armv7 / vf610 / timer.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright 2013 Freescale Semiconductor, Inc.
4  */
5
6 #include <common.h>
7 #include <init.h>
8 #include <time.h>
9 #include <asm/io.h>
10 #include <div64.h>
11 #include <asm/arch/imx-regs.h>
12 #include <asm/arch/clock.h>
13
14 static struct pit_reg *cur_pit = (struct pit_reg *)PIT_BASE_ADDR;
15
16 DECLARE_GLOBAL_DATA_PTR;
17
18 #define TIMER_LOAD_VAL  0xffffffff
19
20 static inline unsigned long long tick_to_time(unsigned long long tick)
21 {
22         tick *= CONFIG_SYS_HZ;
23         do_div(tick, mxc_get_clock(MXC_IPG_CLK));
24
25         return tick;
26 }
27
28 static inline unsigned long long us_to_tick(unsigned long long usec)
29 {
30         usec = usec * mxc_get_clock(MXC_IPG_CLK)  + 999999;
31         do_div(usec, 1000000);
32
33         return usec;
34 }
35
36 int timer_init(void)
37 {
38         __raw_writel(0, &cur_pit->mcr);
39
40         __raw_writel(TIMER_LOAD_VAL, &cur_pit->ldval1);
41         __raw_writel(0, &cur_pit->tctrl1);
42         __raw_writel(1, &cur_pit->tctrl1);
43
44         gd->arch.tbl = 0;
45         gd->arch.tbu = 0;
46
47         return 0;
48 }
49
50 unsigned long long get_ticks(void)
51 {
52         ulong now = TIMER_LOAD_VAL - __raw_readl(&cur_pit->cval1);
53
54         /* increment tbu if tbl has rolled over */
55         if (now < gd->arch.tbl)
56                 gd->arch.tbu++;
57         gd->arch.tbl = now;
58
59         return (((unsigned long long)gd->arch.tbu) << 32) | gd->arch.tbl;
60 }
61
62 ulong get_timer(ulong base)
63 {
64         return tick_to_time(get_ticks()) - base;
65 }
66
67 /* delay x useconds AND preserve advance timstamp value */
68 void __udelay(unsigned long usec)
69 {
70         unsigned long long start;
71         ulong tmo;
72
73         start = get_ticks();                    /* get current timestamp */
74         tmo = us_to_tick(usec);                 /* convert usecs to ticks */
75         while ((get_ticks() - start) < tmo)
76                 ;                               /* loop till time has passed */
77 }
78
79 /*
80  * This function is derived from PowerPC code (timebase clock frequency).
81  * On ARM it returns the number of timer ticks per second.
82  */
83 ulong get_tbclk(void)
84 {
85         return mxc_get_clock(MXC_IPG_CLK);
86 }