sandbox_i2c.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Simulate an I2C port
  4. *
  5. * Copyright (c) 2014 Google, Inc
  6. */
  7. #include <common.h>
  8. #include <dm.h>
  9. #include <errno.h>
  10. #include <i2c.h>
  11. #include <log.h>
  12. #include <asm/i2c.h>
  13. #include <asm/test.h>
  14. #include <dm/acpi.h>
  15. #include <dm/lists.h>
  16. #include <dm/device-internal.h>
  17. static int get_emul(struct udevice *dev, struct udevice **devp,
  18. struct dm_i2c_ops **opsp)
  19. {
  20. struct dm_i2c_chip *plat;
  21. int ret;
  22. *devp = NULL;
  23. *opsp = NULL;
  24. plat = dev_get_parent_plat(dev);
  25. if (!plat->emul) {
  26. ret = i2c_emul_find(dev, &plat->emul);
  27. if (ret)
  28. return ret;
  29. }
  30. *devp = plat->emul;
  31. *opsp = i2c_get_ops(plat->emul);
  32. return 0;
  33. }
  34. void sandbox_i2c_set_test_mode(struct udevice *bus, bool test_mode)
  35. {
  36. struct sandbox_i2c_priv *priv = dev_get_priv(bus);
  37. priv->test_mode = test_mode;
  38. }
  39. static int sandbox_i2c_xfer(struct udevice *bus, struct i2c_msg *msg,
  40. int nmsgs)
  41. {
  42. struct dm_i2c_bus *i2c = dev_get_uclass_priv(bus);
  43. struct sandbox_i2c_priv *priv = dev_get_priv(bus);
  44. struct dm_i2c_ops *ops;
  45. struct udevice *emul, *dev;
  46. bool is_read;
  47. int ret;
  48. /* Special test code to return success but with no emulation */
  49. if (priv->test_mode && msg->addr == SANDBOX_I2C_TEST_ADDR)
  50. return 0;
  51. ret = i2c_get_chip(bus, msg->addr, 1, &dev);
  52. if (ret)
  53. return ret;
  54. ret = get_emul(dev, &emul, &ops);
  55. if (ret)
  56. return ret;
  57. if (priv->test_mode) {
  58. /*
  59. * For testing, don't allow writing above 100KHz for writes and
  60. * 400KHz for reads.
  61. */
  62. is_read = nmsgs > 1;
  63. if (i2c->speed_hz > (is_read ? I2C_SPEED_FAST_RATE :
  64. I2C_SPEED_STANDARD_RATE)) {
  65. debug("%s: Max speed exceeded\n", __func__);
  66. return -EINVAL;
  67. }
  68. }
  69. return ops->xfer(emul, msg, nmsgs);
  70. }
  71. static const struct dm_i2c_ops sandbox_i2c_ops = {
  72. .xfer = sandbox_i2c_xfer,
  73. };
  74. static const struct udevice_id sandbox_i2c_ids[] = {
  75. { .compatible = "sandbox,i2c" },
  76. { }
  77. };
  78. U_BOOT_DRIVER(sandbox_i2c) = {
  79. .name = "sandbox_i2c",
  80. .id = UCLASS_I2C,
  81. .of_match = sandbox_i2c_ids,
  82. .ops = &sandbox_i2c_ops,
  83. .priv_auto = sizeof(struct sandbox_i2c_priv),
  84. };