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