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 <i2c.h> 13 #include <asm/test.h> 14 #include <dm/lists.h> 15 #include <dm/device-internal.h> 16 17 struct sandbox_i2c_priv { 18 bool test_mode; 19 }; 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 struct udevice *child; 26 int ret; 27 28 *devp = NULL; 29 *opsp = NULL; 30 plat = dev_get_parent_platdata(dev); 31 if (!plat->emul) { 32 ret = dm_scan_fdt_dev(dev); 33 if (ret) 34 return ret; 35 36 for (device_find_first_child(dev, &child); child; 37 device_find_next_child(&child)) { 38 if (device_get_uclass_id(child) != UCLASS_I2C_EMUL) 39 continue; 40 41 ret = device_probe(child); 42 if (ret) 43 return ret; 44 45 break; 46 } 47 48 if (child) 49 plat->emul = child; 50 else 51 return -ENODEV; 52 } 53 *devp = plat->emul; 54 *opsp = i2c_get_ops(plat->emul); 55 56 return 0; 57 } 58 59 void sandbox_i2c_set_test_mode(struct udevice *bus, bool test_mode) 60 { 61 struct sandbox_i2c_priv *priv = dev_get_priv(bus); 62 63 priv->test_mode = test_mode; 64 } 65 66 static int sandbox_i2c_xfer(struct udevice *bus, struct i2c_msg *msg, 67 int nmsgs) 68 { 69 struct dm_i2c_bus *i2c = dev_get_uclass_priv(bus); 70 struct sandbox_i2c_priv *priv = dev_get_priv(bus); 71 struct dm_i2c_ops *ops; 72 struct udevice *emul, *dev; 73 bool is_read; 74 int ret; 75 76 /* Special test code to return success but with no emulation */ 77 if (priv->test_mode && msg->addr == SANDBOX_I2C_TEST_ADDR) 78 return 0; 79 80 ret = i2c_get_chip(bus, msg->addr, 1, &dev); 81 if (ret) 82 return ret; 83 84 ret = get_emul(dev, &emul, &ops); 85 if (ret) 86 return ret; 87 88 if (priv->test_mode) { 89 /* 90 * For testing, don't allow writing above 100KHz for writes and 91 * 400KHz for reads. 92 */ 93 is_read = nmsgs > 1; 94 if (i2c->speed_hz > (is_read ? 400000 : 100000)) { 95 debug("%s: Max speed exceeded\n", __func__); 96 return -EINVAL; 97 } 98 } 99 100 return ops->xfer(emul, msg, nmsgs); 101 } 102 103 static const struct dm_i2c_ops sandbox_i2c_ops = { 104 .xfer = sandbox_i2c_xfer, 105 }; 106 107 static const struct udevice_id sandbox_i2c_ids[] = { 108 { .compatible = "sandbox,i2c" }, 109 { } 110 }; 111 112 U_BOOT_DRIVER(i2c_sandbox) = { 113 .name = "i2c_sandbox", 114 .id = UCLASS_I2C, 115 .of_match = sandbox_i2c_ids, 116 .ops = &sandbox_i2c_ops, 117 .priv_auto_alloc_size = sizeof(struct sandbox_i2c_priv), 118 }; 119