1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3 * Copyright (c) 2014 Google, Inc
4 */
5
6 #define LOG_CATEGORY UCLASS_I2C_EMUL
7
8 #include <dm.h>
9 #include <i2c.h>
10 #include <log.h>
11 #include <asm/i2c.h>
12 #include <dm/device-internal.h>
13 #include <dm/uclass-internal.h>
14
15 /*
16 * i2c emulation works using an 'emul' node at the bus level. Each device in
17 * that node is in the UCLASS_I2C_EMUL uclass, and emulates one i2c device. A
18 * pointer to the device it emulates is in the 'dev' property of the emul device
19 * uclass plat (struct i2c_emul_plat), put there by i2c_emul_find().
20 * When sandbox wants an emulator for a device, it calls i2c_emul_find() which
21 * searches for the emulator with the correct address. To find the device for an
22 * emulator, call i2c_emul_get_device().
23 *
24 * The 'emul' node is in the UCLASS_I2C_EMUL_PARENT uclass. We use a separate
25 * uclass so avoid having strange devices on the I2C bus.
26 */
27
i2c_emul_get_device(struct udevice * emul)28 struct udevice *i2c_emul_get_device(struct udevice *emul)
29 {
30 struct i2c_emul_uc_plat *uc_plat = dev_get_uclass_plat(emul);
31
32 return uc_plat->dev;
33 }
34
i2c_emul_set_idx(struct udevice * dev,int emul_idx)35 void i2c_emul_set_idx(struct udevice *dev, int emul_idx)
36 {
37 struct dm_i2c_chip *plat = dev_get_parent_plat(dev);
38
39 plat->emul_idx = emul_idx;
40 }
41
i2c_emul_find(struct udevice * dev,struct udevice ** emulp)42 int i2c_emul_find(struct udevice *dev, struct udevice **emulp)
43 {
44 struct i2c_emul_uc_plat *uc_plat;
45 struct udevice *emul;
46 int ret;
47
48 if (CONFIG_IS_ENABLED(OF_REAL)) {
49 ret = uclass_find_device_by_phandle(UCLASS_I2C_EMUL, dev,
50 "sandbox,emul", &emul);
51 } else {
52 struct dm_i2c_chip *plat = dev_get_parent_plat(dev);
53
54 ret = device_get_by_ofplat_idx(plat->emul_idx, &emul);
55 }
56 if (ret) {
57 log_err("No emulators for device '%s'\n", dev->name);
58 return ret;
59 }
60 uc_plat = dev_get_uclass_plat(emul);
61 uc_plat->dev = dev;
62 *emulp = emul;
63
64 return device_probe(emul);
65 }
66
67 UCLASS_DRIVER(i2c_emul) = {
68 .id = UCLASS_I2C_EMUL,
69 .name = "i2c_emul",
70 .per_device_plat_auto = sizeof(struct i2c_emul_uc_plat),
71 };
72
73 /*
74 * This uclass is a child of the i2c bus. Its plat is not defined here so
75 * is defined by its parent, UCLASS_I2C, which uses struct dm_i2c_chip. See
76 * per_child_plat_auto in UCLASS_DRIVER(i2c).
77 */
78 UCLASS_DRIVER(i2c_emul_parent) = {
79 .id = UCLASS_I2C_EMUL_PARENT,
80 .name = "i2c_emul_parent",
81 #if CONFIG_IS_ENABLED(OF_REAL)
82 .post_bind = dm_scan_fdt_dev,
83 #endif
84 };
85
86 static const struct udevice_id i2c_emul_parent_ids[] = {
87 { .compatible = "sandbox,i2c-emul-parent" },
88 { }
89 };
90
91 U_BOOT_DRIVER(sandbox_i2c_emul_parent) = {
92 .name = "sandbox_i2c_emul_parent",
93 .id = UCLASS_I2C_EMUL_PARENT,
94 .of_match = i2c_emul_parent_ids,
95 };
96