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