timer.c 1.8 KB

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