i2c-eeprom.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * (C) Copyright 2019 Collabora
  4. * (C) Copyright 2019 GE
  5. */
  6. #include <common.h>
  7. #include <bootcount.h>
  8. #include <dm.h>
  9. #include <i2c_eeprom.h>
  10. #include <log.h>
  11. static const u8 bootcount_magic = 0xbc;
  12. struct bootcount_i2c_eeprom_priv {
  13. struct udevice *i2c_eeprom;
  14. u32 offset;
  15. };
  16. static int bootcount_i2c_eeprom_set(struct udevice *dev, const u32 a)
  17. {
  18. struct bootcount_i2c_eeprom_priv *priv = dev_get_priv(dev);
  19. const u16 val = bootcount_magic << 8 | (a & 0xff);
  20. if (i2c_eeprom_write(priv->i2c_eeprom, priv->offset,
  21. (uint8_t *)&val, 2) < 0) {
  22. debug("%s: write failed\n", __func__);
  23. return -EIO;
  24. }
  25. return 0;
  26. }
  27. static int bootcount_i2c_eeprom_get(struct udevice *dev, u32 *a)
  28. {
  29. struct bootcount_i2c_eeprom_priv *priv = dev_get_priv(dev);
  30. u16 val;
  31. if (i2c_eeprom_read(priv->i2c_eeprom, priv->offset,
  32. (uint8_t *)&val, 2) < 0) {
  33. debug("%s: read failed\n", __func__);
  34. return -EIO;
  35. }
  36. if (val >> 8 == bootcount_magic) {
  37. *a = val & 0xff;
  38. return 0;
  39. }
  40. debug("%s: bootcount magic does not match on %04x\n", __func__, val);
  41. return -EIO;
  42. }
  43. static int bootcount_i2c_eeprom_probe(struct udevice *dev)
  44. {
  45. struct ofnode_phandle_args phandle_args;
  46. struct bootcount_i2c_eeprom_priv *priv = dev_get_priv(dev);
  47. struct udevice *i2c_eeprom;
  48. if (dev_read_phandle_with_args(dev, "i2c-eeprom", NULL, 0, 0,
  49. &phandle_args)) {
  50. debug("%s: i2c-eeprom backing device not specified\n",
  51. dev->name);
  52. return -ENOENT;
  53. }
  54. if (uclass_get_device_by_ofnode(UCLASS_I2C_EEPROM, phandle_args.node,
  55. &i2c_eeprom)) {
  56. debug("%s: could not get backing device\n", dev->name);
  57. return -ENODEV;
  58. }
  59. priv->i2c_eeprom = i2c_eeprom;
  60. priv->offset = dev_read_u32_default(dev, "offset", 0);
  61. return 0;
  62. }
  63. static const struct bootcount_ops bootcount_i2c_eeprom_ops = {
  64. .get = bootcount_i2c_eeprom_get,
  65. .set = bootcount_i2c_eeprom_set,
  66. };
  67. static const struct udevice_id bootcount_i2c_eeprom_ids[] = {
  68. { .compatible = "u-boot,bootcount-i2c-eeprom" },
  69. { }
  70. };
  71. U_BOOT_DRIVER(bootcount_spi_flash) = {
  72. .name = "bootcount-i2c-eeprom",
  73. .id = UCLASS_BOOTCOUNT,
  74. .priv_auto = sizeof(struct bootcount_i2c_eeprom_priv),
  75. .probe = bootcount_i2c_eeprom_probe,
  76. .of_match = bootcount_i2c_eeprom_ids,
  77. .ops = &bootcount_i2c_eeprom_ops,
  78. };