delay_timer.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (c) 2015-2019, ARM Limited and Contributors. All rights reserved.
  3. *
  4. * SPDX-License-Identifier: BSD-3-Clause
  5. */
  6. #include <assert.h>
  7. #include <platform_def.h>
  8. #include <drivers/delay_timer.h>
  9. #include <lib/utils_def.h>
  10. /***********************************************************
  11. * The delay timer implementation
  12. ***********************************************************/
  13. static const timer_ops_t *timer_ops;
  14. /***********************************************************
  15. * Delay for the given number of microseconds. The driver must
  16. * be initialized before calling this function.
  17. ***********************************************************/
  18. void udelay(uint32_t usec)
  19. {
  20. assert((timer_ops != NULL) &&
  21. (timer_ops->clk_mult != 0U) &&
  22. (timer_ops->clk_div != 0U) &&
  23. (timer_ops->get_timer_value != NULL));
  24. uint32_t start, delta;
  25. uint64_t total_delta;
  26. assert(usec < (UINT64_MAX / timer_ops->clk_div));
  27. start = timer_ops->get_timer_value();
  28. /* Add an extra tick to avoid delaying less than requested. */
  29. total_delta =
  30. div_round_up((uint64_t)usec * timer_ops->clk_div,
  31. timer_ops->clk_mult) + 1U;
  32. /*
  33. * Precaution for the total_delta ~ UINT32_MAX and the fact that we
  34. * cannot catch every tick of the timer.
  35. * For example 100MHz timer over 25MHz APB will miss at least 4 ticks.
  36. * 1000U is an arbitrary big number which is believed to be sufficient.
  37. */
  38. assert(total_delta < (UINT32_MAX - 1000U));
  39. do {
  40. /*
  41. * If the timer value wraps around, the subtraction will
  42. * overflow and it will still give the correct result.
  43. * delta is decreasing counter
  44. */
  45. delta = start - timer_ops->get_timer_value();
  46. } while (delta < total_delta);
  47. }
  48. /***********************************************************
  49. * Delay for the given number of milliseconds. The driver must
  50. * be initialized before calling this function.
  51. ***********************************************************/
  52. void mdelay(uint32_t msec)
  53. {
  54. assert((msec * 1000UL) < UINT32_MAX);
  55. udelay(msec * 1000U);
  56. }
  57. /***********************************************************
  58. * Initialize the timer. The fields in the provided timer
  59. * ops pointer must be valid.
  60. ***********************************************************/
  61. void timer_init(const timer_ops_t *ops_ptr)
  62. {
  63. assert((ops_ptr != NULL) &&
  64. (ops_ptr->clk_mult != 0U) &&
  65. (ops_ptr->clk_div != 0U) &&
  66. (ops_ptr->get_timer_value != NULL));
  67. timer_ops = ops_ptr;
  68. }