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