rtc.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * (C) Copyright 2018 Theobroma Systems Design und Consulting GmbH
  4. */
  5. #include <common.h>
  6. #include <bootcount.h>
  7. #include <dm.h>
  8. #include <log.h>
  9. #include <rtc.h>
  10. static const u8 bootcount_magic = 0xbc;
  11. struct bootcount_rtc_priv {
  12. struct udevice *rtc;
  13. u32 offset;
  14. };
  15. static int bootcount_rtc_set(struct udevice *dev, const u32 a)
  16. {
  17. struct bootcount_rtc_priv *priv = dev_get_priv(dev);
  18. const u16 val = bootcount_magic << 8 | (a & 0xff);
  19. if (rtc_write16(priv->rtc, priv->offset, val) < 0) {
  20. debug("%s: rtc_write16 failed\n", __func__);
  21. return -EIO;
  22. }
  23. return 0;
  24. }
  25. static int bootcount_rtc_get(struct udevice *dev, u32 *a)
  26. {
  27. struct bootcount_rtc_priv *priv = dev_get_priv(dev);
  28. u16 val;
  29. if (rtc_read16(priv->rtc, priv->offset, &val) < 0) {
  30. debug("%s: rtc_write16 failed\n", __func__);
  31. return -EIO;
  32. }
  33. if (val >> 8 == bootcount_magic) {
  34. *a = val & 0xff;
  35. return 0;
  36. }
  37. debug("%s: bootcount magic does not match on %04x\n", __func__, val);
  38. return -EIO;
  39. }
  40. static int bootcount_rtc_probe(struct udevice *dev)
  41. {
  42. struct ofnode_phandle_args phandle_args;
  43. struct bootcount_rtc_priv *priv = dev_get_priv(dev);
  44. struct udevice *rtc;
  45. if (dev_read_phandle_with_args(dev, "rtc", NULL, 0, 0, &phandle_args)) {
  46. debug("%s: rtc backing device not specified\n", dev->name);
  47. return -ENOENT;
  48. }
  49. if (uclass_get_device_by_ofnode(UCLASS_RTC, phandle_args.node, &rtc)) {
  50. debug("%s: could not get backing device\n", dev->name);
  51. return -ENODEV;
  52. }
  53. priv->rtc = rtc;
  54. priv->offset = dev_read_u32_default(dev, "offset", 0);
  55. return 0;
  56. }
  57. static const struct bootcount_ops bootcount_rtc_ops = {
  58. .get = bootcount_rtc_get,
  59. .set = bootcount_rtc_set,
  60. };
  61. static const struct udevice_id bootcount_rtc_ids[] = {
  62. { .compatible = "u-boot,bootcount-rtc" },
  63. { }
  64. };
  65. U_BOOT_DRIVER(bootcount_rtc) = {
  66. .name = "bootcount-rtc",
  67. .id = UCLASS_BOOTCOUNT,
  68. .priv_auto_alloc_size = sizeof(struct bootcount_rtc_priv),
  69. .probe = bootcount_rtc_probe,
  70. .of_match = bootcount_rtc_ids,
  71. .ops = &bootcount_rtc_ops,
  72. };