sandbox_i2c.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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 *priv;
  25. int ret;
  26. *devp = NULL;
  27. *opsp = NULL;
  28. priv = dev_get_parentdata(dev);
  29. if (!priv->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, &priv->emul);
  35. if (ret)
  36. return ret;
  37. }
  38. *devp = priv->emul;
  39. *opsp = i2c_get_ops(priv->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 = bus->uclass_priv;
  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, &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. return -EINVAL;
  66. return ops->xfer(emul, msg, nmsgs);
  67. }
  68. static const struct dm_i2c_ops sandbox_i2c_ops = {
  69. .xfer = sandbox_i2c_xfer,
  70. };
  71. static int sandbox_i2c_child_pre_probe(struct udevice *dev)
  72. {
  73. struct dm_i2c_chip *i2c_chip = dev_get_parentdata(dev);
  74. /* Ignore our test address */
  75. if (i2c_chip->chip_addr == SANDBOX_I2C_TEST_ADDR)
  76. return 0;
  77. if (dev->of_offset == -1)
  78. return 0;
  79. return i2c_chip_ofdata_to_platdata(gd->fdt_blob, dev->of_offset,
  80. i2c_chip);
  81. }
  82. static const struct udevice_id sandbox_i2c_ids[] = {
  83. { .compatible = "sandbox,i2c" },
  84. { }
  85. };
  86. U_BOOT_DRIVER(i2c_sandbox) = {
  87. .name = "i2c_sandbox",
  88. .id = UCLASS_I2C,
  89. .of_match = sandbox_i2c_ids,
  90. .per_child_auto_alloc_size = sizeof(struct dm_i2c_chip),
  91. .child_pre_probe = sandbox_i2c_child_pre_probe,
  92. .ops = &sandbox_i2c_ops,
  93. };