sandbox_i2c.c 2.2 KB

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