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