riscv_timer.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Copyright (C) 2020, Sean Anderson <seanga2@gmail.com>
  4. * Copyright (C) 2018, Bin Meng <bmeng.cn@gmail.com>
  5. * Copyright (C) 2018, Anup Patel <anup@brainfault.org>
  6. * Copyright (C) 2012 Regents of the University of California
  7. *
  8. * RISC-V architecturally-defined generic timer driver
  9. *
  10. * This driver provides generic timer support for S-mode U-Boot.
  11. */
  12. #include <common.h>
  13. #include <dm.h>
  14. #include <errno.h>
  15. #include <fdt_support.h>
  16. #include <timer.h>
  17. #include <asm/csr.h>
  18. static u64 notrace riscv_timer_get_count(struct udevice *dev)
  19. {
  20. __maybe_unused u32 hi, lo;
  21. if (IS_ENABLED(CONFIG_64BIT))
  22. return csr_read(CSR_TIME);
  23. do {
  24. hi = csr_read(CSR_TIMEH);
  25. lo = csr_read(CSR_TIME);
  26. } while (hi != csr_read(CSR_TIMEH));
  27. return ((u64)hi << 32) | lo;
  28. }
  29. #if CONFIG_IS_ENABLED(RISCV_SMODE) && IS_ENABLED(CONFIG_TIMER_EARLY)
  30. /**
  31. * timer_early_get_rate() - Get the timer rate before driver model
  32. */
  33. unsigned long notrace timer_early_get_rate(void)
  34. {
  35. return RISCV_SMODE_TIMER_FREQ;
  36. }
  37. /**
  38. * timer_early_get_count() - Get the timer count before driver model
  39. *
  40. */
  41. u64 notrace timer_early_get_count(void)
  42. {
  43. return riscv_timer_get_count(NULL);
  44. }
  45. #endif
  46. static int riscv_timer_probe(struct udevice *dev)
  47. {
  48. struct timer_dev_priv *uc_priv = dev_get_uclass_priv(dev);
  49. u32 rate;
  50. /* When this function was called from the CPU driver, clock
  51. * frequency is passed as driver data.
  52. */
  53. rate = dev->driver_data;
  54. /* When called from an FDT match, the rate needs to be looked up. */
  55. if (!rate && gd->fdt_blob) {
  56. rate = fdt_getprop_u32_default(gd->fdt_blob,
  57. "/cpus", "timebase-frequency", 0);
  58. }
  59. uc_priv->clock_rate = rate;
  60. /* With rate==0, timer uclass post_probe might later fail with -EINVAL.
  61. * Give a hint at the cause for debugging.
  62. */
  63. if (!rate)
  64. log_err("riscv_timer_probe with invalid clock rate 0!\n");
  65. return 0;
  66. }
  67. static const struct timer_ops riscv_timer_ops = {
  68. .get_count = riscv_timer_get_count,
  69. };
  70. static const struct udevice_id riscv_timer_ids[] = {
  71. { .compatible = "riscv,timer", },
  72. { }
  73. };
  74. U_BOOT_DRIVER(riscv_timer) = {
  75. .name = "riscv_timer",
  76. .id = UCLASS_TIMER,
  77. .of_match = of_match_ptr(riscv_timer_ids),
  78. .probe = riscv_timer_probe,
  79. .ops = &riscv_timer_ops,
  80. .flags = DM_FLAG_PRE_RELOC,
  81. };