sandbox_i2c.c 2.1 KB

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