timer.c 1.8 KB

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