1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * MDIO I2C bridge
4  *
5  * Copyright (C) 2015-2016 Russell King
6  *
7  * Network PHYs can appear on I2C buses when they are part of SFP module.
8  * This driver exposes these PHYs to the networking PHY code, allowing
9  * our PHY drivers access to these PHYs, and so allowing configuration
10  * of their settings.
11  */
12 #include <linux/i2c.h>
13 #include <linux/phy.h>
14 
15 #include "mdio-i2c.h"
16 
17 /*
18  * I2C bus addresses 0x50 and 0x51 are normally an EEPROM, which is
19  * specified to be present in SFP modules.  These correspond with PHY
20  * addresses 16 and 17.  Disallow access to these "phy" addresses.
21  */
i2c_mii_valid_phy_id(int phy_id)22 static bool i2c_mii_valid_phy_id(int phy_id)
23 {
24 	return phy_id != 0x10 && phy_id != 0x11;
25 }
26 
i2c_mii_phy_addr(int phy_id)27 static unsigned int i2c_mii_phy_addr(int phy_id)
28 {
29 	return phy_id + 0x40;
30 }
31 
i2c_mii_read(struct mii_bus * bus,int phy_id,int reg)32 static int i2c_mii_read(struct mii_bus *bus, int phy_id, int reg)
33 {
34 	struct i2c_adapter *i2c = bus->priv;
35 	struct i2c_msg msgs[2];
36 	u8 data[2], dev_addr = reg;
37 	int bus_addr, ret;
38 
39 	if (!i2c_mii_valid_phy_id(phy_id))
40 		return 0xffff;
41 
42 	bus_addr = i2c_mii_phy_addr(phy_id);
43 	msgs[0].addr = bus_addr;
44 	msgs[0].flags = 0;
45 	msgs[0].len = 1;
46 	msgs[0].buf = &dev_addr;
47 	msgs[1].addr = bus_addr;
48 	msgs[1].flags = I2C_M_RD;
49 	msgs[1].len = sizeof(data);
50 	msgs[1].buf = data;
51 
52 	ret = i2c_transfer(i2c, msgs, ARRAY_SIZE(msgs));
53 	if (ret != ARRAY_SIZE(msgs))
54 		return 0xffff;
55 
56 	return data[0] << 8 | data[1];
57 }
58 
i2c_mii_write(struct mii_bus * bus,int phy_id,int reg,u16 val)59 static int i2c_mii_write(struct mii_bus *bus, int phy_id, int reg, u16 val)
60 {
61 	struct i2c_adapter *i2c = bus->priv;
62 	struct i2c_msg msg;
63 	int ret;
64 	u8 data[3];
65 
66 	if (!i2c_mii_valid_phy_id(phy_id))
67 		return 0;
68 
69 	data[0] = reg;
70 	data[1] = val >> 8;
71 	data[2] = val;
72 
73 	msg.addr = i2c_mii_phy_addr(phy_id);
74 	msg.flags = 0;
75 	msg.len = 3;
76 	msg.buf = data;
77 
78 	ret = i2c_transfer(i2c, &msg, 1);
79 
80 	return ret < 0 ? ret : 0;
81 }
82 
mdio_i2c_alloc(struct device * parent,struct i2c_adapter * i2c)83 struct mii_bus *mdio_i2c_alloc(struct device *parent, struct i2c_adapter *i2c)
84 {
85 	struct mii_bus *mii;
86 
87 	if (!i2c_check_functionality(i2c, I2C_FUNC_I2C))
88 		return ERR_PTR(-EINVAL);
89 
90 	mii = mdiobus_alloc();
91 	if (!mii)
92 		return ERR_PTR(-ENOMEM);
93 
94 	snprintf(mii->id, MII_BUS_ID_SIZE, "i2c:%s", dev_name(parent));
95 	mii->parent = parent;
96 	mii->read = i2c_mii_read;
97 	mii->write = i2c_mii_write;
98 	mii->priv = i2c;
99 
100 	return mii;
101 }
102 EXPORT_SYMBOL_GPL(mdio_i2c_alloc);
103 
104 MODULE_AUTHOR("Russell King");
105 MODULE_DESCRIPTION("MDIO I2C bridge library");
106 MODULE_LICENSE("GPL v2");
107