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