cputime_cortexm.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (c) 2006-2023, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2017-12-23 Bernard first version
  9. * 2022-06-14 Meco Man suuport pref_counter
  10. */
  11. #include <rthw.h>
  12. #include <rtdevice.h>
  13. #include <rtthread.h>
  14. #include <board.h>
  15. #ifdef PKG_USING_PERF_COUNTER
  16. #include <perf_counter.h>
  17. #endif
  18. /* Use Cycle counter of Data Watchpoint and Trace Register for CPU time */
  19. static uint64_t cortexm_cputime_getres(void)
  20. {
  21. uint64_t ret = 1000UL * 1000 * 1000;
  22. ret = (ret * (1000UL * 1000)) / SystemCoreClock;
  23. return ret;
  24. }
  25. static uint64_t cortexm_cputime_gettime(void)
  26. {
  27. #ifdef PKG_USING_PERF_COUNTER
  28. return get_system_ticks();
  29. #else
  30. return DWT->CYCCNT;
  31. #endif
  32. }
  33. const static struct rt_clock_cputime_ops _cortexm_ops =
  34. {
  35. cortexm_cputime_getres,
  36. cortexm_cputime_gettime
  37. };
  38. int cortexm_cputime_init(void)
  39. {
  40. #ifdef PKG_USING_PERF_COUNTER
  41. clock_cpu_setops(&_cortexm_ops);
  42. #else
  43. /* check support bit */
  44. if ((DWT->CTRL & (1UL << DWT_CTRL_NOCYCCNT_Pos)) == 0)
  45. {
  46. /* enable trace*/
  47. CoreDebug->DEMCR |= (1UL << CoreDebug_DEMCR_TRCENA_Pos);
  48. /* whether cycle counter not enabled */
  49. if ((DWT->CTRL & (1UL << DWT_CTRL_CYCCNTENA_Pos)) == 0)
  50. {
  51. /* enable cycle counter */
  52. DWT->CTRL |= (1UL << DWT_CTRL_CYCCNTENA_Pos);
  53. }
  54. clock_cpu_setops(&_cortexm_ops);
  55. }
  56. #endif /* PKG_USING_PERF_COUNTER */
  57. return 0;
  58. }
  59. INIT_BOARD_EXPORT(cortexm_cputime_init);