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