tick.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2018/10/28 Bernard The unify RISC-V porting code.
  9. * 2024/07/08 Shell Using clock_time as tick
  10. */
  11. #include <rthw.h>
  12. #include <rtthread.h>
  13. #include <encoding.h>
  14. #include "sbi.h"
  15. #ifdef RT_USING_CLOCK_TIME
  16. #include <drivers/clock_time.h>
  17. #endif
  18. static volatile unsigned long tick_cycles = 0;
  19. static rt_uint64_t _clock_timer_freq = 0;
  20. rt_weak rt_uint64_t rt_hw_get_clock_timer_freq(void)
  21. {
  22. return CLOCK_TIMER_FREQ;
  23. }
  24. static rt_uint64_t _riscv_read_time(void)
  25. {
  26. unsigned long time_elapsed;
  27. __asm__ __volatile__("rdtime %0" : "=r"(time_elapsed));
  28. return (rt_uint64_t)time_elapsed;
  29. }
  30. int tick_isr(void)
  31. {
  32. rt_tick_increase();
  33. sbi_set_timer(_riscv_read_time() + tick_cycles);
  34. return 0;
  35. }
  36. /* Sets and enable the timer interrupt */
  37. int rt_hw_tick_init(void)
  38. {
  39. rt_uint64_t freq = rt_hw_get_clock_timer_freq();
  40. RT_ASSERT(freq != 0);
  41. _clock_timer_freq = freq;
  42. /* calculate the tick cycles */
  43. tick_cycles = freq / RT_TICK_PER_SECOND;
  44. /* Clear the Supervisor-Timer bit in SIE */
  45. clear_csr(sie, SIP_STIP);
  46. /* Set timer */
  47. sbi_set_timer(_riscv_read_time() + tick_cycles);
  48. #ifdef RT_USING_CLOCK_TIME
  49. rt_clock_time_source_init();
  50. #endif
  51. /* Enable the Supervisor-Timer bit in SIE */
  52. set_csr(sie, SIP_STIP);
  53. return 0;
  54. }
  55. /**
  56. * This function will delay for some us.
  57. *
  58. * @param us the delay time of us
  59. */
  60. void rt_hw_us_delay(rt_uint32_t us)
  61. {
  62. unsigned long start_time;
  63. unsigned long end_time;
  64. unsigned long run_time;
  65. rt_uint64_t freq;
  66. start_time = _riscv_read_time();
  67. freq = _clock_timer_freq ? _clock_timer_freq : rt_hw_get_clock_timer_freq();
  68. RT_ASSERT(freq != 0);
  69. end_time = start_time + (rt_uint64_t)us * freq / 1000000ULL;
  70. do
  71. {
  72. run_time = _riscv_read_time();
  73. } while(run_time < end_time);
  74. }