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