xref: /openbmc/u-boot/drivers/i2c/sandbox_i2c.c (revision acc2372d)
1 /*
2  * Simulate an I2C port
3  *
4  * Copyright (c) 2014 Google, Inc
5  *
6  * SPDX-License-Identifier:	GPL-2.0+
7  */
8 
9 #include <common.h>
10 #include <dm.h>
11 #include <errno.h>
12 #include <fdtdec.h>
13 #include <i2c.h>
14 #include <asm/test.h>
15 #include <dm/lists.h>
16 #include <dm/device-internal.h>
17 #include <dm/root.h>
18 
19 DECLARE_GLOBAL_DATA_PTR;
20 
21 struct dm_sandbox_i2c_emul_priv {
22 	struct udevice *emul;
23 };
24 
25 static int get_emul(struct udevice *dev, struct udevice **devp,
26 		    struct dm_i2c_ops **opsp)
27 {
28 	struct dm_i2c_chip *priv;
29 	int ret;
30 
31 	*devp = NULL;
32 	*opsp = NULL;
33 	priv = dev_get_parentdata(dev);
34 	if (!priv->emul) {
35 		ret = dm_scan_fdt_node(dev, gd->fdt_blob, dev->of_offset,
36 				       false);
37 		if (ret)
38 			return ret;
39 
40 		ret = device_get_child(dev, 0, &priv->emul);
41 		if (ret)
42 			return ret;
43 	}
44 	*devp = priv->emul;
45 	*opsp = i2c_get_ops(priv->emul);
46 
47 	return 0;
48 }
49 
50 static int sandbox_i2c_xfer(struct udevice *bus, struct i2c_msg *msg,
51 			    int nmsgs)
52 {
53 	struct dm_i2c_bus *i2c = bus->uclass_priv;
54 	struct dm_i2c_ops *ops;
55 	struct udevice *emul, *dev;
56 	bool is_read;
57 	int ret;
58 
59 	/* Special test code to return success but with no emulation */
60 	if (msg->addr == SANDBOX_I2C_TEST_ADDR)
61 		return 0;
62 
63 	ret = i2c_get_chip(bus, msg->addr, &dev);
64 	if (ret)
65 		return ret;
66 
67 	ret = get_emul(dev, &emul, &ops);
68 	if (ret)
69 		return ret;
70 
71 	/*
72 	 * For testing, don't allow writing above 100KHz for writes and
73 	 * 400KHz for reads
74 	 */
75 	is_read = nmsgs > 1;
76 	if (i2c->speed_hz > (is_read ? 400000 : 100000))
77 		return -EINVAL;
78 	return ops->xfer(emul, msg, nmsgs);
79 }
80 
81 static const struct dm_i2c_ops sandbox_i2c_ops = {
82 	.xfer		= sandbox_i2c_xfer,
83 };
84 
85 static int sandbox_i2c_child_pre_probe(struct udevice *dev)
86 {
87 	struct dm_i2c_chip *i2c_chip = dev_get_parentdata(dev);
88 
89 	/* Ignore our test address */
90 	if (i2c_chip->chip_addr == SANDBOX_I2C_TEST_ADDR)
91 		return 0;
92 	if (dev->of_offset == -1)
93 		return 0;
94 
95 	return i2c_chip_ofdata_to_platdata(gd->fdt_blob, dev->of_offset,
96 					   i2c_chip);
97 }
98 
99 static const struct udevice_id sandbox_i2c_ids[] = {
100 	{ .compatible = "sandbox,i2c" },
101 	{ }
102 };
103 
104 U_BOOT_DRIVER(i2c_sandbox) = {
105 	.name	= "i2c_sandbox",
106 	.id	= UCLASS_I2C,
107 	.of_match = sandbox_i2c_ids,
108 	.per_child_auto_alloc_size = sizeof(struct dm_i2c_chip),
109 	.child_pre_probe = sandbox_i2c_child_pre_probe,
110 	.ops	= &sandbox_i2c_ops,
111 };
112