timer.c 1.8 KB

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