timer.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Copyright 2013 Freescale Semiconductor, Inc.
  4. */
  5. #include <common.h>
  6. #include <time.h>
  7. #include <asm/io.h>
  8. #include <div64.h>
  9. #include <asm/arch/imx-regs.h>
  10. #include <asm/arch/clock.h>
  11. static struct pit_reg *cur_pit = (struct pit_reg *)PIT_BASE_ADDR;
  12. DECLARE_GLOBAL_DATA_PTR;
  13. #define TIMER_LOAD_VAL 0xffffffff
  14. static inline unsigned long long tick_to_time(unsigned long long tick)
  15. {
  16. tick *= CONFIG_SYS_HZ;
  17. do_div(tick, mxc_get_clock(MXC_IPG_CLK));
  18. return tick;
  19. }
  20. static inline unsigned long long us_to_tick(unsigned long long usec)
  21. {
  22. usec = usec * mxc_get_clock(MXC_IPG_CLK) + 999999;
  23. do_div(usec, 1000000);
  24. return usec;
  25. }
  26. int timer_init(void)
  27. {
  28. __raw_writel(0, &cur_pit->mcr);
  29. __raw_writel(TIMER_LOAD_VAL, &cur_pit->ldval1);
  30. __raw_writel(0, &cur_pit->tctrl1);
  31. __raw_writel(1, &cur_pit->tctrl1);
  32. gd->arch.tbl = 0;
  33. gd->arch.tbu = 0;
  34. return 0;
  35. }
  36. unsigned long long get_ticks(void)
  37. {
  38. ulong now = TIMER_LOAD_VAL - __raw_readl(&cur_pit->cval1);
  39. /* increment tbu if tbl has rolled over */
  40. if (now < gd->arch.tbl)
  41. gd->arch.tbu++;
  42. gd->arch.tbl = now;
  43. return (((unsigned long long)gd->arch.tbu) << 32) | gd->arch.tbl;
  44. }
  45. ulong get_timer(ulong base)
  46. {
  47. return tick_to_time(get_ticks()) - base;
  48. }
  49. /* delay x useconds AND preserve advance timstamp value */
  50. void __udelay(unsigned long usec)
  51. {
  52. unsigned long long start;
  53. ulong tmo;
  54. start = get_ticks(); /* get current timestamp */
  55. tmo = us_to_tick(usec); /* convert usecs to ticks */
  56. while ((get_ticks() - start) < tmo)
  57. ; /* loop till time has passed */
  58. }
  59. /*
  60. * This function is derived from PowerPC code (timebase clock frequency).
  61. * On ARM it returns the number of timer ticks per second.
  62. */
  63. ulong get_tbclk(void)
  64. {
  65. return mxc_get_clock(MXC_IPG_CLK);
  66. }