timer.c 2.2 KB

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