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