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