sandbox_i2c.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 dm_sandbox_i2c_emul_priv {
  19. struct udevice *emul;
  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. static int sandbox_i2c_xfer(struct udevice *bus, struct i2c_msg *msg,
  43. int nmsgs)
  44. {
  45. struct dm_i2c_bus *i2c = dev_get_uclass_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 (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. /*
  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 ? 400000 : 100000)) {
  65. debug("%s: Max speed exceeded\n", __func__);
  66. return -EINVAL;
  67. }
  68. return ops->xfer(emul, msg, nmsgs);
  69. }
  70. static const struct dm_i2c_ops sandbox_i2c_ops = {
  71. .xfer = sandbox_i2c_xfer,
  72. };
  73. static const struct udevice_id sandbox_i2c_ids[] = {
  74. { .compatible = "sandbox,i2c" },
  75. { }
  76. };
  77. U_BOOT_DRIVER(i2c_sandbox) = {
  78. .name = "i2c_sandbox",
  79. .id = UCLASS_I2C,
  80. .of_match = sandbox_i2c_ids,
  81. .ops = &sandbox_i2c_ops,
  82. };