1
2
3
4
5
6
7
8
9
10
11
12#include <linux/i2c.h>
13#include <linux/mdio/mdio-i2c.h>
14#include <linux/phy.h>
15
16
17
18
19
20
21static bool i2c_mii_valid_phy_id(int phy_id)
22{
23 return phy_id != 0x10 && phy_id != 0x11;
24}
25
26static unsigned int i2c_mii_phy_addr(int phy_id)
27{
28 return phy_id + 0x40;
29}
30
31static int i2c_mii_read(struct mii_bus *bus, int phy_id, int reg)
32{
33 struct i2c_adapter *i2c = bus->priv;
34 struct i2c_msg msgs[2];
35 u8 addr[3], data[2], *p;
36 int bus_addr, ret;
37
38 if (!i2c_mii_valid_phy_id(phy_id))
39 return 0xffff;
40
41 p = addr;
42 if (reg & MII_ADDR_C45) {
43 *p++ = 0x20 | ((reg >> 16) & 31);
44 *p++ = reg >> 8;
45 }
46 *p++ = reg;
47
48 bus_addr = i2c_mii_phy_addr(phy_id);
49 msgs[0].addr = bus_addr;
50 msgs[0].flags = 0;
51 msgs[0].len = p - addr;
52 msgs[0].buf = addr;
53 msgs[1].addr = bus_addr;
54 msgs[1].flags = I2C_M_RD;
55 msgs[1].len = sizeof(data);
56 msgs[1].buf = data;
57
58 ret = i2c_transfer(i2c, msgs, ARRAY_SIZE(msgs));
59 if (ret != ARRAY_SIZE(msgs))
60 return 0xffff;
61
62 return data[0] << 8 | data[1];
63}
64
65static int i2c_mii_write(struct mii_bus *bus, int phy_id, int reg, u16 val)
66{
67 struct i2c_adapter *i2c = bus->priv;
68 struct i2c_msg msg;
69 int ret;
70 u8 data[5], *p;
71
72 if (!i2c_mii_valid_phy_id(phy_id))
73 return 0;
74
75 p = data;
76 if (reg & MII_ADDR_C45) {
77 *p++ = (reg >> 16) & 31;
78 *p++ = reg >> 8;
79 }
80 *p++ = reg;
81 *p++ = val >> 8;
82 *p++ = val;
83
84 msg.addr = i2c_mii_phy_addr(phy_id);
85 msg.flags = 0;
86 msg.len = p - data;
87 msg.buf = data;
88
89 ret = i2c_transfer(i2c, &msg, 1);
90
91 return ret < 0 ? ret : 0;
92}
93
94struct mii_bus *mdio_i2c_alloc(struct device *parent, struct i2c_adapter *i2c)
95{
96 struct mii_bus *mii;
97
98 if (!i2c_check_functionality(i2c, I2C_FUNC_I2C))
99 return ERR_PTR(-EINVAL);
100
101 mii = mdiobus_alloc();
102 if (!mii)
103 return ERR_PTR(-ENOMEM);
104
105 snprintf(mii->id, MII_BUS_ID_SIZE, "i2c:%s", dev_name(parent));
106 mii->parent = parent;
107 mii->read = i2c_mii_read;
108 mii->write = i2c_mii_write;
109 mii->priv = i2c;
110
111 return mii;
112}
113EXPORT_SYMBOL_GPL(mdio_i2c_alloc);
114
115MODULE_AUTHOR("Russell King");
116MODULE_DESCRIPTION("MDIO I2C bridge library");
117MODULE_LICENSE("GPL v2");
118