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