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