timer.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * (C) Copyright 2011, Stefan Kristiansson <stefan.kristiansson@saunalahti.fi>
  3. * (C) Copyright 2011, Julius Baxter <julius@opencores.org>
  4. * (C) Copyright 2003
  5. * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
  6. *
  7. * SPDX-License-Identifier: GPL-2.0+
  8. */
  9. #include <common.h>
  10. #include <asm/system.h>
  11. #include <asm/openrisc_exc.h>
  12. static ulong timestamp;
  13. /* how many counter cycles in a jiffy */
  14. #define TIMER_COUNTER_CYCLES (CONFIG_SYS_CLK_FREQ/CONFIG_SYS_OPENRISC_TMR_HZ)
  15. /* how many ms elapses between each timer interrupt */
  16. #define TIMER_TIMESTAMP_INC (1000/CONFIG_SYS_OPENRISC_TMR_HZ)
  17. /* how many cycles per ms */
  18. #define TIMER_CYCLES_MS (CONFIG_SYS_CLK_FREQ/1000)
  19. /* how many cycles per us */
  20. #define TIMER_CYCLES_US (CONFIG_SYS_CLK_FREQ/1000000uL)
  21. void timer_isr(void)
  22. {
  23. timestamp += TIMER_TIMESTAMP_INC;
  24. mtspr(SPR_TTMR, SPR_TTMR_IE | SPR_TTMR_RT |
  25. (TIMER_COUNTER_CYCLES & SPR_TTMR_TP));
  26. }
  27. int timer_init(void)
  28. {
  29. /* Install timer exception handler */
  30. exception_install_handler(EXC_TIMER, timer_isr);
  31. /* Set up the timer for the first expiration. */
  32. timestamp = 0;
  33. mtspr(SPR_TTMR, SPR_TTMR_IE | SPR_TTMR_RT |
  34. (TIMER_COUNTER_CYCLES & SPR_TTMR_TP));
  35. /* Enable tick timer exception in supervisor register */
  36. mtspr(SPR_SR, mfspr(SPR_SR) | SPR_SR_TEE);
  37. return 0;
  38. }
  39. void reset_timer(void)
  40. {
  41. timestamp = 0;
  42. mtspr(SPR_TTMR, SPR_TTMR_IE | SPR_TTMR_RT |
  43. (TIMER_COUNTER_CYCLES & SPR_TTMR_TP));
  44. }
  45. /*
  46. * The timer value in ms is calculated by taking the
  47. * value accumulated by full timer revolutions plus the value
  48. * accumulated in this period
  49. */
  50. ulong get_timer(ulong base)
  51. {
  52. return timestamp + mfspr(SPR_TTCR)/TIMER_CYCLES_MS - base;
  53. }
  54. void set_timer(ulong t)
  55. {
  56. reset_timer();
  57. timestamp = t;
  58. }
  59. unsigned long long get_ticks(void)
  60. {
  61. return get_timer(0);
  62. }
  63. ulong get_tbclk(void)
  64. {
  65. return CONFIG_SYS_HZ;
  66. }
  67. void __udelay(ulong usec)
  68. {
  69. ulong elapsed = 0;
  70. ulong tick;
  71. ulong last_tick;
  72. last_tick = mfspr(SPR_TTCR);
  73. while ((elapsed / TIMER_CYCLES_US) < usec) {
  74. tick = mfspr(SPR_TTCR);
  75. if (tick >= last_tick)
  76. elapsed += (tick - last_tick);
  77. else
  78. elapsed += TIMER_COUNTER_CYCLES - (last_tick - tick);
  79. last_tick = tick;
  80. }
  81. }