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