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