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