timer.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. /*
  2. * (C) Copyright 2015
  3. * Kamil Lulko, <kamil.lulko@gmail.com>
  4. *
  5. * SPDX-License-Identifier: GPL-2.0+
  6. */
  7. #include <common.h>
  8. #include <asm/io.h>
  9. #include <asm/armv7m.h>
  10. #include <asm/arch/stm32.h>
  11. DECLARE_GLOBAL_DATA_PTR;
  12. #define STM32_TIM2_BASE (STM32_APB1PERIPH_BASE + 0x0000)
  13. #define RCC_APB1ENR_TIM2EN (1 << 0)
  14. struct stm32_tim2_5 {
  15. u32 cr1;
  16. u32 cr2;
  17. u32 smcr;
  18. u32 dier;
  19. u32 sr;
  20. u32 egr;
  21. u32 ccmr1;
  22. u32 ccmr2;
  23. u32 ccer;
  24. u32 cnt;
  25. u32 psc;
  26. u32 arr;
  27. u32 reserved1;
  28. u32 ccr1;
  29. u32 ccr2;
  30. u32 ccr3;
  31. u32 ccr4;
  32. u32 reserved2;
  33. u32 dcr;
  34. u32 dmar;
  35. u32 or;
  36. };
  37. #define TIM_CR1_CEN (1 << 0)
  38. #define TIM_EGR_UG (1 << 0)
  39. int timer_init(void)
  40. {
  41. struct stm32_tim2_5 *tim = (struct stm32_tim2_5 *)STM32_TIM2_BASE;
  42. setbits_le32(&STM32_RCC->apb1enr, RCC_APB1ENR_TIM2EN);
  43. if (clock_get(CLOCK_AHB) == clock_get(CLOCK_APB1))
  44. writel((clock_get(CLOCK_APB1) / CONFIG_SYS_HZ_CLOCK) - 1,
  45. &tim->psc);
  46. else
  47. writel(((clock_get(CLOCK_APB1) * 2) / CONFIG_SYS_HZ_CLOCK) - 1,
  48. &tim->psc);
  49. writel(0xFFFFFFFF, &tim->arr);
  50. writel(TIM_CR1_CEN, &tim->cr1);
  51. setbits_le32(&tim->egr, TIM_EGR_UG);
  52. gd->arch.tbl = 0;
  53. gd->arch.tbu = 0;
  54. gd->arch.lastinc = 0;
  55. return 0;
  56. }
  57. ulong get_timer(ulong base)
  58. {
  59. return (get_ticks() / (CONFIG_SYS_HZ_CLOCK / CONFIG_SYS_HZ)) - base;
  60. }
  61. unsigned long long get_ticks(void)
  62. {
  63. struct stm32_tim2_5 *tim = (struct stm32_tim2_5 *)STM32_TIM2_BASE;
  64. u32 now;
  65. now = readl(&tim->cnt);
  66. if (now >= gd->arch.lastinc)
  67. gd->arch.tbl += (now - gd->arch.lastinc);
  68. else
  69. gd->arch.tbl += (0xFFFFFFFF - gd->arch.lastinc) + now;
  70. gd->arch.lastinc = now;
  71. return gd->arch.tbl;
  72. }
  73. void reset_timer(void)
  74. {
  75. struct stm32_tim2_5 *tim = (struct stm32_tim2_5 *)STM32_TIM2_BASE;
  76. gd->arch.lastinc = readl(&tim->cnt);
  77. gd->arch.tbl = 0;
  78. }
  79. /* delay x useconds */
  80. void __udelay(ulong usec)
  81. {
  82. unsigned long long start;
  83. start = get_ticks(); /* get current timestamp */
  84. while ((get_ticks() - start) < usec)
  85. ; /* loop till time has passed */
  86. }
  87. /*
  88. * This function is derived from PowerPC code (timebase clock frequency).
  89. * On ARM it returns the number of timer ticks per second.
  90. */
  91. ulong get_tbclk(void)
  92. {
  93. return CONFIG_SYS_HZ_CLOCK;
  94. }