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