emul_rtc.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Copyright 2020, Heinrich Schuchardt <xypron.glpk@gmx.de>
  4. *
  5. * This driver emulates a real time clock based on timer ticks.
  6. */
  7. #include <common.h>
  8. #include <div64.h>
  9. #include <dm.h>
  10. #include <env.h>
  11. #include <generated/timestamp_autogenerated.h>
  12. #include <rtc.h>
  13. /**
  14. * struct emul_rtc - private data for emulated RTC driver
  15. */
  16. struct emul_rtc {
  17. /**
  18. * @offset_us: microseconds from 1970-01-01 to timer_get_us() base
  19. */
  20. u64 offset_us;
  21. /**
  22. * @isdst: daylight saving time
  23. */
  24. int isdst;
  25. };
  26. static int emul_rtc_get(struct udevice *dev, struct rtc_time *time)
  27. {
  28. struct emul_rtc *priv = dev_get_priv(dev);
  29. u64 now;
  30. now = timer_get_us() + priv->offset_us;
  31. do_div(now, 1000000);
  32. rtc_to_tm(now, time);
  33. time->tm_isdst = priv->isdst;
  34. return 0;
  35. }
  36. static int emul_rtc_set(struct udevice *dev, const struct rtc_time *time)
  37. {
  38. struct emul_rtc *priv = dev_get_priv(dev);
  39. if (time->tm_year < 1970)
  40. return -EINVAL;
  41. priv->offset_us = rtc_mktime(time) * 1000000ULL - timer_get_us();
  42. if (time->tm_isdst > 0)
  43. priv->isdst = 1;
  44. else if (time->tm_isdst < 0)
  45. priv->isdst = -1;
  46. else
  47. priv->isdst = 0;
  48. return 0;
  49. }
  50. int emul_rtc_probe(struct udevice *dev)
  51. {
  52. struct emul_rtc *priv = dev_get_priv(dev);
  53. const char *epoch_str;
  54. u64 epoch;
  55. epoch_str = env_get("rtc_emul_epoch");
  56. if (epoch_str) {
  57. epoch = simple_strtoull(epoch_str, NULL, 10);
  58. } else {
  59. /* Use the build date as initial time */
  60. epoch = U_BOOT_EPOCH;
  61. }
  62. priv->offset_us = epoch * 1000000ULL - timer_get_us();
  63. priv->isdst = -1;
  64. return 0;
  65. }
  66. static const struct rtc_ops emul_rtc_ops = {
  67. .get = emul_rtc_get,
  68. .set = emul_rtc_set,
  69. };
  70. U_BOOT_DRIVER(rtc_emul) = {
  71. .name = "rtc_emul",
  72. .id = UCLASS_RTC,
  73. .ops = &emul_rtc_ops,
  74. .probe = emul_rtc_probe,
  75. .priv_auto_alloc_size = sizeof(struct emul_rtc),
  76. };
  77. U_BOOT_DEVICE(rtc_emul) = {
  78. .name = "rtc_emul",
  79. };