generic_delay_timer.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (c) 2016-2024, Arm Limited and Contributors. All rights reserved.
  3. * Copyright (c) 2020, NVIDIA Corporation. All rights reserved.
  4. *
  5. * SPDX-License-Identifier: BSD-3-Clause
  6. */
  7. #include <assert.h>
  8. #include <arch_features.h>
  9. #include <arch_helpers.h>
  10. #include <common/bl_common.h>
  11. #include <common/debug.h>
  12. #include <drivers/delay_timer.h>
  13. #include <drivers/generic_delay_timer.h>
  14. #include <lib/utils_def.h>
  15. #include <plat/common/platform.h>
  16. static timer_ops_t ops;
  17. static uint64_t timeout_cnt_us2cnt(uint32_t us)
  18. {
  19. return ((uint64_t)us * (uint64_t)read_cntfrq_el0()) / 1000000ULL;
  20. }
  21. static uint64_t generic_delay_timeout_init_us(uint32_t us)
  22. {
  23. uint64_t cnt = timeout_cnt_us2cnt(us);
  24. cnt += read_cntpct_el0();
  25. return cnt;
  26. }
  27. static bool generic_delay_timeout_elapsed(uint64_t expire_cnt)
  28. {
  29. return read_cntpct_el0() > expire_cnt;
  30. }
  31. static uint32_t generic_delay_get_timer_value(void)
  32. {
  33. /*
  34. * Generic delay timer implementation expects the timer to be a down
  35. * counter. We apply bitwise NOT operator to the tick values returned
  36. * by read_cntpct_el0() to simulate the down counter. The value is
  37. * clipped from 64 to 32 bits.
  38. */
  39. return (uint32_t)(~read_cntpct_el0());
  40. }
  41. void generic_delay_timer_init_args(uint32_t mult, uint32_t div)
  42. {
  43. ops.get_timer_value = generic_delay_get_timer_value;
  44. ops.clk_mult = mult;
  45. ops.clk_div = div;
  46. ops.timeout_init_us = generic_delay_timeout_init_us;
  47. ops.timeout_elapsed = generic_delay_timeout_elapsed;
  48. timer_init(&ops);
  49. VERBOSE("Generic delay timer configured with mult=%u and div=%u\n",
  50. mult, div);
  51. }
  52. void generic_delay_timer_init(void)
  53. {
  54. assert(is_armv7_gentimer_present());
  55. /* Value in ticks */
  56. unsigned int mult = MHZ_TICKS_PER_SEC;
  57. /* Value in ticks per second (Hz) */
  58. unsigned int div = plat_get_syscnt_freq2();
  59. /* Reduce multiplier and divider by dividing them repeatedly by 10 */
  60. while (((mult % 10U) == 0U) && ((div % 10U) == 0U)) {
  61. mult /= 10U;
  62. div /= 10U;
  63. }
  64. generic_delay_timer_init_args(mult, div);
  65. }