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