xref: /openbmc/linux/drivers/net/phy/sfp.c (revision 1974fd3b)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/debugfs.h>
3 #include <linux/delay.h>
4 #include <linux/gpio/consumer.h>
5 #include <linux/hwmon.h>
6 #include <linux/i2c.h>
7 #include <linux/interrupt.h>
8 #include <linux/jiffies.h>
9 #include <linux/mdio/mdio-i2c.h>
10 #include <linux/module.h>
11 #include <linux/mutex.h>
12 #include <linux/of.h>
13 #include <linux/phy.h>
14 #include <linux/platform_device.h>
15 #include <linux/rtnetlink.h>
16 #include <linux/slab.h>
17 #include <linux/workqueue.h>
18 
19 #include "sfp.h"
20 #include "swphy.h"
21 
22 enum {
23 	GPIO_MODDEF0,
24 	GPIO_LOS,
25 	GPIO_TX_FAULT,
26 	GPIO_TX_DISABLE,
27 	GPIO_RATE_SELECT,
28 	GPIO_MAX,
29 
30 	SFP_F_PRESENT = BIT(GPIO_MODDEF0),
31 	SFP_F_LOS = BIT(GPIO_LOS),
32 	SFP_F_TX_FAULT = BIT(GPIO_TX_FAULT),
33 	SFP_F_TX_DISABLE = BIT(GPIO_TX_DISABLE),
34 	SFP_F_RATE_SELECT = BIT(GPIO_RATE_SELECT),
35 
36 	SFP_E_INSERT = 0,
37 	SFP_E_REMOVE,
38 	SFP_E_DEV_ATTACH,
39 	SFP_E_DEV_DETACH,
40 	SFP_E_DEV_DOWN,
41 	SFP_E_DEV_UP,
42 	SFP_E_TX_FAULT,
43 	SFP_E_TX_CLEAR,
44 	SFP_E_LOS_HIGH,
45 	SFP_E_LOS_LOW,
46 	SFP_E_TIMEOUT,
47 
48 	SFP_MOD_EMPTY = 0,
49 	SFP_MOD_ERROR,
50 	SFP_MOD_PROBE,
51 	SFP_MOD_WAITDEV,
52 	SFP_MOD_HPOWER,
53 	SFP_MOD_WAITPWR,
54 	SFP_MOD_PRESENT,
55 
56 	SFP_DEV_DETACHED = 0,
57 	SFP_DEV_DOWN,
58 	SFP_DEV_UP,
59 
60 	SFP_S_DOWN = 0,
61 	SFP_S_FAIL,
62 	SFP_S_WAIT,
63 	SFP_S_INIT,
64 	SFP_S_INIT_PHY,
65 	SFP_S_INIT_TX_FAULT,
66 	SFP_S_WAIT_LOS,
67 	SFP_S_LINK_UP,
68 	SFP_S_TX_FAULT,
69 	SFP_S_REINIT,
70 	SFP_S_TX_DISABLE,
71 };
72 
73 static const char  * const mod_state_strings[] = {
74 	[SFP_MOD_EMPTY] = "empty",
75 	[SFP_MOD_ERROR] = "error",
76 	[SFP_MOD_PROBE] = "probe",
77 	[SFP_MOD_WAITDEV] = "waitdev",
78 	[SFP_MOD_HPOWER] = "hpower",
79 	[SFP_MOD_WAITPWR] = "waitpwr",
80 	[SFP_MOD_PRESENT] = "present",
81 };
82 
83 static const char *mod_state_to_str(unsigned short mod_state)
84 {
85 	if (mod_state >= ARRAY_SIZE(mod_state_strings))
86 		return "Unknown module state";
87 	return mod_state_strings[mod_state];
88 }
89 
90 static const char * const dev_state_strings[] = {
91 	[SFP_DEV_DETACHED] = "detached",
92 	[SFP_DEV_DOWN] = "down",
93 	[SFP_DEV_UP] = "up",
94 };
95 
96 static const char *dev_state_to_str(unsigned short dev_state)
97 {
98 	if (dev_state >= ARRAY_SIZE(dev_state_strings))
99 		return "Unknown device state";
100 	return dev_state_strings[dev_state];
101 }
102 
103 static const char * const event_strings[] = {
104 	[SFP_E_INSERT] = "insert",
105 	[SFP_E_REMOVE] = "remove",
106 	[SFP_E_DEV_ATTACH] = "dev_attach",
107 	[SFP_E_DEV_DETACH] = "dev_detach",
108 	[SFP_E_DEV_DOWN] = "dev_down",
109 	[SFP_E_DEV_UP] = "dev_up",
110 	[SFP_E_TX_FAULT] = "tx_fault",
111 	[SFP_E_TX_CLEAR] = "tx_clear",
112 	[SFP_E_LOS_HIGH] = "los_high",
113 	[SFP_E_LOS_LOW] = "los_low",
114 	[SFP_E_TIMEOUT] = "timeout",
115 };
116 
117 static const char *event_to_str(unsigned short event)
118 {
119 	if (event >= ARRAY_SIZE(event_strings))
120 		return "Unknown event";
121 	return event_strings[event];
122 }
123 
124 static const char * const sm_state_strings[] = {
125 	[SFP_S_DOWN] = "down",
126 	[SFP_S_FAIL] = "fail",
127 	[SFP_S_WAIT] = "wait",
128 	[SFP_S_INIT] = "init",
129 	[SFP_S_INIT_PHY] = "init_phy",
130 	[SFP_S_INIT_TX_FAULT] = "init_tx_fault",
131 	[SFP_S_WAIT_LOS] = "wait_los",
132 	[SFP_S_LINK_UP] = "link_up",
133 	[SFP_S_TX_FAULT] = "tx_fault",
134 	[SFP_S_REINIT] = "reinit",
135 	[SFP_S_TX_DISABLE] = "tx_disable",
136 };
137 
138 static const char *sm_state_to_str(unsigned short sm_state)
139 {
140 	if (sm_state >= ARRAY_SIZE(sm_state_strings))
141 		return "Unknown state";
142 	return sm_state_strings[sm_state];
143 }
144 
145 static const char *gpio_names[] = {
146 	"mod-def0",
147 	"los",
148 	"tx-fault",
149 	"tx-disable",
150 	"rate-select0",
151 };
152 
153 static const enum gpiod_flags gpio_flags[] = {
154 	GPIOD_IN,
155 	GPIOD_IN,
156 	GPIOD_IN,
157 	GPIOD_ASIS,
158 	GPIOD_ASIS,
159 };
160 
161 /* t_start_up (SFF-8431) or t_init (SFF-8472) is the time required for a
162  * non-cooled module to initialise its laser safety circuitry. We wait
163  * an initial T_WAIT period before we check the tx fault to give any PHY
164  * on board (for a copper SFP) time to initialise.
165  */
166 #define T_WAIT			msecs_to_jiffies(50)
167 #define T_WAIT_ROLLBALL		msecs_to_jiffies(25000)
168 #define T_START_UP		msecs_to_jiffies(300)
169 #define T_START_UP_BAD_GPON	msecs_to_jiffies(60000)
170 
171 /* t_reset is the time required to assert the TX_DISABLE signal to reset
172  * an indicated TX_FAULT.
173  */
174 #define T_RESET_US		10
175 #define T_FAULT_RECOVER		msecs_to_jiffies(1000)
176 
177 /* N_FAULT_INIT is the number of recovery attempts at module initialisation
178  * time. If the TX_FAULT signal is not deasserted after this number of
179  * attempts at clearing it, we decide that the module is faulty.
180  * N_FAULT is the same but after the module has initialised.
181  */
182 #define N_FAULT_INIT		5
183 #define N_FAULT			5
184 
185 /* T_PHY_RETRY is the time interval between attempts to probe the PHY.
186  * R_PHY_RETRY is the number of attempts.
187  */
188 #define T_PHY_RETRY		msecs_to_jiffies(50)
189 #define R_PHY_RETRY		12
190 
191 /* SFP module presence detection is poor: the three MOD DEF signals are
192  * the same length on the PCB, which means it's possible for MOD DEF 0 to
193  * connect before the I2C bus on MOD DEF 1/2.
194  *
195  * The SFF-8472 specifies t_serial ("Time from power on until module is
196  * ready for data transmission over the two wire serial bus.") as 300ms.
197  */
198 #define T_SERIAL		msecs_to_jiffies(300)
199 #define T_HPOWER_LEVEL		msecs_to_jiffies(300)
200 #define T_PROBE_RETRY_INIT	msecs_to_jiffies(100)
201 #define R_PROBE_RETRY_INIT	10
202 #define T_PROBE_RETRY_SLOW	msecs_to_jiffies(5000)
203 #define R_PROBE_RETRY_SLOW	12
204 
205 /* SFP modules appear to always have their PHY configured for bus address
206  * 0x56 (which with mdio-i2c, translates to a PHY address of 22).
207  * RollBall SFPs access phy via SFP Enhanced Digital Diagnostic Interface
208  * via address 0x51 (mdio-i2c will use RollBall protocol on this address).
209  */
210 #define SFP_PHY_ADDR		22
211 #define SFP_PHY_ADDR_ROLLBALL	17
212 
213 /* SFP_EEPROM_BLOCK_SIZE is the size of data chunk to read the EEPROM
214  * at a time. Some SFP modules and also some Linux I2C drivers do not like
215  * reads longer than 16 bytes.
216  */
217 #define SFP_EEPROM_BLOCK_SIZE	16
218 
219 struct sff_data {
220 	unsigned int gpios;
221 	bool (*module_supported)(const struct sfp_eeprom_id *id);
222 };
223 
224 struct sfp {
225 	struct device *dev;
226 	struct i2c_adapter *i2c;
227 	struct mii_bus *i2c_mii;
228 	struct sfp_bus *sfp_bus;
229 	enum mdio_i2c_proto mdio_protocol;
230 	struct phy_device *mod_phy;
231 	const struct sff_data *type;
232 	size_t i2c_block_size;
233 	u32 max_power_mW;
234 
235 	unsigned int (*get_state)(struct sfp *);
236 	void (*set_state)(struct sfp *, unsigned int);
237 	int (*read)(struct sfp *, bool, u8, void *, size_t);
238 	int (*write)(struct sfp *, bool, u8, void *, size_t);
239 
240 	struct gpio_desc *gpio[GPIO_MAX];
241 	int gpio_irq[GPIO_MAX];
242 
243 	bool need_poll;
244 
245 	/* Access rules:
246 	 * state_hw_drive: st_mutex held
247 	 * state_hw_mask: st_mutex held
248 	 * state_soft_mask: st_mutex held
249 	 * state: st_mutex held unless reading input bits
250 	 */
251 	struct mutex st_mutex;			/* Protects state */
252 	unsigned int state_hw_mask;
253 	unsigned int state_soft_mask;
254 	unsigned int state;
255 
256 	struct delayed_work poll;
257 	struct delayed_work timeout;
258 	struct mutex sm_mutex;			/* Protects state machine */
259 	unsigned char sm_mod_state;
260 	unsigned char sm_mod_tries_init;
261 	unsigned char sm_mod_tries;
262 	unsigned char sm_dev_state;
263 	unsigned short sm_state;
264 	unsigned char sm_fault_retries;
265 	unsigned char sm_phy_retries;
266 
267 	struct sfp_eeprom_id id;
268 	unsigned int module_power_mW;
269 	unsigned int module_t_start_up;
270 	unsigned int module_t_wait;
271 
272 	bool have_a2;
273 	bool tx_fault_ignore;
274 
275 	const struct sfp_quirk *quirk;
276 
277 #if IS_ENABLED(CONFIG_HWMON)
278 	struct sfp_diag diag;
279 	struct delayed_work hwmon_probe;
280 	unsigned int hwmon_tries;
281 	struct device *hwmon_dev;
282 	char *hwmon_name;
283 #endif
284 
285 #if IS_ENABLED(CONFIG_DEBUG_FS)
286 	struct dentry *debugfs_dir;
287 #endif
288 };
289 
290 static bool sff_module_supported(const struct sfp_eeprom_id *id)
291 {
292 	return id->base.phys_id == SFF8024_ID_SFF_8472 &&
293 	       id->base.phys_ext_id == SFP_PHYS_EXT_ID_SFP;
294 }
295 
296 static const struct sff_data sff_data = {
297 	.gpios = SFP_F_LOS | SFP_F_TX_FAULT | SFP_F_TX_DISABLE,
298 	.module_supported = sff_module_supported,
299 };
300 
301 static bool sfp_module_supported(const struct sfp_eeprom_id *id)
302 {
303 	if (id->base.phys_id == SFF8024_ID_SFP &&
304 	    id->base.phys_ext_id == SFP_PHYS_EXT_ID_SFP)
305 		return true;
306 
307 	/* SFP GPON module Ubiquiti U-Fiber Instant has in its EEPROM stored
308 	 * phys id SFF instead of SFP. Therefore mark this module explicitly
309 	 * as supported based on vendor name and pn match.
310 	 */
311 	if (id->base.phys_id == SFF8024_ID_SFF_8472 &&
312 	    id->base.phys_ext_id == SFP_PHYS_EXT_ID_SFP &&
313 	    !memcmp(id->base.vendor_name, "UBNT            ", 16) &&
314 	    !memcmp(id->base.vendor_pn, "UF-INSTANT      ", 16))
315 		return true;
316 
317 	return false;
318 }
319 
320 static const struct sff_data sfp_data = {
321 	.gpios = SFP_F_PRESENT | SFP_F_LOS | SFP_F_TX_FAULT |
322 		 SFP_F_TX_DISABLE | SFP_F_RATE_SELECT,
323 	.module_supported = sfp_module_supported,
324 };
325 
326 static const struct of_device_id sfp_of_match[] = {
327 	{ .compatible = "sff,sff", .data = &sff_data, },
328 	{ .compatible = "sff,sfp", .data = &sfp_data, },
329 	{ },
330 };
331 MODULE_DEVICE_TABLE(of, sfp_of_match);
332 
333 static void sfp_fixup_long_startup(struct sfp *sfp)
334 {
335 	sfp->module_t_start_up = T_START_UP_BAD_GPON;
336 }
337 
338 static void sfp_fixup_ignore_tx_fault(struct sfp *sfp)
339 {
340 	sfp->tx_fault_ignore = true;
341 }
342 
343 static void sfp_fixup_halny_gsfp(struct sfp *sfp)
344 {
345 	/* Ignore the TX_FAULT and LOS signals on this module.
346 	 * these are possibly used for other purposes on this
347 	 * module, e.g. a serial port.
348 	 */
349 	sfp->state_hw_mask &= ~(SFP_F_TX_FAULT | SFP_F_LOS);
350 }
351 
352 static void sfp_fixup_rollball(struct sfp *sfp)
353 {
354 	sfp->mdio_protocol = MDIO_I2C_ROLLBALL;
355 	sfp->module_t_wait = T_WAIT_ROLLBALL;
356 }
357 
358 static void sfp_fixup_rollball_cc(struct sfp *sfp)
359 {
360 	sfp_fixup_rollball(sfp);
361 
362 	/* Some RollBall SFPs may have wrong (zero) extended compliance code
363 	 * burned in EEPROM. For PHY probing we need the correct one.
364 	 */
365 	sfp->id.base.extended_cc = SFF8024_ECC_10GBASE_T_SFI;
366 }
367 
368 static void sfp_quirk_2500basex(const struct sfp_eeprom_id *id,
369 				unsigned long *modes,
370 				unsigned long *interfaces)
371 {
372 	linkmode_set_bit(ETHTOOL_LINK_MODE_2500baseX_Full_BIT, modes);
373 	__set_bit(PHY_INTERFACE_MODE_2500BASEX, interfaces);
374 }
375 
376 static void sfp_quirk_disable_autoneg(const struct sfp_eeprom_id *id,
377 				      unsigned long *modes,
378 				      unsigned long *interfaces)
379 {
380 	linkmode_clear_bit(ETHTOOL_LINK_MODE_Autoneg_BIT, modes);
381 }
382 
383 static void sfp_quirk_oem_2_5g(const struct sfp_eeprom_id *id,
384 			       unsigned long *modes,
385 			       unsigned long *interfaces)
386 {
387 	/* Copper 2.5G SFP */
388 	linkmode_set_bit(ETHTOOL_LINK_MODE_2500baseT_Full_BIT, modes);
389 	__set_bit(PHY_INTERFACE_MODE_2500BASEX, interfaces);
390 	sfp_quirk_disable_autoneg(id, modes, interfaces);
391 }
392 
393 static void sfp_quirk_ubnt_uf_instant(const struct sfp_eeprom_id *id,
394 				      unsigned long *modes,
395 				      unsigned long *interfaces)
396 {
397 	/* Ubiquiti U-Fiber Instant module claims that support all transceiver
398 	 * types including 10G Ethernet which is not truth. So clear all claimed
399 	 * modes and set only one mode which module supports: 1000baseX_Full.
400 	 */
401 	linkmode_zero(modes);
402 	linkmode_set_bit(ETHTOOL_LINK_MODE_1000baseX_Full_BIT, modes);
403 }
404 
405 #define SFP_QUIRK(_v, _p, _m, _f) \
406 	{ .vendor = _v, .part = _p, .modes = _m, .fixup = _f, }
407 #define SFP_QUIRK_M(_v, _p, _m) SFP_QUIRK(_v, _p, _m, NULL)
408 #define SFP_QUIRK_F(_v, _p, _f) SFP_QUIRK(_v, _p, NULL, _f)
409 
410 static const struct sfp_quirk sfp_quirks[] = {
411 	// Alcatel Lucent G-010S-P can operate at 2500base-X, but incorrectly
412 	// report 2500MBd NRZ in their EEPROM
413 	SFP_QUIRK_M("ALCATELLUCENT", "G010SP", sfp_quirk_2500basex),
414 
415 	// Alcatel Lucent G-010S-A can operate at 2500base-X, but report 3.2GBd
416 	// NRZ in their EEPROM
417 	SFP_QUIRK("ALCATELLUCENT", "3FE46541AA", sfp_quirk_2500basex,
418 		  sfp_fixup_long_startup),
419 
420 	SFP_QUIRK_F("HALNy", "HL-GSFP", sfp_fixup_halny_gsfp),
421 
422 	// HG MXPD-483II-F 2.5G supports 2500Base-X, but incorrectly reports
423 	// 2600MBd in their EERPOM
424 	SFP_QUIRK_M("HG GENUINE", "MXPD-483II", sfp_quirk_2500basex),
425 
426 	// Huawei MA5671A can operate at 2500base-X, but report 1.2GBd NRZ in
427 	// their EEPROM
428 	SFP_QUIRK("HUAWEI", "MA5671A", sfp_quirk_2500basex,
429 		  sfp_fixup_ignore_tx_fault),
430 
431 	// Lantech 8330-262D-E can operate at 2500base-X, but incorrectly report
432 	// 2500MBd NRZ in their EEPROM
433 	SFP_QUIRK_M("Lantech", "8330-262D-E", sfp_quirk_2500basex),
434 
435 	SFP_QUIRK_M("UBNT", "UF-INSTANT", sfp_quirk_ubnt_uf_instant),
436 
437 	SFP_QUIRK_F("OEM", "SFP-10G-T", sfp_fixup_rollball_cc),
438 	SFP_QUIRK_M("OEM", "SFP-2.5G-T", sfp_quirk_oem_2_5g),
439 	SFP_QUIRK_F("OEM", "RTSFP-10", sfp_fixup_rollball_cc),
440 	SFP_QUIRK_F("OEM", "RTSFP-10G", sfp_fixup_rollball_cc),
441 	SFP_QUIRK_F("Turris", "RTSFP-10", sfp_fixup_rollball),
442 	SFP_QUIRK_F("Turris", "RTSFP-10G", sfp_fixup_rollball),
443 };
444 
445 static size_t sfp_strlen(const char *str, size_t maxlen)
446 {
447 	size_t size, i;
448 
449 	/* Trailing characters should be filled with space chars, but
450 	 * some manufacturers can't read SFF-8472 and use NUL.
451 	 */
452 	for (i = 0, size = 0; i < maxlen; i++)
453 		if (str[i] != ' ' && str[i] != '\0')
454 			size = i + 1;
455 
456 	return size;
457 }
458 
459 static bool sfp_match(const char *qs, const char *str, size_t len)
460 {
461 	if (!qs)
462 		return true;
463 	if (strlen(qs) != len)
464 		return false;
465 	return !strncmp(qs, str, len);
466 }
467 
468 static const struct sfp_quirk *sfp_lookup_quirk(const struct sfp_eeprom_id *id)
469 {
470 	const struct sfp_quirk *q;
471 	unsigned int i;
472 	size_t vs, ps;
473 
474 	vs = sfp_strlen(id->base.vendor_name, ARRAY_SIZE(id->base.vendor_name));
475 	ps = sfp_strlen(id->base.vendor_pn, ARRAY_SIZE(id->base.vendor_pn));
476 
477 	for (i = 0, q = sfp_quirks; i < ARRAY_SIZE(sfp_quirks); i++, q++)
478 		if (sfp_match(q->vendor, id->base.vendor_name, vs) &&
479 		    sfp_match(q->part, id->base.vendor_pn, ps))
480 			return q;
481 
482 	return NULL;
483 }
484 
485 static unsigned long poll_jiffies;
486 
487 static unsigned int sfp_gpio_get_state(struct sfp *sfp)
488 {
489 	unsigned int i, state, v;
490 
491 	for (i = state = 0; i < GPIO_MAX; i++) {
492 		if (gpio_flags[i] != GPIOD_IN || !sfp->gpio[i])
493 			continue;
494 
495 		v = gpiod_get_value_cansleep(sfp->gpio[i]);
496 		if (v)
497 			state |= BIT(i);
498 	}
499 
500 	return state;
501 }
502 
503 static unsigned int sff_gpio_get_state(struct sfp *sfp)
504 {
505 	return sfp_gpio_get_state(sfp) | SFP_F_PRESENT;
506 }
507 
508 static void sfp_gpio_set_state(struct sfp *sfp, unsigned int state)
509 {
510 	if (state & SFP_F_PRESENT) {
511 		/* If the module is present, drive the signals */
512 		if (sfp->gpio[GPIO_TX_DISABLE])
513 			gpiod_direction_output(sfp->gpio[GPIO_TX_DISABLE],
514 					       state & SFP_F_TX_DISABLE);
515 		if (state & SFP_F_RATE_SELECT)
516 			gpiod_direction_output(sfp->gpio[GPIO_RATE_SELECT],
517 					       state & SFP_F_RATE_SELECT);
518 	} else {
519 		/* Otherwise, let them float to the pull-ups */
520 		if (sfp->gpio[GPIO_TX_DISABLE])
521 			gpiod_direction_input(sfp->gpio[GPIO_TX_DISABLE]);
522 		if (state & SFP_F_RATE_SELECT)
523 			gpiod_direction_input(sfp->gpio[GPIO_RATE_SELECT]);
524 	}
525 }
526 
527 static int sfp_i2c_read(struct sfp *sfp, bool a2, u8 dev_addr, void *buf,
528 			size_t len)
529 {
530 	struct i2c_msg msgs[2];
531 	u8 bus_addr = a2 ? 0x51 : 0x50;
532 	size_t block_size = sfp->i2c_block_size;
533 	size_t this_len;
534 	int ret;
535 
536 	msgs[0].addr = bus_addr;
537 	msgs[0].flags = 0;
538 	msgs[0].len = 1;
539 	msgs[0].buf = &dev_addr;
540 	msgs[1].addr = bus_addr;
541 	msgs[1].flags = I2C_M_RD;
542 	msgs[1].len = len;
543 	msgs[1].buf = buf;
544 
545 	while (len) {
546 		this_len = len;
547 		if (this_len > block_size)
548 			this_len = block_size;
549 
550 		msgs[1].len = this_len;
551 
552 		ret = i2c_transfer(sfp->i2c, msgs, ARRAY_SIZE(msgs));
553 		if (ret < 0)
554 			return ret;
555 
556 		if (ret != ARRAY_SIZE(msgs))
557 			break;
558 
559 		msgs[1].buf += this_len;
560 		dev_addr += this_len;
561 		len -= this_len;
562 	}
563 
564 	return msgs[1].buf - (u8 *)buf;
565 }
566 
567 static int sfp_i2c_write(struct sfp *sfp, bool a2, u8 dev_addr, void *buf,
568 	size_t len)
569 {
570 	struct i2c_msg msgs[1];
571 	u8 bus_addr = a2 ? 0x51 : 0x50;
572 	int ret;
573 
574 	msgs[0].addr = bus_addr;
575 	msgs[0].flags = 0;
576 	msgs[0].len = 1 + len;
577 	msgs[0].buf = kmalloc(1 + len, GFP_KERNEL);
578 	if (!msgs[0].buf)
579 		return -ENOMEM;
580 
581 	msgs[0].buf[0] = dev_addr;
582 	memcpy(&msgs[0].buf[1], buf, len);
583 
584 	ret = i2c_transfer(sfp->i2c, msgs, ARRAY_SIZE(msgs));
585 
586 	kfree(msgs[0].buf);
587 
588 	if (ret < 0)
589 		return ret;
590 
591 	return ret == ARRAY_SIZE(msgs) ? len : 0;
592 }
593 
594 static int sfp_i2c_configure(struct sfp *sfp, struct i2c_adapter *i2c)
595 {
596 	if (!i2c_check_functionality(i2c, I2C_FUNC_I2C))
597 		return -EINVAL;
598 
599 	sfp->i2c = i2c;
600 	sfp->read = sfp_i2c_read;
601 	sfp->write = sfp_i2c_write;
602 
603 	return 0;
604 }
605 
606 static int sfp_i2c_mdiobus_create(struct sfp *sfp)
607 {
608 	struct mii_bus *i2c_mii;
609 	int ret;
610 
611 	i2c_mii = mdio_i2c_alloc(sfp->dev, sfp->i2c, sfp->mdio_protocol);
612 	if (IS_ERR(i2c_mii))
613 		return PTR_ERR(i2c_mii);
614 
615 	i2c_mii->name = "SFP I2C Bus";
616 	i2c_mii->phy_mask = ~0;
617 
618 	ret = mdiobus_register(i2c_mii);
619 	if (ret < 0) {
620 		mdiobus_free(i2c_mii);
621 		return ret;
622 	}
623 
624 	sfp->i2c_mii = i2c_mii;
625 
626 	return 0;
627 }
628 
629 static void sfp_i2c_mdiobus_destroy(struct sfp *sfp)
630 {
631 	mdiobus_unregister(sfp->i2c_mii);
632 	sfp->i2c_mii = NULL;
633 }
634 
635 /* Interface */
636 static int sfp_read(struct sfp *sfp, bool a2, u8 addr, void *buf, size_t len)
637 {
638 	return sfp->read(sfp, a2, addr, buf, len);
639 }
640 
641 static int sfp_write(struct sfp *sfp, bool a2, u8 addr, void *buf, size_t len)
642 {
643 	return sfp->write(sfp, a2, addr, buf, len);
644 }
645 
646 static int sfp_modify_u8(struct sfp *sfp, bool a2, u8 addr, u8 mask, u8 val)
647 {
648 	int ret;
649 	u8 old, v;
650 
651 	ret = sfp_read(sfp, a2, addr, &old, sizeof(old));
652 	if (ret != sizeof(old))
653 		return ret;
654 
655 	v = (old & ~mask) | (val & mask);
656 	if (v == old)
657 		return sizeof(v);
658 
659 	return sfp_write(sfp, a2, addr, &v, sizeof(v));
660 }
661 
662 static unsigned int sfp_soft_get_state(struct sfp *sfp)
663 {
664 	unsigned int state = 0;
665 	u8 status;
666 	int ret;
667 
668 	ret = sfp_read(sfp, true, SFP_STATUS, &status, sizeof(status));
669 	if (ret == sizeof(status)) {
670 		if (status & SFP_STATUS_RX_LOS)
671 			state |= SFP_F_LOS;
672 		if (status & SFP_STATUS_TX_FAULT)
673 			state |= SFP_F_TX_FAULT;
674 	} else {
675 		dev_err_ratelimited(sfp->dev,
676 				    "failed to read SFP soft status: %pe\n",
677 				    ERR_PTR(ret));
678 		/* Preserve the current state */
679 		state = sfp->state;
680 	}
681 
682 	return state & sfp->state_soft_mask;
683 }
684 
685 static void sfp_soft_set_state(struct sfp *sfp, unsigned int state)
686 {
687 	u8 mask = SFP_STATUS_TX_DISABLE_FORCE;
688 	u8 val = 0;
689 
690 	if (state & SFP_F_TX_DISABLE)
691 		val |= SFP_STATUS_TX_DISABLE_FORCE;
692 
693 
694 	sfp_modify_u8(sfp, true, SFP_STATUS, mask, val);
695 }
696 
697 static void sfp_soft_start_poll(struct sfp *sfp)
698 {
699 	const struct sfp_eeprom_id *id = &sfp->id;
700 	unsigned int mask = 0;
701 
702 	if (id->ext.enhopts & SFP_ENHOPTS_SOFT_TX_DISABLE)
703 		mask |= SFP_F_TX_DISABLE;
704 	if (id->ext.enhopts & SFP_ENHOPTS_SOFT_TX_FAULT)
705 		mask |= SFP_F_TX_FAULT;
706 	if (id->ext.enhopts & SFP_ENHOPTS_SOFT_RX_LOS)
707 		mask |= SFP_F_LOS;
708 
709 	mutex_lock(&sfp->st_mutex);
710 	// Poll the soft state for hardware pins we want to ignore
711 	sfp->state_soft_mask = ~sfp->state_hw_mask & mask;
712 
713 	if (sfp->state_soft_mask & (SFP_F_LOS | SFP_F_TX_FAULT) &&
714 	    !sfp->need_poll)
715 		mod_delayed_work(system_wq, &sfp->poll, poll_jiffies);
716 	mutex_unlock(&sfp->st_mutex);
717 }
718 
719 static void sfp_soft_stop_poll(struct sfp *sfp)
720 {
721 	mutex_lock(&sfp->st_mutex);
722 	sfp->state_soft_mask = 0;
723 	mutex_unlock(&sfp->st_mutex);
724 }
725 
726 /* sfp_get_state() - must be called with st_mutex held, or in the
727  * initialisation path.
728  */
729 static unsigned int sfp_get_state(struct sfp *sfp)
730 {
731 	unsigned int soft = sfp->state_soft_mask & (SFP_F_LOS | SFP_F_TX_FAULT);
732 	unsigned int state;
733 
734 	state = sfp->get_state(sfp) & sfp->state_hw_mask;
735 	if (state & SFP_F_PRESENT && soft)
736 		state |= sfp_soft_get_state(sfp);
737 
738 	return state;
739 }
740 
741 /* sfp_set_state() - must be called with st_mutex held, or in the
742  * initialisation path.
743  */
744 static void sfp_set_state(struct sfp *sfp, unsigned int state)
745 {
746 	sfp->set_state(sfp, state);
747 
748 	if (state & SFP_F_PRESENT &&
749 	    sfp->state_soft_mask & SFP_F_TX_DISABLE)
750 		sfp_soft_set_state(sfp, state);
751 }
752 
753 static void sfp_mod_state(struct sfp *sfp, unsigned int mask, unsigned int set)
754 {
755 	mutex_lock(&sfp->st_mutex);
756 	sfp->state = (sfp->state & ~mask) | set;
757 	sfp_set_state(sfp, sfp->state);
758 	mutex_unlock(&sfp->st_mutex);
759 }
760 
761 static unsigned int sfp_check(void *buf, size_t len)
762 {
763 	u8 *p, check;
764 
765 	for (p = buf, check = 0; len; p++, len--)
766 		check += *p;
767 
768 	return check;
769 }
770 
771 /* hwmon */
772 #if IS_ENABLED(CONFIG_HWMON)
773 static umode_t sfp_hwmon_is_visible(const void *data,
774 				    enum hwmon_sensor_types type,
775 				    u32 attr, int channel)
776 {
777 	const struct sfp *sfp = data;
778 
779 	switch (type) {
780 	case hwmon_temp:
781 		switch (attr) {
782 		case hwmon_temp_min_alarm:
783 		case hwmon_temp_max_alarm:
784 		case hwmon_temp_lcrit_alarm:
785 		case hwmon_temp_crit_alarm:
786 		case hwmon_temp_min:
787 		case hwmon_temp_max:
788 		case hwmon_temp_lcrit:
789 		case hwmon_temp_crit:
790 			if (!(sfp->id.ext.enhopts & SFP_ENHOPTS_ALARMWARN))
791 				return 0;
792 			fallthrough;
793 		case hwmon_temp_input:
794 		case hwmon_temp_label:
795 			return 0444;
796 		default:
797 			return 0;
798 		}
799 	case hwmon_in:
800 		switch (attr) {
801 		case hwmon_in_min_alarm:
802 		case hwmon_in_max_alarm:
803 		case hwmon_in_lcrit_alarm:
804 		case hwmon_in_crit_alarm:
805 		case hwmon_in_min:
806 		case hwmon_in_max:
807 		case hwmon_in_lcrit:
808 		case hwmon_in_crit:
809 			if (!(sfp->id.ext.enhopts & SFP_ENHOPTS_ALARMWARN))
810 				return 0;
811 			fallthrough;
812 		case hwmon_in_input:
813 		case hwmon_in_label:
814 			return 0444;
815 		default:
816 			return 0;
817 		}
818 	case hwmon_curr:
819 		switch (attr) {
820 		case hwmon_curr_min_alarm:
821 		case hwmon_curr_max_alarm:
822 		case hwmon_curr_lcrit_alarm:
823 		case hwmon_curr_crit_alarm:
824 		case hwmon_curr_min:
825 		case hwmon_curr_max:
826 		case hwmon_curr_lcrit:
827 		case hwmon_curr_crit:
828 			if (!(sfp->id.ext.enhopts & SFP_ENHOPTS_ALARMWARN))
829 				return 0;
830 			fallthrough;
831 		case hwmon_curr_input:
832 		case hwmon_curr_label:
833 			return 0444;
834 		default:
835 			return 0;
836 		}
837 	case hwmon_power:
838 		/* External calibration of receive power requires
839 		 * floating point arithmetic. Doing that in the kernel
840 		 * is not easy, so just skip it. If the module does
841 		 * not require external calibration, we can however
842 		 * show receiver power, since FP is then not needed.
843 		 */
844 		if (sfp->id.ext.diagmon & SFP_DIAGMON_EXT_CAL &&
845 		    channel == 1)
846 			return 0;
847 		switch (attr) {
848 		case hwmon_power_min_alarm:
849 		case hwmon_power_max_alarm:
850 		case hwmon_power_lcrit_alarm:
851 		case hwmon_power_crit_alarm:
852 		case hwmon_power_min:
853 		case hwmon_power_max:
854 		case hwmon_power_lcrit:
855 		case hwmon_power_crit:
856 			if (!(sfp->id.ext.enhopts & SFP_ENHOPTS_ALARMWARN))
857 				return 0;
858 			fallthrough;
859 		case hwmon_power_input:
860 		case hwmon_power_label:
861 			return 0444;
862 		default:
863 			return 0;
864 		}
865 	default:
866 		return 0;
867 	}
868 }
869 
870 static int sfp_hwmon_read_sensor(struct sfp *sfp, int reg, long *value)
871 {
872 	__be16 val;
873 	int err;
874 
875 	err = sfp_read(sfp, true, reg, &val, sizeof(val));
876 	if (err < 0)
877 		return err;
878 
879 	*value = be16_to_cpu(val);
880 
881 	return 0;
882 }
883 
884 static void sfp_hwmon_to_rx_power(long *value)
885 {
886 	*value = DIV_ROUND_CLOSEST(*value, 10);
887 }
888 
889 static void sfp_hwmon_calibrate(struct sfp *sfp, unsigned int slope, int offset,
890 				long *value)
891 {
892 	if (sfp->id.ext.diagmon & SFP_DIAGMON_EXT_CAL)
893 		*value = DIV_ROUND_CLOSEST(*value * slope, 256) + offset;
894 }
895 
896 static void sfp_hwmon_calibrate_temp(struct sfp *sfp, long *value)
897 {
898 	sfp_hwmon_calibrate(sfp, be16_to_cpu(sfp->diag.cal_t_slope),
899 			    be16_to_cpu(sfp->diag.cal_t_offset), value);
900 
901 	if (*value >= 0x8000)
902 		*value -= 0x10000;
903 
904 	*value = DIV_ROUND_CLOSEST(*value * 1000, 256);
905 }
906 
907 static void sfp_hwmon_calibrate_vcc(struct sfp *sfp, long *value)
908 {
909 	sfp_hwmon_calibrate(sfp, be16_to_cpu(sfp->diag.cal_v_slope),
910 			    be16_to_cpu(sfp->diag.cal_v_offset), value);
911 
912 	*value = DIV_ROUND_CLOSEST(*value, 10);
913 }
914 
915 static void sfp_hwmon_calibrate_bias(struct sfp *sfp, long *value)
916 {
917 	sfp_hwmon_calibrate(sfp, be16_to_cpu(sfp->diag.cal_txi_slope),
918 			    be16_to_cpu(sfp->diag.cal_txi_offset), value);
919 
920 	*value = DIV_ROUND_CLOSEST(*value, 500);
921 }
922 
923 static void sfp_hwmon_calibrate_tx_power(struct sfp *sfp, long *value)
924 {
925 	sfp_hwmon_calibrate(sfp, be16_to_cpu(sfp->diag.cal_txpwr_slope),
926 			    be16_to_cpu(sfp->diag.cal_txpwr_offset), value);
927 
928 	*value = DIV_ROUND_CLOSEST(*value, 10);
929 }
930 
931 static int sfp_hwmon_read_temp(struct sfp *sfp, int reg, long *value)
932 {
933 	int err;
934 
935 	err = sfp_hwmon_read_sensor(sfp, reg, value);
936 	if (err < 0)
937 		return err;
938 
939 	sfp_hwmon_calibrate_temp(sfp, value);
940 
941 	return 0;
942 }
943 
944 static int sfp_hwmon_read_vcc(struct sfp *sfp, int reg, long *value)
945 {
946 	int err;
947 
948 	err = sfp_hwmon_read_sensor(sfp, reg, value);
949 	if (err < 0)
950 		return err;
951 
952 	sfp_hwmon_calibrate_vcc(sfp, value);
953 
954 	return 0;
955 }
956 
957 static int sfp_hwmon_read_bias(struct sfp *sfp, int reg, long *value)
958 {
959 	int err;
960 
961 	err = sfp_hwmon_read_sensor(sfp, reg, value);
962 	if (err < 0)
963 		return err;
964 
965 	sfp_hwmon_calibrate_bias(sfp, value);
966 
967 	return 0;
968 }
969 
970 static int sfp_hwmon_read_tx_power(struct sfp *sfp, int reg, long *value)
971 {
972 	int err;
973 
974 	err = sfp_hwmon_read_sensor(sfp, reg, value);
975 	if (err < 0)
976 		return err;
977 
978 	sfp_hwmon_calibrate_tx_power(sfp, value);
979 
980 	return 0;
981 }
982 
983 static int sfp_hwmon_read_rx_power(struct sfp *sfp, int reg, long *value)
984 {
985 	int err;
986 
987 	err = sfp_hwmon_read_sensor(sfp, reg, value);
988 	if (err < 0)
989 		return err;
990 
991 	sfp_hwmon_to_rx_power(value);
992 
993 	return 0;
994 }
995 
996 static int sfp_hwmon_temp(struct sfp *sfp, u32 attr, long *value)
997 {
998 	u8 status;
999 	int err;
1000 
1001 	switch (attr) {
1002 	case hwmon_temp_input:
1003 		return sfp_hwmon_read_temp(sfp, SFP_TEMP, value);
1004 
1005 	case hwmon_temp_lcrit:
1006 		*value = be16_to_cpu(sfp->diag.temp_low_alarm);
1007 		sfp_hwmon_calibrate_temp(sfp, value);
1008 		return 0;
1009 
1010 	case hwmon_temp_min:
1011 		*value = be16_to_cpu(sfp->diag.temp_low_warn);
1012 		sfp_hwmon_calibrate_temp(sfp, value);
1013 		return 0;
1014 	case hwmon_temp_max:
1015 		*value = be16_to_cpu(sfp->diag.temp_high_warn);
1016 		sfp_hwmon_calibrate_temp(sfp, value);
1017 		return 0;
1018 
1019 	case hwmon_temp_crit:
1020 		*value = be16_to_cpu(sfp->diag.temp_high_alarm);
1021 		sfp_hwmon_calibrate_temp(sfp, value);
1022 		return 0;
1023 
1024 	case hwmon_temp_lcrit_alarm:
1025 		err = sfp_read(sfp, true, SFP_ALARM0, &status, sizeof(status));
1026 		if (err < 0)
1027 			return err;
1028 
1029 		*value = !!(status & SFP_ALARM0_TEMP_LOW);
1030 		return 0;
1031 
1032 	case hwmon_temp_min_alarm:
1033 		err = sfp_read(sfp, true, SFP_WARN0, &status, sizeof(status));
1034 		if (err < 0)
1035 			return err;
1036 
1037 		*value = !!(status & SFP_WARN0_TEMP_LOW);
1038 		return 0;
1039 
1040 	case hwmon_temp_max_alarm:
1041 		err = sfp_read(sfp, true, SFP_WARN0, &status, sizeof(status));
1042 		if (err < 0)
1043 			return err;
1044 
1045 		*value = !!(status & SFP_WARN0_TEMP_HIGH);
1046 		return 0;
1047 
1048 	case hwmon_temp_crit_alarm:
1049 		err = sfp_read(sfp, true, SFP_ALARM0, &status, sizeof(status));
1050 		if (err < 0)
1051 			return err;
1052 
1053 		*value = !!(status & SFP_ALARM0_TEMP_HIGH);
1054 		return 0;
1055 	default:
1056 		return -EOPNOTSUPP;
1057 	}
1058 
1059 	return -EOPNOTSUPP;
1060 }
1061 
1062 static int sfp_hwmon_vcc(struct sfp *sfp, u32 attr, long *value)
1063 {
1064 	u8 status;
1065 	int err;
1066 
1067 	switch (attr) {
1068 	case hwmon_in_input:
1069 		return sfp_hwmon_read_vcc(sfp, SFP_VCC, value);
1070 
1071 	case hwmon_in_lcrit:
1072 		*value = be16_to_cpu(sfp->diag.volt_low_alarm);
1073 		sfp_hwmon_calibrate_vcc(sfp, value);
1074 		return 0;
1075 
1076 	case hwmon_in_min:
1077 		*value = be16_to_cpu(sfp->diag.volt_low_warn);
1078 		sfp_hwmon_calibrate_vcc(sfp, value);
1079 		return 0;
1080 
1081 	case hwmon_in_max:
1082 		*value = be16_to_cpu(sfp->diag.volt_high_warn);
1083 		sfp_hwmon_calibrate_vcc(sfp, value);
1084 		return 0;
1085 
1086 	case hwmon_in_crit:
1087 		*value = be16_to_cpu(sfp->diag.volt_high_alarm);
1088 		sfp_hwmon_calibrate_vcc(sfp, value);
1089 		return 0;
1090 
1091 	case hwmon_in_lcrit_alarm:
1092 		err = sfp_read(sfp, true, SFP_ALARM0, &status, sizeof(status));
1093 		if (err < 0)
1094 			return err;
1095 
1096 		*value = !!(status & SFP_ALARM0_VCC_LOW);
1097 		return 0;
1098 
1099 	case hwmon_in_min_alarm:
1100 		err = sfp_read(sfp, true, SFP_WARN0, &status, sizeof(status));
1101 		if (err < 0)
1102 			return err;
1103 
1104 		*value = !!(status & SFP_WARN0_VCC_LOW);
1105 		return 0;
1106 
1107 	case hwmon_in_max_alarm:
1108 		err = sfp_read(sfp, true, SFP_WARN0, &status, sizeof(status));
1109 		if (err < 0)
1110 			return err;
1111 
1112 		*value = !!(status & SFP_WARN0_VCC_HIGH);
1113 		return 0;
1114 
1115 	case hwmon_in_crit_alarm:
1116 		err = sfp_read(sfp, true, SFP_ALARM0, &status, sizeof(status));
1117 		if (err < 0)
1118 			return err;
1119 
1120 		*value = !!(status & SFP_ALARM0_VCC_HIGH);
1121 		return 0;
1122 	default:
1123 		return -EOPNOTSUPP;
1124 	}
1125 
1126 	return -EOPNOTSUPP;
1127 }
1128 
1129 static int sfp_hwmon_bias(struct sfp *sfp, u32 attr, long *value)
1130 {
1131 	u8 status;
1132 	int err;
1133 
1134 	switch (attr) {
1135 	case hwmon_curr_input:
1136 		return sfp_hwmon_read_bias(sfp, SFP_TX_BIAS, value);
1137 
1138 	case hwmon_curr_lcrit:
1139 		*value = be16_to_cpu(sfp->diag.bias_low_alarm);
1140 		sfp_hwmon_calibrate_bias(sfp, value);
1141 		return 0;
1142 
1143 	case hwmon_curr_min:
1144 		*value = be16_to_cpu(sfp->diag.bias_low_warn);
1145 		sfp_hwmon_calibrate_bias(sfp, value);
1146 		return 0;
1147 
1148 	case hwmon_curr_max:
1149 		*value = be16_to_cpu(sfp->diag.bias_high_warn);
1150 		sfp_hwmon_calibrate_bias(sfp, value);
1151 		return 0;
1152 
1153 	case hwmon_curr_crit:
1154 		*value = be16_to_cpu(sfp->diag.bias_high_alarm);
1155 		sfp_hwmon_calibrate_bias(sfp, value);
1156 		return 0;
1157 
1158 	case hwmon_curr_lcrit_alarm:
1159 		err = sfp_read(sfp, true, SFP_ALARM0, &status, sizeof(status));
1160 		if (err < 0)
1161 			return err;
1162 
1163 		*value = !!(status & SFP_ALARM0_TX_BIAS_LOW);
1164 		return 0;
1165 
1166 	case hwmon_curr_min_alarm:
1167 		err = sfp_read(sfp, true, SFP_WARN0, &status, sizeof(status));
1168 		if (err < 0)
1169 			return err;
1170 
1171 		*value = !!(status & SFP_WARN0_TX_BIAS_LOW);
1172 		return 0;
1173 
1174 	case hwmon_curr_max_alarm:
1175 		err = sfp_read(sfp, true, SFP_WARN0, &status, sizeof(status));
1176 		if (err < 0)
1177 			return err;
1178 
1179 		*value = !!(status & SFP_WARN0_TX_BIAS_HIGH);
1180 		return 0;
1181 
1182 	case hwmon_curr_crit_alarm:
1183 		err = sfp_read(sfp, true, SFP_ALARM0, &status, sizeof(status));
1184 		if (err < 0)
1185 			return err;
1186 
1187 		*value = !!(status & SFP_ALARM0_TX_BIAS_HIGH);
1188 		return 0;
1189 	default:
1190 		return -EOPNOTSUPP;
1191 	}
1192 
1193 	return -EOPNOTSUPP;
1194 }
1195 
1196 static int sfp_hwmon_tx_power(struct sfp *sfp, u32 attr, long *value)
1197 {
1198 	u8 status;
1199 	int err;
1200 
1201 	switch (attr) {
1202 	case hwmon_power_input:
1203 		return sfp_hwmon_read_tx_power(sfp, SFP_TX_POWER, value);
1204 
1205 	case hwmon_power_lcrit:
1206 		*value = be16_to_cpu(sfp->diag.txpwr_low_alarm);
1207 		sfp_hwmon_calibrate_tx_power(sfp, value);
1208 		return 0;
1209 
1210 	case hwmon_power_min:
1211 		*value = be16_to_cpu(sfp->diag.txpwr_low_warn);
1212 		sfp_hwmon_calibrate_tx_power(sfp, value);
1213 		return 0;
1214 
1215 	case hwmon_power_max:
1216 		*value = be16_to_cpu(sfp->diag.txpwr_high_warn);
1217 		sfp_hwmon_calibrate_tx_power(sfp, value);
1218 		return 0;
1219 
1220 	case hwmon_power_crit:
1221 		*value = be16_to_cpu(sfp->diag.txpwr_high_alarm);
1222 		sfp_hwmon_calibrate_tx_power(sfp, value);
1223 		return 0;
1224 
1225 	case hwmon_power_lcrit_alarm:
1226 		err = sfp_read(sfp, true, SFP_ALARM0, &status, sizeof(status));
1227 		if (err < 0)
1228 			return err;
1229 
1230 		*value = !!(status & SFP_ALARM0_TXPWR_LOW);
1231 		return 0;
1232 
1233 	case hwmon_power_min_alarm:
1234 		err = sfp_read(sfp, true, SFP_WARN0, &status, sizeof(status));
1235 		if (err < 0)
1236 			return err;
1237 
1238 		*value = !!(status & SFP_WARN0_TXPWR_LOW);
1239 		return 0;
1240 
1241 	case hwmon_power_max_alarm:
1242 		err = sfp_read(sfp, true, SFP_WARN0, &status, sizeof(status));
1243 		if (err < 0)
1244 			return err;
1245 
1246 		*value = !!(status & SFP_WARN0_TXPWR_HIGH);
1247 		return 0;
1248 
1249 	case hwmon_power_crit_alarm:
1250 		err = sfp_read(sfp, true, SFP_ALARM0, &status, sizeof(status));
1251 		if (err < 0)
1252 			return err;
1253 
1254 		*value = !!(status & SFP_ALARM0_TXPWR_HIGH);
1255 		return 0;
1256 	default:
1257 		return -EOPNOTSUPP;
1258 	}
1259 
1260 	return -EOPNOTSUPP;
1261 }
1262 
1263 static int sfp_hwmon_rx_power(struct sfp *sfp, u32 attr, long *value)
1264 {
1265 	u8 status;
1266 	int err;
1267 
1268 	switch (attr) {
1269 	case hwmon_power_input:
1270 		return sfp_hwmon_read_rx_power(sfp, SFP_RX_POWER, value);
1271 
1272 	case hwmon_power_lcrit:
1273 		*value = be16_to_cpu(sfp->diag.rxpwr_low_alarm);
1274 		sfp_hwmon_to_rx_power(value);
1275 		return 0;
1276 
1277 	case hwmon_power_min:
1278 		*value = be16_to_cpu(sfp->diag.rxpwr_low_warn);
1279 		sfp_hwmon_to_rx_power(value);
1280 		return 0;
1281 
1282 	case hwmon_power_max:
1283 		*value = be16_to_cpu(sfp->diag.rxpwr_high_warn);
1284 		sfp_hwmon_to_rx_power(value);
1285 		return 0;
1286 
1287 	case hwmon_power_crit:
1288 		*value = be16_to_cpu(sfp->diag.rxpwr_high_alarm);
1289 		sfp_hwmon_to_rx_power(value);
1290 		return 0;
1291 
1292 	case hwmon_power_lcrit_alarm:
1293 		err = sfp_read(sfp, true, SFP_ALARM1, &status, sizeof(status));
1294 		if (err < 0)
1295 			return err;
1296 
1297 		*value = !!(status & SFP_ALARM1_RXPWR_LOW);
1298 		return 0;
1299 
1300 	case hwmon_power_min_alarm:
1301 		err = sfp_read(sfp, true, SFP_WARN1, &status, sizeof(status));
1302 		if (err < 0)
1303 			return err;
1304 
1305 		*value = !!(status & SFP_WARN1_RXPWR_LOW);
1306 		return 0;
1307 
1308 	case hwmon_power_max_alarm:
1309 		err = sfp_read(sfp, true, SFP_WARN1, &status, sizeof(status));
1310 		if (err < 0)
1311 			return err;
1312 
1313 		*value = !!(status & SFP_WARN1_RXPWR_HIGH);
1314 		return 0;
1315 
1316 	case hwmon_power_crit_alarm:
1317 		err = sfp_read(sfp, true, SFP_ALARM1, &status, sizeof(status));
1318 		if (err < 0)
1319 			return err;
1320 
1321 		*value = !!(status & SFP_ALARM1_RXPWR_HIGH);
1322 		return 0;
1323 	default:
1324 		return -EOPNOTSUPP;
1325 	}
1326 
1327 	return -EOPNOTSUPP;
1328 }
1329 
1330 static int sfp_hwmon_read(struct device *dev, enum hwmon_sensor_types type,
1331 			  u32 attr, int channel, long *value)
1332 {
1333 	struct sfp *sfp = dev_get_drvdata(dev);
1334 
1335 	switch (type) {
1336 	case hwmon_temp:
1337 		return sfp_hwmon_temp(sfp, attr, value);
1338 	case hwmon_in:
1339 		return sfp_hwmon_vcc(sfp, attr, value);
1340 	case hwmon_curr:
1341 		return sfp_hwmon_bias(sfp, attr, value);
1342 	case hwmon_power:
1343 		switch (channel) {
1344 		case 0:
1345 			return sfp_hwmon_tx_power(sfp, attr, value);
1346 		case 1:
1347 			return sfp_hwmon_rx_power(sfp, attr, value);
1348 		default:
1349 			return -EOPNOTSUPP;
1350 		}
1351 	default:
1352 		return -EOPNOTSUPP;
1353 	}
1354 }
1355 
1356 static const char *const sfp_hwmon_power_labels[] = {
1357 	"TX_power",
1358 	"RX_power",
1359 };
1360 
1361 static int sfp_hwmon_read_string(struct device *dev,
1362 				 enum hwmon_sensor_types type,
1363 				 u32 attr, int channel, const char **str)
1364 {
1365 	switch (type) {
1366 	case hwmon_curr:
1367 		switch (attr) {
1368 		case hwmon_curr_label:
1369 			*str = "bias";
1370 			return 0;
1371 		default:
1372 			return -EOPNOTSUPP;
1373 		}
1374 		break;
1375 	case hwmon_temp:
1376 		switch (attr) {
1377 		case hwmon_temp_label:
1378 			*str = "temperature";
1379 			return 0;
1380 		default:
1381 			return -EOPNOTSUPP;
1382 		}
1383 		break;
1384 	case hwmon_in:
1385 		switch (attr) {
1386 		case hwmon_in_label:
1387 			*str = "VCC";
1388 			return 0;
1389 		default:
1390 			return -EOPNOTSUPP;
1391 		}
1392 		break;
1393 	case hwmon_power:
1394 		switch (attr) {
1395 		case hwmon_power_label:
1396 			*str = sfp_hwmon_power_labels[channel];
1397 			return 0;
1398 		default:
1399 			return -EOPNOTSUPP;
1400 		}
1401 		break;
1402 	default:
1403 		return -EOPNOTSUPP;
1404 	}
1405 
1406 	return -EOPNOTSUPP;
1407 }
1408 
1409 static const struct hwmon_ops sfp_hwmon_ops = {
1410 	.is_visible = sfp_hwmon_is_visible,
1411 	.read = sfp_hwmon_read,
1412 	.read_string = sfp_hwmon_read_string,
1413 };
1414 
1415 static const struct hwmon_channel_info * const sfp_hwmon_info[] = {
1416 	HWMON_CHANNEL_INFO(chip,
1417 			   HWMON_C_REGISTER_TZ),
1418 	HWMON_CHANNEL_INFO(in,
1419 			   HWMON_I_INPUT |
1420 			   HWMON_I_MAX | HWMON_I_MIN |
1421 			   HWMON_I_MAX_ALARM | HWMON_I_MIN_ALARM |
1422 			   HWMON_I_CRIT | HWMON_I_LCRIT |
1423 			   HWMON_I_CRIT_ALARM | HWMON_I_LCRIT_ALARM |
1424 			   HWMON_I_LABEL),
1425 	HWMON_CHANNEL_INFO(temp,
1426 			   HWMON_T_INPUT |
1427 			   HWMON_T_MAX | HWMON_T_MIN |
1428 			   HWMON_T_MAX_ALARM | HWMON_T_MIN_ALARM |
1429 			   HWMON_T_CRIT | HWMON_T_LCRIT |
1430 			   HWMON_T_CRIT_ALARM | HWMON_T_LCRIT_ALARM |
1431 			   HWMON_T_LABEL),
1432 	HWMON_CHANNEL_INFO(curr,
1433 			   HWMON_C_INPUT |
1434 			   HWMON_C_MAX | HWMON_C_MIN |
1435 			   HWMON_C_MAX_ALARM | HWMON_C_MIN_ALARM |
1436 			   HWMON_C_CRIT | HWMON_C_LCRIT |
1437 			   HWMON_C_CRIT_ALARM | HWMON_C_LCRIT_ALARM |
1438 			   HWMON_C_LABEL),
1439 	HWMON_CHANNEL_INFO(power,
1440 			   /* Transmit power */
1441 			   HWMON_P_INPUT |
1442 			   HWMON_P_MAX | HWMON_P_MIN |
1443 			   HWMON_P_MAX_ALARM | HWMON_P_MIN_ALARM |
1444 			   HWMON_P_CRIT | HWMON_P_LCRIT |
1445 			   HWMON_P_CRIT_ALARM | HWMON_P_LCRIT_ALARM |
1446 			   HWMON_P_LABEL,
1447 			   /* Receive power */
1448 			   HWMON_P_INPUT |
1449 			   HWMON_P_MAX | HWMON_P_MIN |
1450 			   HWMON_P_MAX_ALARM | HWMON_P_MIN_ALARM |
1451 			   HWMON_P_CRIT | HWMON_P_LCRIT |
1452 			   HWMON_P_CRIT_ALARM | HWMON_P_LCRIT_ALARM |
1453 			   HWMON_P_LABEL),
1454 	NULL,
1455 };
1456 
1457 static const struct hwmon_chip_info sfp_hwmon_chip_info = {
1458 	.ops = &sfp_hwmon_ops,
1459 	.info = sfp_hwmon_info,
1460 };
1461 
1462 static void sfp_hwmon_probe(struct work_struct *work)
1463 {
1464 	struct sfp *sfp = container_of(work, struct sfp, hwmon_probe.work);
1465 	int err;
1466 
1467 	/* hwmon interface needs to access 16bit registers in atomic way to
1468 	 * guarantee coherency of the diagnostic monitoring data. If it is not
1469 	 * possible to guarantee coherency because EEPROM is broken in such way
1470 	 * that does not support atomic 16bit read operation then we have to
1471 	 * skip registration of hwmon device.
1472 	 */
1473 	if (sfp->i2c_block_size < 2) {
1474 		dev_info(sfp->dev,
1475 			 "skipping hwmon device registration due to broken EEPROM\n");
1476 		dev_info(sfp->dev,
1477 			 "diagnostic EEPROM area cannot be read atomically to guarantee data coherency\n");
1478 		return;
1479 	}
1480 
1481 	err = sfp_read(sfp, true, 0, &sfp->diag, sizeof(sfp->diag));
1482 	if (err < 0) {
1483 		if (sfp->hwmon_tries--) {
1484 			mod_delayed_work(system_wq, &sfp->hwmon_probe,
1485 					 T_PROBE_RETRY_SLOW);
1486 		} else {
1487 			dev_warn(sfp->dev, "hwmon probe failed: %pe\n",
1488 				 ERR_PTR(err));
1489 		}
1490 		return;
1491 	}
1492 
1493 	sfp->hwmon_name = hwmon_sanitize_name(dev_name(sfp->dev));
1494 	if (IS_ERR(sfp->hwmon_name)) {
1495 		dev_err(sfp->dev, "out of memory for hwmon name\n");
1496 		return;
1497 	}
1498 
1499 	sfp->hwmon_dev = hwmon_device_register_with_info(sfp->dev,
1500 							 sfp->hwmon_name, sfp,
1501 							 &sfp_hwmon_chip_info,
1502 							 NULL);
1503 	if (IS_ERR(sfp->hwmon_dev))
1504 		dev_err(sfp->dev, "failed to register hwmon device: %ld\n",
1505 			PTR_ERR(sfp->hwmon_dev));
1506 }
1507 
1508 static int sfp_hwmon_insert(struct sfp *sfp)
1509 {
1510 	if (sfp->have_a2 && sfp->id.ext.diagmon & SFP_DIAGMON_DDM) {
1511 		mod_delayed_work(system_wq, &sfp->hwmon_probe, 1);
1512 		sfp->hwmon_tries = R_PROBE_RETRY_SLOW;
1513 	}
1514 
1515 	return 0;
1516 }
1517 
1518 static void sfp_hwmon_remove(struct sfp *sfp)
1519 {
1520 	cancel_delayed_work_sync(&sfp->hwmon_probe);
1521 	if (!IS_ERR_OR_NULL(sfp->hwmon_dev)) {
1522 		hwmon_device_unregister(sfp->hwmon_dev);
1523 		sfp->hwmon_dev = NULL;
1524 		kfree(sfp->hwmon_name);
1525 	}
1526 }
1527 
1528 static int sfp_hwmon_init(struct sfp *sfp)
1529 {
1530 	INIT_DELAYED_WORK(&sfp->hwmon_probe, sfp_hwmon_probe);
1531 
1532 	return 0;
1533 }
1534 
1535 static void sfp_hwmon_exit(struct sfp *sfp)
1536 {
1537 	cancel_delayed_work_sync(&sfp->hwmon_probe);
1538 }
1539 #else
1540 static int sfp_hwmon_insert(struct sfp *sfp)
1541 {
1542 	return 0;
1543 }
1544 
1545 static void sfp_hwmon_remove(struct sfp *sfp)
1546 {
1547 }
1548 
1549 static int sfp_hwmon_init(struct sfp *sfp)
1550 {
1551 	return 0;
1552 }
1553 
1554 static void sfp_hwmon_exit(struct sfp *sfp)
1555 {
1556 }
1557 #endif
1558 
1559 /* Helpers */
1560 static void sfp_module_tx_disable(struct sfp *sfp)
1561 {
1562 	dev_dbg(sfp->dev, "tx disable %u -> %u\n",
1563 		sfp->state & SFP_F_TX_DISABLE ? 1 : 0, 1);
1564 	sfp_mod_state(sfp, SFP_F_TX_DISABLE, SFP_F_TX_DISABLE);
1565 }
1566 
1567 static void sfp_module_tx_enable(struct sfp *sfp)
1568 {
1569 	dev_dbg(sfp->dev, "tx disable %u -> %u\n",
1570 		sfp->state & SFP_F_TX_DISABLE ? 1 : 0, 0);
1571 	sfp_mod_state(sfp, SFP_F_TX_DISABLE, 0);
1572 }
1573 
1574 #if IS_ENABLED(CONFIG_DEBUG_FS)
1575 static int sfp_debug_state_show(struct seq_file *s, void *data)
1576 {
1577 	struct sfp *sfp = s->private;
1578 
1579 	seq_printf(s, "Module state: %s\n",
1580 		   mod_state_to_str(sfp->sm_mod_state));
1581 	seq_printf(s, "Module probe attempts: %d %d\n",
1582 		   R_PROBE_RETRY_INIT - sfp->sm_mod_tries_init,
1583 		   R_PROBE_RETRY_SLOW - sfp->sm_mod_tries);
1584 	seq_printf(s, "Device state: %s\n",
1585 		   dev_state_to_str(sfp->sm_dev_state));
1586 	seq_printf(s, "Main state: %s\n",
1587 		   sm_state_to_str(sfp->sm_state));
1588 	seq_printf(s, "Fault recovery remaining retries: %d\n",
1589 		   sfp->sm_fault_retries);
1590 	seq_printf(s, "PHY probe remaining retries: %d\n",
1591 		   sfp->sm_phy_retries);
1592 	seq_printf(s, "moddef0: %d\n", !!(sfp->state & SFP_F_PRESENT));
1593 	seq_printf(s, "rx_los: %d\n", !!(sfp->state & SFP_F_LOS));
1594 	seq_printf(s, "tx_fault: %d\n", !!(sfp->state & SFP_F_TX_FAULT));
1595 	seq_printf(s, "tx_disable: %d\n", !!(sfp->state & SFP_F_TX_DISABLE));
1596 	return 0;
1597 }
1598 DEFINE_SHOW_ATTRIBUTE(sfp_debug_state);
1599 
1600 static void sfp_debugfs_init(struct sfp *sfp)
1601 {
1602 	sfp->debugfs_dir = debugfs_create_dir(dev_name(sfp->dev), NULL);
1603 
1604 	debugfs_create_file("state", 0600, sfp->debugfs_dir, sfp,
1605 			    &sfp_debug_state_fops);
1606 }
1607 
1608 static void sfp_debugfs_exit(struct sfp *sfp)
1609 {
1610 	debugfs_remove_recursive(sfp->debugfs_dir);
1611 }
1612 #else
1613 static void sfp_debugfs_init(struct sfp *sfp)
1614 {
1615 }
1616 
1617 static void sfp_debugfs_exit(struct sfp *sfp)
1618 {
1619 }
1620 #endif
1621 
1622 static void sfp_module_tx_fault_reset(struct sfp *sfp)
1623 {
1624 	unsigned int state;
1625 
1626 	mutex_lock(&sfp->st_mutex);
1627 	state = sfp->state;
1628 	if (!(state & SFP_F_TX_DISABLE)) {
1629 		sfp_set_state(sfp, state | SFP_F_TX_DISABLE);
1630 
1631 		udelay(T_RESET_US);
1632 
1633 		sfp_set_state(sfp, state);
1634 	}
1635 	mutex_unlock(&sfp->st_mutex);
1636 }
1637 
1638 /* SFP state machine */
1639 static void sfp_sm_set_timer(struct sfp *sfp, unsigned int timeout)
1640 {
1641 	if (timeout)
1642 		mod_delayed_work(system_power_efficient_wq, &sfp->timeout,
1643 				 timeout);
1644 	else
1645 		cancel_delayed_work(&sfp->timeout);
1646 }
1647 
1648 static void sfp_sm_next(struct sfp *sfp, unsigned int state,
1649 			unsigned int timeout)
1650 {
1651 	sfp->sm_state = state;
1652 	sfp_sm_set_timer(sfp, timeout);
1653 }
1654 
1655 static void sfp_sm_mod_next(struct sfp *sfp, unsigned int state,
1656 			    unsigned int timeout)
1657 {
1658 	sfp->sm_mod_state = state;
1659 	sfp_sm_set_timer(sfp, timeout);
1660 }
1661 
1662 static void sfp_sm_phy_detach(struct sfp *sfp)
1663 {
1664 	sfp_remove_phy(sfp->sfp_bus);
1665 	phy_device_remove(sfp->mod_phy);
1666 	phy_device_free(sfp->mod_phy);
1667 	sfp->mod_phy = NULL;
1668 }
1669 
1670 static int sfp_sm_probe_phy(struct sfp *sfp, int addr, bool is_c45)
1671 {
1672 	struct phy_device *phy;
1673 	int err;
1674 
1675 	phy = get_phy_device(sfp->i2c_mii, addr, is_c45);
1676 	if (phy == ERR_PTR(-ENODEV))
1677 		return PTR_ERR(phy);
1678 	if (IS_ERR(phy)) {
1679 		dev_err(sfp->dev, "mdiobus scan returned %pe\n", phy);
1680 		return PTR_ERR(phy);
1681 	}
1682 
1683 	err = phy_device_register(phy);
1684 	if (err) {
1685 		phy_device_free(phy);
1686 		dev_err(sfp->dev, "phy_device_register failed: %pe\n",
1687 			ERR_PTR(err));
1688 		return err;
1689 	}
1690 
1691 	err = sfp_add_phy(sfp->sfp_bus, phy);
1692 	if (err) {
1693 		phy_device_remove(phy);
1694 		phy_device_free(phy);
1695 		dev_err(sfp->dev, "sfp_add_phy failed: %pe\n", ERR_PTR(err));
1696 		return err;
1697 	}
1698 
1699 	sfp->mod_phy = phy;
1700 
1701 	return 0;
1702 }
1703 
1704 static void sfp_sm_link_up(struct sfp *sfp)
1705 {
1706 	sfp_link_up(sfp->sfp_bus);
1707 	sfp_sm_next(sfp, SFP_S_LINK_UP, 0);
1708 }
1709 
1710 static void sfp_sm_link_down(struct sfp *sfp)
1711 {
1712 	sfp_link_down(sfp->sfp_bus);
1713 }
1714 
1715 static void sfp_sm_link_check_los(struct sfp *sfp)
1716 {
1717 	const __be16 los_inverted = cpu_to_be16(SFP_OPTIONS_LOS_INVERTED);
1718 	const __be16 los_normal = cpu_to_be16(SFP_OPTIONS_LOS_NORMAL);
1719 	__be16 los_options = sfp->id.ext.options & (los_inverted | los_normal);
1720 	bool los = false;
1721 
1722 	/* If neither SFP_OPTIONS_LOS_INVERTED nor SFP_OPTIONS_LOS_NORMAL
1723 	 * are set, we assume that no LOS signal is available. If both are
1724 	 * set, we assume LOS is not implemented (and is meaningless.)
1725 	 */
1726 	if (los_options == los_inverted)
1727 		los = !(sfp->state & SFP_F_LOS);
1728 	else if (los_options == los_normal)
1729 		los = !!(sfp->state & SFP_F_LOS);
1730 
1731 	if (los)
1732 		sfp_sm_next(sfp, SFP_S_WAIT_LOS, 0);
1733 	else
1734 		sfp_sm_link_up(sfp);
1735 }
1736 
1737 static bool sfp_los_event_active(struct sfp *sfp, unsigned int event)
1738 {
1739 	const __be16 los_inverted = cpu_to_be16(SFP_OPTIONS_LOS_INVERTED);
1740 	const __be16 los_normal = cpu_to_be16(SFP_OPTIONS_LOS_NORMAL);
1741 	__be16 los_options = sfp->id.ext.options & (los_inverted | los_normal);
1742 
1743 	return (los_options == los_inverted && event == SFP_E_LOS_LOW) ||
1744 	       (los_options == los_normal && event == SFP_E_LOS_HIGH);
1745 }
1746 
1747 static bool sfp_los_event_inactive(struct sfp *sfp, unsigned int event)
1748 {
1749 	const __be16 los_inverted = cpu_to_be16(SFP_OPTIONS_LOS_INVERTED);
1750 	const __be16 los_normal = cpu_to_be16(SFP_OPTIONS_LOS_NORMAL);
1751 	__be16 los_options = sfp->id.ext.options & (los_inverted | los_normal);
1752 
1753 	return (los_options == los_inverted && event == SFP_E_LOS_HIGH) ||
1754 	       (los_options == los_normal && event == SFP_E_LOS_LOW);
1755 }
1756 
1757 static void sfp_sm_fault(struct sfp *sfp, unsigned int next_state, bool warn)
1758 {
1759 	if (sfp->sm_fault_retries && !--sfp->sm_fault_retries) {
1760 		dev_err(sfp->dev,
1761 			"module persistently indicates fault, disabling\n");
1762 		sfp_sm_next(sfp, SFP_S_TX_DISABLE, 0);
1763 	} else {
1764 		if (warn)
1765 			dev_err(sfp->dev, "module transmit fault indicated\n");
1766 
1767 		sfp_sm_next(sfp, next_state, T_FAULT_RECOVER);
1768 	}
1769 }
1770 
1771 static int sfp_sm_add_mdio_bus(struct sfp *sfp)
1772 {
1773 	if (sfp->mdio_protocol != MDIO_I2C_NONE)
1774 		return sfp_i2c_mdiobus_create(sfp);
1775 
1776 	return 0;
1777 }
1778 
1779 /* Probe a SFP for a PHY device if the module supports copper - the PHY
1780  * normally sits at I2C bus address 0x56, and may either be a clause 22
1781  * or clause 45 PHY.
1782  *
1783  * Clause 22 copper SFP modules normally operate in Cisco SGMII mode with
1784  * negotiation enabled, but some may be in 1000base-X - which is for the
1785  * PHY driver to determine.
1786  *
1787  * Clause 45 copper SFP+ modules (10G) appear to switch their interface
1788  * mode according to the negotiated line speed.
1789  */
1790 static int sfp_sm_probe_for_phy(struct sfp *sfp)
1791 {
1792 	int err = 0;
1793 
1794 	switch (sfp->mdio_protocol) {
1795 	case MDIO_I2C_NONE:
1796 		break;
1797 
1798 	case MDIO_I2C_MARVELL_C22:
1799 		err = sfp_sm_probe_phy(sfp, SFP_PHY_ADDR, false);
1800 		break;
1801 
1802 	case MDIO_I2C_C45:
1803 		err = sfp_sm_probe_phy(sfp, SFP_PHY_ADDR, true);
1804 		break;
1805 
1806 	case MDIO_I2C_ROLLBALL:
1807 		err = sfp_sm_probe_phy(sfp, SFP_PHY_ADDR_ROLLBALL, true);
1808 		break;
1809 	}
1810 
1811 	return err;
1812 }
1813 
1814 static int sfp_module_parse_power(struct sfp *sfp)
1815 {
1816 	u32 power_mW = 1000;
1817 	bool supports_a2;
1818 
1819 	if (sfp->id.ext.sff8472_compliance >= SFP_SFF8472_COMPLIANCE_REV10_2 &&
1820 	    sfp->id.ext.options & cpu_to_be16(SFP_OPTIONS_POWER_DECL))
1821 		power_mW = 1500;
1822 	/* Added in Rev 11.9, but there is no compliance code for this */
1823 	if (sfp->id.ext.sff8472_compliance >= SFP_SFF8472_COMPLIANCE_REV11_4 &&
1824 	    sfp->id.ext.options & cpu_to_be16(SFP_OPTIONS_HIGH_POWER_LEVEL))
1825 		power_mW = 2000;
1826 
1827 	/* Power level 1 modules (max. 1W) are always supported. */
1828 	if (power_mW <= 1000) {
1829 		sfp->module_power_mW = power_mW;
1830 		return 0;
1831 	}
1832 
1833 	supports_a2 = sfp->id.ext.sff8472_compliance !=
1834 				SFP_SFF8472_COMPLIANCE_NONE ||
1835 		      sfp->id.ext.diagmon & SFP_DIAGMON_DDM;
1836 
1837 	if (power_mW > sfp->max_power_mW) {
1838 		/* Module power specification exceeds the allowed maximum. */
1839 		if (!supports_a2) {
1840 			/* The module appears not to implement bus address
1841 			 * 0xa2, so assume that the module powers up in the
1842 			 * indicated mode.
1843 			 */
1844 			dev_err(sfp->dev,
1845 				"Host does not support %u.%uW modules\n",
1846 				power_mW / 1000, (power_mW / 100) % 10);
1847 			return -EINVAL;
1848 		} else {
1849 			dev_warn(sfp->dev,
1850 				 "Host does not support %u.%uW modules, module left in power mode 1\n",
1851 				 power_mW / 1000, (power_mW / 100) % 10);
1852 			return 0;
1853 		}
1854 	}
1855 
1856 	if (!supports_a2) {
1857 		/* The module power level is below the host maximum and the
1858 		 * module appears not to implement bus address 0xa2, so assume
1859 		 * that the module powers up in the indicated mode.
1860 		 */
1861 		return 0;
1862 	}
1863 
1864 	/* If the module requires a higher power mode, but also requires
1865 	 * an address change sequence, warn the user that the module may
1866 	 * not be functional.
1867 	 */
1868 	if (sfp->id.ext.diagmon & SFP_DIAGMON_ADDRMODE) {
1869 		dev_warn(sfp->dev,
1870 			 "Address Change Sequence not supported but module requires %u.%uW, module may not be functional\n",
1871 			 power_mW / 1000, (power_mW / 100) % 10);
1872 		return 0;
1873 	}
1874 
1875 	sfp->module_power_mW = power_mW;
1876 
1877 	return 0;
1878 }
1879 
1880 static int sfp_sm_mod_hpower(struct sfp *sfp, bool enable)
1881 {
1882 	int err;
1883 
1884 	err = sfp_modify_u8(sfp, true, SFP_EXT_STATUS,
1885 			    SFP_EXT_STATUS_PWRLVL_SELECT,
1886 			    enable ? SFP_EXT_STATUS_PWRLVL_SELECT : 0);
1887 	if (err != sizeof(u8)) {
1888 		dev_err(sfp->dev, "failed to %sable high power: %pe\n",
1889 			enable ? "en" : "dis", ERR_PTR(err));
1890 		return -EAGAIN;
1891 	}
1892 
1893 	if (enable)
1894 		dev_info(sfp->dev, "Module switched to %u.%uW power level\n",
1895 			 sfp->module_power_mW / 1000,
1896 			 (sfp->module_power_mW / 100) % 10);
1897 
1898 	return 0;
1899 }
1900 
1901 /* GPON modules based on Realtek RTL8672 and RTL9601C chips (e.g. V-SOL
1902  * V2801F, CarlitoxxPro CPGOS03-0490, Ubiquiti U-Fiber Instant, ...) do
1903  * not support multibyte reads from the EEPROM. Each multi-byte read
1904  * operation returns just one byte of EEPROM followed by zeros. There is
1905  * no way to identify which modules are using Realtek RTL8672 and RTL9601C
1906  * chips. Moreover every OEM of V-SOL V2801F module puts its own vendor
1907  * name and vendor id into EEPROM, so there is even no way to detect if
1908  * module is V-SOL V2801F. Therefore check for those zeros in the read
1909  * data and then based on check switch to reading EEPROM to one byte
1910  * at a time.
1911  */
1912 static bool sfp_id_needs_byte_io(struct sfp *sfp, void *buf, size_t len)
1913 {
1914 	size_t i, block_size = sfp->i2c_block_size;
1915 
1916 	/* Already using byte IO */
1917 	if (block_size == 1)
1918 		return false;
1919 
1920 	for (i = 1; i < len; i += block_size) {
1921 		if (memchr_inv(buf + i, '\0', min(block_size - 1, len - i)))
1922 			return false;
1923 	}
1924 	return true;
1925 }
1926 
1927 static int sfp_cotsworks_fixup_check(struct sfp *sfp, struct sfp_eeprom_id *id)
1928 {
1929 	u8 check;
1930 	int err;
1931 
1932 	if (id->base.phys_id != SFF8024_ID_SFF_8472 ||
1933 	    id->base.phys_ext_id != SFP_PHYS_EXT_ID_SFP ||
1934 	    id->base.connector != SFF8024_CONNECTOR_LC) {
1935 		dev_warn(sfp->dev, "Rewriting fiber module EEPROM with corrected values\n");
1936 		id->base.phys_id = SFF8024_ID_SFF_8472;
1937 		id->base.phys_ext_id = SFP_PHYS_EXT_ID_SFP;
1938 		id->base.connector = SFF8024_CONNECTOR_LC;
1939 		err = sfp_write(sfp, false, SFP_PHYS_ID, &id->base, 3);
1940 		if (err != 3) {
1941 			dev_err(sfp->dev,
1942 				"Failed to rewrite module EEPROM: %pe\n",
1943 				ERR_PTR(err));
1944 			return err;
1945 		}
1946 
1947 		/* Cotsworks modules have been found to require a delay between write operations. */
1948 		mdelay(50);
1949 
1950 		/* Update base structure checksum */
1951 		check = sfp_check(&id->base, sizeof(id->base) - 1);
1952 		err = sfp_write(sfp, false, SFP_CC_BASE, &check, 1);
1953 		if (err != 1) {
1954 			dev_err(sfp->dev,
1955 				"Failed to update base structure checksum in fiber module EEPROM: %pe\n",
1956 				ERR_PTR(err));
1957 			return err;
1958 		}
1959 	}
1960 	return 0;
1961 }
1962 
1963 static int sfp_module_parse_sff8472(struct sfp *sfp)
1964 {
1965 	/* If the module requires address swap mode, warn about it */
1966 	if (sfp->id.ext.diagmon & SFP_DIAGMON_ADDRMODE)
1967 		dev_warn(sfp->dev,
1968 			 "module address swap to access page 0xA2 is not supported.\n");
1969 	else
1970 		sfp->have_a2 = true;
1971 
1972 	return 0;
1973 }
1974 
1975 static int sfp_sm_mod_probe(struct sfp *sfp, bool report)
1976 {
1977 	/* SFP module inserted - read I2C data */
1978 	struct sfp_eeprom_id id;
1979 	bool cotsworks_sfbg;
1980 	unsigned int mask;
1981 	bool cotsworks;
1982 	u8 check;
1983 	int ret;
1984 
1985 	sfp->i2c_block_size = SFP_EEPROM_BLOCK_SIZE;
1986 
1987 	ret = sfp_read(sfp, false, 0, &id.base, sizeof(id.base));
1988 	if (ret < 0) {
1989 		if (report)
1990 			dev_err(sfp->dev, "failed to read EEPROM: %pe\n",
1991 				ERR_PTR(ret));
1992 		return -EAGAIN;
1993 	}
1994 
1995 	if (ret != sizeof(id.base)) {
1996 		dev_err(sfp->dev, "EEPROM short read: %pe\n", ERR_PTR(ret));
1997 		return -EAGAIN;
1998 	}
1999 
2000 	/* Some SFP modules (e.g. Nokia 3FE46541AA) lock up if read from
2001 	 * address 0x51 is just one byte at a time. Also SFF-8472 requires
2002 	 * that EEPROM supports atomic 16bit read operation for diagnostic
2003 	 * fields, so do not switch to one byte reading at a time unless it
2004 	 * is really required and we have no other option.
2005 	 */
2006 	if (sfp_id_needs_byte_io(sfp, &id.base, sizeof(id.base))) {
2007 		dev_info(sfp->dev,
2008 			 "Detected broken RTL8672/RTL9601C emulated EEPROM\n");
2009 		dev_info(sfp->dev,
2010 			 "Switching to reading EEPROM to one byte at a time\n");
2011 		sfp->i2c_block_size = 1;
2012 
2013 		ret = sfp_read(sfp, false, 0, &id.base, sizeof(id.base));
2014 		if (ret < 0) {
2015 			if (report)
2016 				dev_err(sfp->dev,
2017 					"failed to read EEPROM: %pe\n",
2018 					ERR_PTR(ret));
2019 			return -EAGAIN;
2020 		}
2021 
2022 		if (ret != sizeof(id.base)) {
2023 			dev_err(sfp->dev, "EEPROM short read: %pe\n",
2024 				ERR_PTR(ret));
2025 			return -EAGAIN;
2026 		}
2027 	}
2028 
2029 	/* Cotsworks do not seem to update the checksums when they
2030 	 * do the final programming with the final module part number,
2031 	 * serial number and date code.
2032 	 */
2033 	cotsworks = !memcmp(id.base.vendor_name, "COTSWORKS       ", 16);
2034 	cotsworks_sfbg = !memcmp(id.base.vendor_pn, "SFBG", 4);
2035 
2036 	/* Cotsworks SFF module EEPROM do not always have valid phys_id,
2037 	 * phys_ext_id, and connector bytes.  Rewrite SFF EEPROM bytes if
2038 	 * Cotsworks PN matches and bytes are not correct.
2039 	 */
2040 	if (cotsworks && cotsworks_sfbg) {
2041 		ret = sfp_cotsworks_fixup_check(sfp, &id);
2042 		if (ret < 0)
2043 			return ret;
2044 	}
2045 
2046 	/* Validate the checksum over the base structure */
2047 	check = sfp_check(&id.base, sizeof(id.base) - 1);
2048 	if (check != id.base.cc_base) {
2049 		if (cotsworks) {
2050 			dev_warn(sfp->dev,
2051 				 "EEPROM base structure checksum failure (0x%02x != 0x%02x)\n",
2052 				 check, id.base.cc_base);
2053 		} else {
2054 			dev_err(sfp->dev,
2055 				"EEPROM base structure checksum failure: 0x%02x != 0x%02x\n",
2056 				check, id.base.cc_base);
2057 			print_hex_dump(KERN_ERR, "sfp EE: ", DUMP_PREFIX_OFFSET,
2058 				       16, 1, &id, sizeof(id), true);
2059 			return -EINVAL;
2060 		}
2061 	}
2062 
2063 	ret = sfp_read(sfp, false, SFP_CC_BASE + 1, &id.ext, sizeof(id.ext));
2064 	if (ret < 0) {
2065 		if (report)
2066 			dev_err(sfp->dev, "failed to read EEPROM: %pe\n",
2067 				ERR_PTR(ret));
2068 		return -EAGAIN;
2069 	}
2070 
2071 	if (ret != sizeof(id.ext)) {
2072 		dev_err(sfp->dev, "EEPROM short read: %pe\n", ERR_PTR(ret));
2073 		return -EAGAIN;
2074 	}
2075 
2076 	check = sfp_check(&id.ext, sizeof(id.ext) - 1);
2077 	if (check != id.ext.cc_ext) {
2078 		if (cotsworks) {
2079 			dev_warn(sfp->dev,
2080 				 "EEPROM extended structure checksum failure (0x%02x != 0x%02x)\n",
2081 				 check, id.ext.cc_ext);
2082 		} else {
2083 			dev_err(sfp->dev,
2084 				"EEPROM extended structure checksum failure: 0x%02x != 0x%02x\n",
2085 				check, id.ext.cc_ext);
2086 			print_hex_dump(KERN_ERR, "sfp EE: ", DUMP_PREFIX_OFFSET,
2087 				       16, 1, &id, sizeof(id), true);
2088 			memset(&id.ext, 0, sizeof(id.ext));
2089 		}
2090 	}
2091 
2092 	sfp->id = id;
2093 
2094 	dev_info(sfp->dev, "module %.*s %.*s rev %.*s sn %.*s dc %.*s\n",
2095 		 (int)sizeof(id.base.vendor_name), id.base.vendor_name,
2096 		 (int)sizeof(id.base.vendor_pn), id.base.vendor_pn,
2097 		 (int)sizeof(id.base.vendor_rev), id.base.vendor_rev,
2098 		 (int)sizeof(id.ext.vendor_sn), id.ext.vendor_sn,
2099 		 (int)sizeof(id.ext.datecode), id.ext.datecode);
2100 
2101 	/* Check whether we support this module */
2102 	if (!sfp->type->module_supported(&id)) {
2103 		dev_err(sfp->dev,
2104 			"module is not supported - phys id 0x%02x 0x%02x\n",
2105 			sfp->id.base.phys_id, sfp->id.base.phys_ext_id);
2106 		return -EINVAL;
2107 	}
2108 
2109 	if (sfp->id.ext.sff8472_compliance != SFP_SFF8472_COMPLIANCE_NONE) {
2110 		ret = sfp_module_parse_sff8472(sfp);
2111 		if (ret < 0)
2112 			return ret;
2113 	}
2114 
2115 	/* Parse the module power requirement */
2116 	ret = sfp_module_parse_power(sfp);
2117 	if (ret < 0)
2118 		return ret;
2119 
2120 	mask = SFP_F_PRESENT;
2121 	if (sfp->gpio[GPIO_TX_DISABLE])
2122 		mask |= SFP_F_TX_DISABLE;
2123 	if (sfp->gpio[GPIO_TX_FAULT])
2124 		mask |= SFP_F_TX_FAULT;
2125 	if (sfp->gpio[GPIO_LOS])
2126 		mask |= SFP_F_LOS;
2127 
2128 	sfp->module_t_start_up = T_START_UP;
2129 	sfp->module_t_wait = T_WAIT;
2130 
2131 	sfp->tx_fault_ignore = false;
2132 
2133 	if (sfp->id.base.extended_cc == SFF8024_ECC_10GBASE_T_SFI ||
2134 	    sfp->id.base.extended_cc == SFF8024_ECC_10GBASE_T_SR ||
2135 	    sfp->id.base.extended_cc == SFF8024_ECC_5GBASE_T ||
2136 	    sfp->id.base.extended_cc == SFF8024_ECC_2_5GBASE_T)
2137 		sfp->mdio_protocol = MDIO_I2C_C45;
2138 	else if (sfp->id.base.e1000_base_t)
2139 		sfp->mdio_protocol = MDIO_I2C_MARVELL_C22;
2140 	else
2141 		sfp->mdio_protocol = MDIO_I2C_NONE;
2142 
2143 	sfp->quirk = sfp_lookup_quirk(&id);
2144 
2145 	mutex_lock(&sfp->st_mutex);
2146 	/* Initialise state bits to use from hardware */
2147 	sfp->state_hw_mask = mask;
2148 
2149 	if (sfp->quirk && sfp->quirk->fixup)
2150 		sfp->quirk->fixup(sfp);
2151 	mutex_unlock(&sfp->st_mutex);
2152 
2153 	return 0;
2154 }
2155 
2156 static void sfp_sm_mod_remove(struct sfp *sfp)
2157 {
2158 	if (sfp->sm_mod_state > SFP_MOD_WAITDEV)
2159 		sfp_module_remove(sfp->sfp_bus);
2160 
2161 	sfp_hwmon_remove(sfp);
2162 
2163 	memset(&sfp->id, 0, sizeof(sfp->id));
2164 	sfp->module_power_mW = 0;
2165 	sfp->have_a2 = false;
2166 
2167 	dev_info(sfp->dev, "module removed\n");
2168 }
2169 
2170 /* This state machine tracks the upstream's state */
2171 static void sfp_sm_device(struct sfp *sfp, unsigned int event)
2172 {
2173 	switch (sfp->sm_dev_state) {
2174 	default:
2175 		if (event == SFP_E_DEV_ATTACH)
2176 			sfp->sm_dev_state = SFP_DEV_DOWN;
2177 		break;
2178 
2179 	case SFP_DEV_DOWN:
2180 		if (event == SFP_E_DEV_DETACH)
2181 			sfp->sm_dev_state = SFP_DEV_DETACHED;
2182 		else if (event == SFP_E_DEV_UP)
2183 			sfp->sm_dev_state = SFP_DEV_UP;
2184 		break;
2185 
2186 	case SFP_DEV_UP:
2187 		if (event == SFP_E_DEV_DETACH)
2188 			sfp->sm_dev_state = SFP_DEV_DETACHED;
2189 		else if (event == SFP_E_DEV_DOWN)
2190 			sfp->sm_dev_state = SFP_DEV_DOWN;
2191 		break;
2192 	}
2193 }
2194 
2195 /* This state machine tracks the insert/remove state of the module, probes
2196  * the on-board EEPROM, and sets up the power level.
2197  */
2198 static void sfp_sm_module(struct sfp *sfp, unsigned int event)
2199 {
2200 	int err;
2201 
2202 	/* Handle remove event globally, it resets this state machine */
2203 	if (event == SFP_E_REMOVE) {
2204 		if (sfp->sm_mod_state > SFP_MOD_PROBE)
2205 			sfp_sm_mod_remove(sfp);
2206 		sfp_sm_mod_next(sfp, SFP_MOD_EMPTY, 0);
2207 		return;
2208 	}
2209 
2210 	/* Handle device detach globally */
2211 	if (sfp->sm_dev_state < SFP_DEV_DOWN &&
2212 	    sfp->sm_mod_state > SFP_MOD_WAITDEV) {
2213 		if (sfp->module_power_mW > 1000 &&
2214 		    sfp->sm_mod_state > SFP_MOD_HPOWER)
2215 			sfp_sm_mod_hpower(sfp, false);
2216 		sfp_sm_mod_next(sfp, SFP_MOD_WAITDEV, 0);
2217 		return;
2218 	}
2219 
2220 	switch (sfp->sm_mod_state) {
2221 	default:
2222 		if (event == SFP_E_INSERT) {
2223 			sfp_sm_mod_next(sfp, SFP_MOD_PROBE, T_SERIAL);
2224 			sfp->sm_mod_tries_init = R_PROBE_RETRY_INIT;
2225 			sfp->sm_mod_tries = R_PROBE_RETRY_SLOW;
2226 		}
2227 		break;
2228 
2229 	case SFP_MOD_PROBE:
2230 		/* Wait for T_PROBE_INIT to time out */
2231 		if (event != SFP_E_TIMEOUT)
2232 			break;
2233 
2234 		err = sfp_sm_mod_probe(sfp, sfp->sm_mod_tries == 1);
2235 		if (err == -EAGAIN) {
2236 			if (sfp->sm_mod_tries_init &&
2237 			   --sfp->sm_mod_tries_init) {
2238 				sfp_sm_set_timer(sfp, T_PROBE_RETRY_INIT);
2239 				break;
2240 			} else if (sfp->sm_mod_tries && --sfp->sm_mod_tries) {
2241 				if (sfp->sm_mod_tries == R_PROBE_RETRY_SLOW - 1)
2242 					dev_warn(sfp->dev,
2243 						 "please wait, module slow to respond\n");
2244 				sfp_sm_set_timer(sfp, T_PROBE_RETRY_SLOW);
2245 				break;
2246 			}
2247 		}
2248 		if (err < 0) {
2249 			sfp_sm_mod_next(sfp, SFP_MOD_ERROR, 0);
2250 			break;
2251 		}
2252 
2253 		/* Force a poll to re-read the hardware signal state after
2254 		 * sfp_sm_mod_probe() changed state_hw_mask.
2255 		 */
2256 		mod_delayed_work(system_wq, &sfp->poll, 1);
2257 
2258 		err = sfp_hwmon_insert(sfp);
2259 		if (err)
2260 			dev_warn(sfp->dev, "hwmon probe failed: %pe\n",
2261 				 ERR_PTR(err));
2262 
2263 		sfp_sm_mod_next(sfp, SFP_MOD_WAITDEV, 0);
2264 		fallthrough;
2265 	case SFP_MOD_WAITDEV:
2266 		/* Ensure that the device is attached before proceeding */
2267 		if (sfp->sm_dev_state < SFP_DEV_DOWN)
2268 			break;
2269 
2270 		/* Report the module insertion to the upstream device */
2271 		err = sfp_module_insert(sfp->sfp_bus, &sfp->id,
2272 					sfp->quirk);
2273 		if (err < 0) {
2274 			sfp_sm_mod_next(sfp, SFP_MOD_ERROR, 0);
2275 			break;
2276 		}
2277 
2278 		/* If this is a power level 1 module, we are done */
2279 		if (sfp->module_power_mW <= 1000)
2280 			goto insert;
2281 
2282 		sfp_sm_mod_next(sfp, SFP_MOD_HPOWER, 0);
2283 		fallthrough;
2284 	case SFP_MOD_HPOWER:
2285 		/* Enable high power mode */
2286 		err = sfp_sm_mod_hpower(sfp, true);
2287 		if (err < 0) {
2288 			if (err != -EAGAIN) {
2289 				sfp_module_remove(sfp->sfp_bus);
2290 				sfp_sm_mod_next(sfp, SFP_MOD_ERROR, 0);
2291 			} else {
2292 				sfp_sm_set_timer(sfp, T_PROBE_RETRY_INIT);
2293 			}
2294 			break;
2295 		}
2296 
2297 		sfp_sm_mod_next(sfp, SFP_MOD_WAITPWR, T_HPOWER_LEVEL);
2298 		break;
2299 
2300 	case SFP_MOD_WAITPWR:
2301 		/* Wait for T_HPOWER_LEVEL to time out */
2302 		if (event != SFP_E_TIMEOUT)
2303 			break;
2304 
2305 	insert:
2306 		sfp_sm_mod_next(sfp, SFP_MOD_PRESENT, 0);
2307 		break;
2308 
2309 	case SFP_MOD_PRESENT:
2310 	case SFP_MOD_ERROR:
2311 		break;
2312 	}
2313 }
2314 
2315 static void sfp_sm_main(struct sfp *sfp, unsigned int event)
2316 {
2317 	unsigned long timeout;
2318 	int ret;
2319 
2320 	/* Some events are global */
2321 	if (sfp->sm_state != SFP_S_DOWN &&
2322 	    (sfp->sm_mod_state != SFP_MOD_PRESENT ||
2323 	     sfp->sm_dev_state != SFP_DEV_UP)) {
2324 		if (sfp->sm_state == SFP_S_LINK_UP &&
2325 		    sfp->sm_dev_state == SFP_DEV_UP)
2326 			sfp_sm_link_down(sfp);
2327 		if (sfp->sm_state > SFP_S_INIT)
2328 			sfp_module_stop(sfp->sfp_bus);
2329 		if (sfp->mod_phy)
2330 			sfp_sm_phy_detach(sfp);
2331 		if (sfp->i2c_mii)
2332 			sfp_i2c_mdiobus_destroy(sfp);
2333 		sfp_module_tx_disable(sfp);
2334 		sfp_soft_stop_poll(sfp);
2335 		sfp_sm_next(sfp, SFP_S_DOWN, 0);
2336 		return;
2337 	}
2338 
2339 	/* The main state machine */
2340 	switch (sfp->sm_state) {
2341 	case SFP_S_DOWN:
2342 		if (sfp->sm_mod_state != SFP_MOD_PRESENT ||
2343 		    sfp->sm_dev_state != SFP_DEV_UP)
2344 			break;
2345 
2346 		/* Only use the soft state bits if we have access to the A2h
2347 		 * memory, which implies that we have some level of SFF-8472
2348 		 * compliance.
2349 		 */
2350 		if (sfp->have_a2)
2351 			sfp_soft_start_poll(sfp);
2352 
2353 		sfp_module_tx_enable(sfp);
2354 
2355 		/* Initialise the fault clearance retries */
2356 		sfp->sm_fault_retries = N_FAULT_INIT;
2357 
2358 		/* We need to check the TX_FAULT state, which is not defined
2359 		 * while TX_DISABLE is asserted. The earliest we want to do
2360 		 * anything (such as probe for a PHY) is 50ms (or more on
2361 		 * specific modules).
2362 		 */
2363 		sfp_sm_next(sfp, SFP_S_WAIT, sfp->module_t_wait);
2364 		break;
2365 
2366 	case SFP_S_WAIT:
2367 		if (event != SFP_E_TIMEOUT)
2368 			break;
2369 
2370 		if (sfp->state & SFP_F_TX_FAULT) {
2371 			/* Wait up to t_init (SFF-8472) or t_start_up (SFF-8431)
2372 			 * from the TX_DISABLE deassertion for the module to
2373 			 * initialise, which is indicated by TX_FAULT
2374 			 * deasserting.
2375 			 */
2376 			timeout = sfp->module_t_start_up;
2377 			if (timeout > sfp->module_t_wait)
2378 				timeout -= sfp->module_t_wait;
2379 			else
2380 				timeout = 1;
2381 
2382 			sfp_sm_next(sfp, SFP_S_INIT, timeout);
2383 		} else {
2384 			/* TX_FAULT is not asserted, assume the module has
2385 			 * finished initialising.
2386 			 */
2387 			goto init_done;
2388 		}
2389 		break;
2390 
2391 	case SFP_S_INIT:
2392 		if (event == SFP_E_TIMEOUT && sfp->state & SFP_F_TX_FAULT) {
2393 			/* TX_FAULT is still asserted after t_init
2394 			 * or t_start_up, so assume there is a fault.
2395 			 */
2396 			sfp_sm_fault(sfp, SFP_S_INIT_TX_FAULT,
2397 				     sfp->sm_fault_retries == N_FAULT_INIT);
2398 		} else if (event == SFP_E_TIMEOUT || event == SFP_E_TX_CLEAR) {
2399 	init_done:
2400 			/* Create mdiobus and start trying for PHY */
2401 			ret = sfp_sm_add_mdio_bus(sfp);
2402 			if (ret < 0) {
2403 				sfp_sm_next(sfp, SFP_S_FAIL, 0);
2404 				break;
2405 			}
2406 			sfp->sm_phy_retries = R_PHY_RETRY;
2407 			goto phy_probe;
2408 		}
2409 		break;
2410 
2411 	case SFP_S_INIT_PHY:
2412 		if (event != SFP_E_TIMEOUT)
2413 			break;
2414 	phy_probe:
2415 		/* TX_FAULT deasserted or we timed out with TX_FAULT
2416 		 * clear.  Probe for the PHY and check the LOS state.
2417 		 */
2418 		ret = sfp_sm_probe_for_phy(sfp);
2419 		if (ret == -ENODEV) {
2420 			if (--sfp->sm_phy_retries) {
2421 				sfp_sm_next(sfp, SFP_S_INIT_PHY, T_PHY_RETRY);
2422 				break;
2423 			} else {
2424 				dev_info(sfp->dev, "no PHY detected\n");
2425 			}
2426 		} else if (ret) {
2427 			sfp_sm_next(sfp, SFP_S_FAIL, 0);
2428 			break;
2429 		}
2430 		if (sfp_module_start(sfp->sfp_bus)) {
2431 			sfp_sm_next(sfp, SFP_S_FAIL, 0);
2432 			break;
2433 		}
2434 		sfp_sm_link_check_los(sfp);
2435 
2436 		/* Reset the fault retry count */
2437 		sfp->sm_fault_retries = N_FAULT;
2438 		break;
2439 
2440 	case SFP_S_INIT_TX_FAULT:
2441 		if (event == SFP_E_TIMEOUT) {
2442 			sfp_module_tx_fault_reset(sfp);
2443 			sfp_sm_next(sfp, SFP_S_INIT, sfp->module_t_start_up);
2444 		}
2445 		break;
2446 
2447 	case SFP_S_WAIT_LOS:
2448 		if (event == SFP_E_TX_FAULT)
2449 			sfp_sm_fault(sfp, SFP_S_TX_FAULT, true);
2450 		else if (sfp_los_event_inactive(sfp, event))
2451 			sfp_sm_link_up(sfp);
2452 		break;
2453 
2454 	case SFP_S_LINK_UP:
2455 		if (event == SFP_E_TX_FAULT) {
2456 			sfp_sm_link_down(sfp);
2457 			sfp_sm_fault(sfp, SFP_S_TX_FAULT, true);
2458 		} else if (sfp_los_event_active(sfp, event)) {
2459 			sfp_sm_link_down(sfp);
2460 			sfp_sm_next(sfp, SFP_S_WAIT_LOS, 0);
2461 		}
2462 		break;
2463 
2464 	case SFP_S_TX_FAULT:
2465 		if (event == SFP_E_TIMEOUT) {
2466 			sfp_module_tx_fault_reset(sfp);
2467 			sfp_sm_next(sfp, SFP_S_REINIT, sfp->module_t_start_up);
2468 		}
2469 		break;
2470 
2471 	case SFP_S_REINIT:
2472 		if (event == SFP_E_TIMEOUT && sfp->state & SFP_F_TX_FAULT) {
2473 			sfp_sm_fault(sfp, SFP_S_TX_FAULT, false);
2474 		} else if (event == SFP_E_TIMEOUT || event == SFP_E_TX_CLEAR) {
2475 			dev_info(sfp->dev, "module transmit fault recovered\n");
2476 			sfp_sm_link_check_los(sfp);
2477 		}
2478 		break;
2479 
2480 	case SFP_S_TX_DISABLE:
2481 		break;
2482 	}
2483 }
2484 
2485 static void __sfp_sm_event(struct sfp *sfp, unsigned int event)
2486 {
2487 	dev_dbg(sfp->dev, "SM: enter %s:%s:%s event %s\n",
2488 		mod_state_to_str(sfp->sm_mod_state),
2489 		dev_state_to_str(sfp->sm_dev_state),
2490 		sm_state_to_str(sfp->sm_state),
2491 		event_to_str(event));
2492 
2493 	sfp_sm_device(sfp, event);
2494 	sfp_sm_module(sfp, event);
2495 	sfp_sm_main(sfp, event);
2496 
2497 	dev_dbg(sfp->dev, "SM: exit %s:%s:%s\n",
2498 		mod_state_to_str(sfp->sm_mod_state),
2499 		dev_state_to_str(sfp->sm_dev_state),
2500 		sm_state_to_str(sfp->sm_state));
2501 }
2502 
2503 static void sfp_sm_event(struct sfp *sfp, unsigned int event)
2504 {
2505 	mutex_lock(&sfp->sm_mutex);
2506 	__sfp_sm_event(sfp, event);
2507 	mutex_unlock(&sfp->sm_mutex);
2508 }
2509 
2510 static void sfp_attach(struct sfp *sfp)
2511 {
2512 	sfp_sm_event(sfp, SFP_E_DEV_ATTACH);
2513 }
2514 
2515 static void sfp_detach(struct sfp *sfp)
2516 {
2517 	sfp_sm_event(sfp, SFP_E_DEV_DETACH);
2518 }
2519 
2520 static void sfp_start(struct sfp *sfp)
2521 {
2522 	sfp_sm_event(sfp, SFP_E_DEV_UP);
2523 }
2524 
2525 static void sfp_stop(struct sfp *sfp)
2526 {
2527 	sfp_sm_event(sfp, SFP_E_DEV_DOWN);
2528 }
2529 
2530 static int sfp_module_info(struct sfp *sfp, struct ethtool_modinfo *modinfo)
2531 {
2532 	/* locking... and check module is present */
2533 
2534 	if (sfp->id.ext.sff8472_compliance &&
2535 	    !(sfp->id.ext.diagmon & SFP_DIAGMON_ADDRMODE)) {
2536 		modinfo->type = ETH_MODULE_SFF_8472;
2537 		modinfo->eeprom_len = ETH_MODULE_SFF_8472_LEN;
2538 	} else {
2539 		modinfo->type = ETH_MODULE_SFF_8079;
2540 		modinfo->eeprom_len = ETH_MODULE_SFF_8079_LEN;
2541 	}
2542 	return 0;
2543 }
2544 
2545 static int sfp_module_eeprom(struct sfp *sfp, struct ethtool_eeprom *ee,
2546 			     u8 *data)
2547 {
2548 	unsigned int first, last, len;
2549 	int ret;
2550 
2551 	if (!(sfp->state & SFP_F_PRESENT))
2552 		return -ENODEV;
2553 
2554 	if (ee->len == 0)
2555 		return -EINVAL;
2556 
2557 	first = ee->offset;
2558 	last = ee->offset + ee->len;
2559 	if (first < ETH_MODULE_SFF_8079_LEN) {
2560 		len = min_t(unsigned int, last, ETH_MODULE_SFF_8079_LEN);
2561 		len -= first;
2562 
2563 		ret = sfp_read(sfp, false, first, data, len);
2564 		if (ret < 0)
2565 			return ret;
2566 
2567 		first += len;
2568 		data += len;
2569 	}
2570 	if (first < ETH_MODULE_SFF_8472_LEN && last > ETH_MODULE_SFF_8079_LEN) {
2571 		len = min_t(unsigned int, last, ETH_MODULE_SFF_8472_LEN);
2572 		len -= first;
2573 		first -= ETH_MODULE_SFF_8079_LEN;
2574 
2575 		ret = sfp_read(sfp, true, first, data, len);
2576 		if (ret < 0)
2577 			return ret;
2578 	}
2579 	return 0;
2580 }
2581 
2582 static int sfp_module_eeprom_by_page(struct sfp *sfp,
2583 				     const struct ethtool_module_eeprom *page,
2584 				     struct netlink_ext_ack *extack)
2585 {
2586 	if (!(sfp->state & SFP_F_PRESENT))
2587 		return -ENODEV;
2588 
2589 	if (page->bank) {
2590 		NL_SET_ERR_MSG(extack, "Banks not supported");
2591 		return -EOPNOTSUPP;
2592 	}
2593 
2594 	if (page->page) {
2595 		NL_SET_ERR_MSG(extack, "Only page 0 supported");
2596 		return -EOPNOTSUPP;
2597 	}
2598 
2599 	if (page->i2c_address != 0x50 &&
2600 	    page->i2c_address != 0x51) {
2601 		NL_SET_ERR_MSG(extack, "Only address 0x50 and 0x51 supported");
2602 		return -EOPNOTSUPP;
2603 	}
2604 
2605 	return sfp_read(sfp, page->i2c_address == 0x51, page->offset,
2606 			page->data, page->length);
2607 };
2608 
2609 static const struct sfp_socket_ops sfp_module_ops = {
2610 	.attach = sfp_attach,
2611 	.detach = sfp_detach,
2612 	.start = sfp_start,
2613 	.stop = sfp_stop,
2614 	.module_info = sfp_module_info,
2615 	.module_eeprom = sfp_module_eeprom,
2616 	.module_eeprom_by_page = sfp_module_eeprom_by_page,
2617 };
2618 
2619 static void sfp_timeout(struct work_struct *work)
2620 {
2621 	struct sfp *sfp = container_of(work, struct sfp, timeout.work);
2622 
2623 	rtnl_lock();
2624 	sfp_sm_event(sfp, SFP_E_TIMEOUT);
2625 	rtnl_unlock();
2626 }
2627 
2628 static void sfp_check_state(struct sfp *sfp)
2629 {
2630 	unsigned int state, i, changed;
2631 
2632 	rtnl_lock();
2633 	mutex_lock(&sfp->st_mutex);
2634 	state = sfp_get_state(sfp);
2635 	changed = state ^ sfp->state;
2636 	if (sfp->tx_fault_ignore)
2637 		changed &= SFP_F_PRESENT | SFP_F_LOS;
2638 	else
2639 		changed &= SFP_F_PRESENT | SFP_F_LOS | SFP_F_TX_FAULT;
2640 
2641 	for (i = 0; i < GPIO_MAX; i++)
2642 		if (changed & BIT(i))
2643 			dev_dbg(sfp->dev, "%s %u -> %u\n", gpio_names[i],
2644 				!!(sfp->state & BIT(i)), !!(state & BIT(i)));
2645 
2646 	state |= sfp->state & (SFP_F_TX_DISABLE | SFP_F_RATE_SELECT);
2647 	sfp->state = state;
2648 	mutex_unlock(&sfp->st_mutex);
2649 
2650 	mutex_lock(&sfp->sm_mutex);
2651 	if (changed & SFP_F_PRESENT)
2652 		__sfp_sm_event(sfp, state & SFP_F_PRESENT ?
2653 				    SFP_E_INSERT : SFP_E_REMOVE);
2654 
2655 	if (changed & SFP_F_TX_FAULT)
2656 		__sfp_sm_event(sfp, state & SFP_F_TX_FAULT ?
2657 				    SFP_E_TX_FAULT : SFP_E_TX_CLEAR);
2658 
2659 	if (changed & SFP_F_LOS)
2660 		__sfp_sm_event(sfp, state & SFP_F_LOS ?
2661 				    SFP_E_LOS_HIGH : SFP_E_LOS_LOW);
2662 	mutex_unlock(&sfp->sm_mutex);
2663 	rtnl_unlock();
2664 }
2665 
2666 static irqreturn_t sfp_irq(int irq, void *data)
2667 {
2668 	struct sfp *sfp = data;
2669 
2670 	sfp_check_state(sfp);
2671 
2672 	return IRQ_HANDLED;
2673 }
2674 
2675 static void sfp_poll(struct work_struct *work)
2676 {
2677 	struct sfp *sfp = container_of(work, struct sfp, poll.work);
2678 
2679 	sfp_check_state(sfp);
2680 
2681 	// st_mutex doesn't need to be held here for state_soft_mask,
2682 	// it's unimportant if we race while reading this.
2683 	if (sfp->state_soft_mask & (SFP_F_LOS | SFP_F_TX_FAULT) ||
2684 	    sfp->need_poll)
2685 		mod_delayed_work(system_wq, &sfp->poll, poll_jiffies);
2686 }
2687 
2688 static struct sfp *sfp_alloc(struct device *dev)
2689 {
2690 	struct sfp *sfp;
2691 
2692 	sfp = kzalloc(sizeof(*sfp), GFP_KERNEL);
2693 	if (!sfp)
2694 		return ERR_PTR(-ENOMEM);
2695 
2696 	sfp->dev = dev;
2697 	sfp->i2c_block_size = SFP_EEPROM_BLOCK_SIZE;
2698 
2699 	mutex_init(&sfp->sm_mutex);
2700 	mutex_init(&sfp->st_mutex);
2701 	INIT_DELAYED_WORK(&sfp->poll, sfp_poll);
2702 	INIT_DELAYED_WORK(&sfp->timeout, sfp_timeout);
2703 
2704 	sfp_hwmon_init(sfp);
2705 
2706 	return sfp;
2707 }
2708 
2709 static void sfp_cleanup(void *data)
2710 {
2711 	struct sfp *sfp = data;
2712 
2713 	sfp_hwmon_exit(sfp);
2714 
2715 	cancel_delayed_work_sync(&sfp->poll);
2716 	cancel_delayed_work_sync(&sfp->timeout);
2717 	if (sfp->i2c_mii) {
2718 		mdiobus_unregister(sfp->i2c_mii);
2719 		mdiobus_free(sfp->i2c_mii);
2720 	}
2721 	if (sfp->i2c)
2722 		i2c_put_adapter(sfp->i2c);
2723 	kfree(sfp);
2724 }
2725 
2726 static int sfp_i2c_get(struct sfp *sfp)
2727 {
2728 	struct fwnode_handle *h;
2729 	struct i2c_adapter *i2c;
2730 	int err;
2731 
2732 	h = fwnode_find_reference(dev_fwnode(sfp->dev), "i2c-bus", 0);
2733 	if (IS_ERR(h)) {
2734 		dev_err(sfp->dev, "missing 'i2c-bus' property\n");
2735 		return -ENODEV;
2736 	}
2737 
2738 	i2c = i2c_get_adapter_by_fwnode(h);
2739 	if (!i2c) {
2740 		err = -EPROBE_DEFER;
2741 		goto put;
2742 	}
2743 
2744 	err = sfp_i2c_configure(sfp, i2c);
2745 	if (err)
2746 		i2c_put_adapter(i2c);
2747 put:
2748 	fwnode_handle_put(h);
2749 	return err;
2750 }
2751 
2752 static int sfp_probe(struct platform_device *pdev)
2753 {
2754 	const struct sff_data *sff;
2755 	char *sfp_irq_name;
2756 	struct sfp *sfp;
2757 	int err, i;
2758 
2759 	sfp = sfp_alloc(&pdev->dev);
2760 	if (IS_ERR(sfp))
2761 		return PTR_ERR(sfp);
2762 
2763 	platform_set_drvdata(pdev, sfp);
2764 
2765 	err = devm_add_action_or_reset(sfp->dev, sfp_cleanup, sfp);
2766 	if (err < 0)
2767 		return err;
2768 
2769 	sff = device_get_match_data(sfp->dev);
2770 	if (!sff)
2771 		sff = &sfp_data;
2772 
2773 	sfp->type = sff;
2774 
2775 	err = sfp_i2c_get(sfp);
2776 	if (err)
2777 		return err;
2778 
2779 	for (i = 0; i < GPIO_MAX; i++)
2780 		if (sff->gpios & BIT(i)) {
2781 			sfp->gpio[i] = devm_gpiod_get_optional(sfp->dev,
2782 					   gpio_names[i], gpio_flags[i]);
2783 			if (IS_ERR(sfp->gpio[i]))
2784 				return PTR_ERR(sfp->gpio[i]);
2785 		}
2786 
2787 	sfp->state_hw_mask = SFP_F_PRESENT;
2788 
2789 	sfp->get_state = sfp_gpio_get_state;
2790 	sfp->set_state = sfp_gpio_set_state;
2791 
2792 	/* Modules that have no detect signal are always present */
2793 	if (!(sfp->gpio[GPIO_MODDEF0]))
2794 		sfp->get_state = sff_gpio_get_state;
2795 
2796 	device_property_read_u32(&pdev->dev, "maximum-power-milliwatt",
2797 				 &sfp->max_power_mW);
2798 	if (sfp->max_power_mW < 1000) {
2799 		if (sfp->max_power_mW)
2800 			dev_warn(sfp->dev,
2801 				 "Firmware bug: host maximum power should be at least 1W\n");
2802 		sfp->max_power_mW = 1000;
2803 	}
2804 
2805 	dev_info(sfp->dev, "Host maximum power %u.%uW\n",
2806 		 sfp->max_power_mW / 1000, (sfp->max_power_mW / 100) % 10);
2807 
2808 	/* Get the initial state, and always signal TX disable,
2809 	 * since the network interface will not be up.
2810 	 */
2811 	sfp->state = sfp_get_state(sfp) | SFP_F_TX_DISABLE;
2812 
2813 	if (sfp->gpio[GPIO_RATE_SELECT] &&
2814 	    gpiod_get_value_cansleep(sfp->gpio[GPIO_RATE_SELECT]))
2815 		sfp->state |= SFP_F_RATE_SELECT;
2816 	sfp_set_state(sfp, sfp->state);
2817 	sfp_module_tx_disable(sfp);
2818 	if (sfp->state & SFP_F_PRESENT) {
2819 		rtnl_lock();
2820 		sfp_sm_event(sfp, SFP_E_INSERT);
2821 		rtnl_unlock();
2822 	}
2823 
2824 	for (i = 0; i < GPIO_MAX; i++) {
2825 		if (gpio_flags[i] != GPIOD_IN || !sfp->gpio[i])
2826 			continue;
2827 
2828 		sfp->gpio_irq[i] = gpiod_to_irq(sfp->gpio[i]);
2829 		if (sfp->gpio_irq[i] < 0) {
2830 			sfp->gpio_irq[i] = 0;
2831 			sfp->need_poll = true;
2832 			continue;
2833 		}
2834 
2835 		sfp_irq_name = devm_kasprintf(sfp->dev, GFP_KERNEL,
2836 					      "%s-%s", dev_name(sfp->dev),
2837 					      gpio_names[i]);
2838 
2839 		if (!sfp_irq_name)
2840 			return -ENOMEM;
2841 
2842 		err = devm_request_threaded_irq(sfp->dev, sfp->gpio_irq[i],
2843 						NULL, sfp_irq,
2844 						IRQF_ONESHOT |
2845 						IRQF_TRIGGER_RISING |
2846 						IRQF_TRIGGER_FALLING,
2847 						sfp_irq_name, sfp);
2848 		if (err) {
2849 			sfp->gpio_irq[i] = 0;
2850 			sfp->need_poll = true;
2851 		}
2852 	}
2853 
2854 	if (sfp->need_poll)
2855 		mod_delayed_work(system_wq, &sfp->poll, poll_jiffies);
2856 
2857 	/* We could have an issue in cases no Tx disable pin is available or
2858 	 * wired as modules using a laser as their light source will continue to
2859 	 * be active when the fiber is removed. This could be a safety issue and
2860 	 * we should at least warn the user about that.
2861 	 */
2862 	if (!sfp->gpio[GPIO_TX_DISABLE])
2863 		dev_warn(sfp->dev,
2864 			 "No tx_disable pin: SFP modules will always be emitting.\n");
2865 
2866 	sfp->sfp_bus = sfp_register_socket(sfp->dev, sfp, &sfp_module_ops);
2867 	if (!sfp->sfp_bus)
2868 		return -ENOMEM;
2869 
2870 	sfp_debugfs_init(sfp);
2871 
2872 	return 0;
2873 }
2874 
2875 static int sfp_remove(struct platform_device *pdev)
2876 {
2877 	struct sfp *sfp = platform_get_drvdata(pdev);
2878 
2879 	sfp_debugfs_exit(sfp);
2880 	sfp_unregister_socket(sfp->sfp_bus);
2881 
2882 	rtnl_lock();
2883 	sfp_sm_event(sfp, SFP_E_REMOVE);
2884 	rtnl_unlock();
2885 
2886 	return 0;
2887 }
2888 
2889 static void sfp_shutdown(struct platform_device *pdev)
2890 {
2891 	struct sfp *sfp = platform_get_drvdata(pdev);
2892 	int i;
2893 
2894 	for (i = 0; i < GPIO_MAX; i++) {
2895 		if (!sfp->gpio_irq[i])
2896 			continue;
2897 
2898 		devm_free_irq(sfp->dev, sfp->gpio_irq[i], sfp);
2899 	}
2900 
2901 	cancel_delayed_work_sync(&sfp->poll);
2902 	cancel_delayed_work_sync(&sfp->timeout);
2903 }
2904 
2905 static struct platform_driver sfp_driver = {
2906 	.probe = sfp_probe,
2907 	.remove = sfp_remove,
2908 	.shutdown = sfp_shutdown,
2909 	.driver = {
2910 		.name = "sfp",
2911 		.of_match_table = sfp_of_match,
2912 	},
2913 };
2914 
2915 static int sfp_init(void)
2916 {
2917 	poll_jiffies = msecs_to_jiffies(100);
2918 
2919 	return platform_driver_register(&sfp_driver);
2920 }
2921 module_init(sfp_init);
2922 
2923 static void sfp_exit(void)
2924 {
2925 	platform_driver_unregister(&sfp_driver);
2926 }
2927 module_exit(sfp_exit);
2928 
2929 MODULE_ALIAS("platform:sfp");
2930 MODULE_AUTHOR("Russell King");
2931 MODULE_LICENSE("GPL v2");
2932