]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - arch/sh/lib/time.c
Merge git://git.denx.de/u-boot-arm
[karo-tx-uboot.git] / arch / sh / lib / time.c
1 /*
2  * (C) Copyright 2009
3  * Jean-Christophe PLAGNIOL-VILLARD <plagnioj@jcrosoft.com>
4  *
5  * (C) Copyright 2007-2012
6  * Nobobuhiro Iwamatsu <iwamatsu@nigauri.org>
7  *
8  * (C) Copyright 2003
9  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
10  *
11  * SPDX-License-Identifier:     GPL-2.0+
12  */
13
14 #include <common.h>
15 #include <div64.h>
16 #include <asm/processor.h>
17 #include <asm/io.h>
18 #include <sh_tmu.h>
19
20 static struct tmu_regs *tmu = (struct tmu_regs *)TMU_BASE;
21
22 static u16 bit;
23 static unsigned long last_tcnt;
24 static unsigned long long overflow_ticks;
25
26 unsigned long get_tbclk(void)
27 {
28         return get_tmu0_clk_rate() >> ((bit + 1) * 2);
29 }
30
31 static inline unsigned long long tick_to_time(unsigned long long tick)
32 {
33         tick *= CONFIG_SYS_HZ;
34         do_div(tick, get_tbclk());
35
36         return tick;
37 }
38
39 static inline unsigned long long usec_to_tick(unsigned long long usec)
40 {
41         usec *= get_tbclk();
42         do_div(usec, 1000000);
43
44         return usec;
45 }
46
47 static void tmu_timer_start(unsigned int timer)
48 {
49         if (timer > 2)
50                 return;
51         writeb(readb(&tmu->tstr) | (1 << timer), &tmu->tstr);
52 }
53
54 static void tmu_timer_stop(unsigned int timer)
55 {
56         if (timer > 2)
57                 return;
58         writeb(readb(&tmu->tstr) & ~(1 << timer), &tmu->tstr);
59 }
60
61 int timer_init(void)
62 {
63         bit = (ffs(CONFIG_SYS_TMU_CLK_DIV) >> 1) - 1;
64         writew(readw(&tmu->tcr0) | bit, &tmu->tcr0);
65
66         tmu_timer_stop(0);
67         tmu_timer_start(0);
68
69         last_tcnt = 0;
70         overflow_ticks = 0;
71
72         return 0;
73 }
74
75 unsigned long long get_ticks(void)
76 {
77         unsigned long tcnt = 0 - readl(&tmu->tcnt0);
78
79         if (last_tcnt > tcnt) /* overflow */
80                 overflow_ticks++;
81         last_tcnt = tcnt;
82
83         return (overflow_ticks << 32) | tcnt;
84 }
85
86 void __udelay(unsigned long usec)
87 {
88         unsigned long long tmp;
89         ulong tmo;
90
91         tmo = usec_to_tick(usec);
92         tmp = get_ticks() + tmo;        /* get current timestamp */
93
94         while (get_ticks() < tmp)       /* loop till event */
95                  /*NOP*/;
96 }
97
98 unsigned long get_timer(unsigned long base)
99 {
100         /* return msec */
101         return tick_to_time(get_ticks()) - base;
102 }
103
104 void set_timer(unsigned long t)
105 {
106         writel((0 - t), &tmu->tcnt0);
107 }
108
109 void reset_timer(void)
110 {
111         tmu_timer_stop(0);
112         set_timer(0);
113         tmu_timer_start(0);
114 }