sandbox_i2c.c 2.0 KB

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