1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3 * Simulate an I2C port
4 *
5 * Copyright (c) 2014 Google, Inc
6 */
7
8 #include <dm.h>
9 #include <errno.h>
10 #include <i2c.h>
11 #include <log.h>
12 #include <asm/i2c.h>
13 #include <asm/test.h>
14 #include <dm/acpi.h>
15 #include <dm/lists.h>
16 #include <dm/device-internal.h>
17
get_emul(struct udevice * dev,struct udevice ** devp,struct dm_i2c_ops ** opsp)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
24 *devp = NULL;
25 *opsp = NULL;
26 plat = dev_get_parent_plat(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
35 return 0;
36 }
37
sandbox_i2c_set_test_mode(struct udevice * bus,bool test_mode)38 void sandbox_i2c_set_test_mode(struct udevice *bus, bool test_mode)
39 {
40 struct sandbox_i2c_priv *priv = dev_get_priv(bus);
41
42 priv->test_mode = test_mode;
43 }
44
sandbox_i2c_xfer(struct udevice * bus,struct i2c_msg * msg,int nmsgs)45 static int sandbox_i2c_xfer(struct udevice *bus, struct i2c_msg *msg,
46 int nmsgs)
47 {
48 struct dm_i2c_bus *i2c = dev_get_uclass_priv(bus);
49 struct sandbox_i2c_priv *priv = dev_get_priv(bus);
50 struct dm_i2c_ops *ops;
51 struct udevice *emul, *dev;
52 bool is_read;
53 int ret;
54
55 /* Special test code to return success but with no emulation */
56 if (priv->test_mode && msg->addr == SANDBOX_I2C_TEST_ADDR)
57 return 0;
58
59 ret = i2c_get_chip(bus, msg->addr, 1, &dev);
60 if (ret)
61 return ret;
62
63 ret = get_emul(dev, &emul, &ops);
64 if (ret)
65 return ret;
66
67 if (priv->test_mode) {
68 /*
69 * For testing, don't allow writing above 100KHz for writes and
70 * 400KHz for reads.
71 */
72 is_read = nmsgs > 1;
73 if (i2c->speed_hz > (is_read ? I2C_SPEED_FAST_RATE :
74 I2C_SPEED_STANDARD_RATE)) {
75 debug("%s: Max speed exceeded\n", __func__);
76 return -EINVAL;
77 }
78 }
79
80 return ops->xfer(emul, msg, nmsgs);
81 }
82
83 static const struct dm_i2c_ops sandbox_i2c_ops = {
84 .xfer = sandbox_i2c_xfer,
85 };
86
87 static const struct udevice_id sandbox_i2c_ids[] = {
88 { .compatible = "sandbox,i2c" },
89 { }
90 };
91
92 U_BOOT_DRIVER(sandbox_i2c) = {
93 .name = "sandbox_i2c",
94 .id = UCLASS_I2C,
95 .of_match = sandbox_i2c_ids,
96 .ops = &sandbox_i2c_ops,
97 .priv_auto = sizeof(struct sandbox_i2c_priv),
98 };
99