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