time.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. #include <common.h>
  14. #include <div64.h>
  15. #include <asm/processor.h>
  16. #include <asm/io.h>
  17. #include <sh_tmu.h>
  18. #define TCR_TPSC 0x07
  19. static struct tmu_regs *tmu = (struct tmu_regs *)TMU_BASE;
  20. static unsigned long last_tcnt;
  21. static unsigned long long overflow_ticks;
  22. unsigned long get_tbclk(void)
  23. {
  24. u16 tmu_bit = (ffs(CONFIG_SYS_TMU_CLK_DIV) >> 1) - 1;
  25. return get_tmu0_clk_rate() >> ((tmu_bit + 1) * 2);
  26. }
  27. static inline unsigned long long tick_to_time(unsigned long long tick)
  28. {
  29. tick *= CONFIG_SYS_HZ;
  30. do_div(tick, get_tbclk());
  31. return tick;
  32. }
  33. static inline unsigned long long usec_to_tick(unsigned long long usec)
  34. {
  35. usec *= get_tbclk();
  36. do_div(usec, 1000000);
  37. return usec;
  38. }
  39. static void tmu_timer_start(unsigned int timer)
  40. {
  41. if (timer > 2)
  42. return;
  43. writeb(readb(&tmu->tstr) | (1 << timer), &tmu->tstr);
  44. }
  45. static void tmu_timer_stop(unsigned int timer)
  46. {
  47. if (timer > 2)
  48. return;
  49. writeb(readb(&tmu->tstr) & ~(1 << timer), &tmu->tstr);
  50. }
  51. int timer_init(void)
  52. {
  53. u16 tmu_bit = (ffs(CONFIG_SYS_TMU_CLK_DIV) >> 1) - 1;
  54. writew((readw(&tmu->tcr0) & ~TCR_TPSC) | tmu_bit, &tmu->tcr0);
  55. tmu_timer_stop(0);
  56. tmu_timer_start(0);
  57. last_tcnt = 0;
  58. overflow_ticks = 0;
  59. return 0;
  60. }
  61. unsigned long long get_ticks(void)
  62. {
  63. unsigned long tcnt = 0 - readl(&tmu->tcnt0);
  64. if (last_tcnt > tcnt) /* overflow */
  65. overflow_ticks++;
  66. last_tcnt = tcnt;
  67. return (overflow_ticks << 32) | tcnt;
  68. }
  69. void __udelay(unsigned long usec)
  70. {
  71. unsigned long long tmp;
  72. ulong tmo;
  73. tmo = usec_to_tick(usec);
  74. tmp = get_ticks() + tmo; /* get current timestamp */
  75. while (get_ticks() < tmp) /* loop till event */
  76. /*NOP*/;
  77. }
  78. unsigned long get_timer(unsigned long base)
  79. {
  80. /* return msec */
  81. return tick_to_time(get_ticks()) - base;
  82. }
  83. void set_timer(unsigned long t)
  84. {
  85. writel((0 - t), &tmu->tcnt0);
  86. }
  87. void reset_timer(void)
  88. {
  89. tmu_timer_stop(0);
  90. set_timer(0);
  91. tmu_timer_start(0);
  92. }