phy: add proper phy struct device refcounting
[firefly-linux-kernel-4.4.55.git] / drivers / net / phy / phy_device.c
1 /* Framework for finding and configuring PHYs.
2  * Also contains generic PHY driver
3  *
4  * Author: Andy Fleming
5  *
6  * Copyright (c) 2004 Freescale Semiconductor, Inc.
7  *
8  * This program is free software; you can redistribute  it and/or modify it
9  * under  the terms of  the GNU General  Public License as published by the
10  * Free Software Foundation;  either version 2 of the  License, or (at your
11  * option) any later version.
12  *
13  */
14
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16
17 #include <linux/kernel.h>
18 #include <linux/string.h>
19 #include <linux/errno.h>
20 #include <linux/unistd.h>
21 #include <linux/slab.h>
22 #include <linux/interrupt.h>
23 #include <linux/init.h>
24 #include <linux/delay.h>
25 #include <linux/netdevice.h>
26 #include <linux/etherdevice.h>
27 #include <linux/skbuff.h>
28 #include <linux/mm.h>
29 #include <linux/module.h>
30 #include <linux/mii.h>
31 #include <linux/ethtool.h>
32 #include <linux/phy.h>
33 #include <linux/mdio.h>
34 #include <linux/io.h>
35 #include <linux/uaccess.h>
36 #include <linux/of.h>
37
38 #include <asm/irq.h>
39
40 MODULE_DESCRIPTION("PHY library");
41 MODULE_AUTHOR("Andy Fleming");
42 MODULE_LICENSE("GPL");
43
44 void phy_device_free(struct phy_device *phydev)
45 {
46         put_device(&phydev->dev);
47 }
48 EXPORT_SYMBOL(phy_device_free);
49
50 static void phy_device_release(struct device *dev)
51 {
52         kfree(to_phy_device(dev));
53 }
54
55 enum genphy_driver {
56         GENPHY_DRV_1G,
57         GENPHY_DRV_10G,
58         GENPHY_DRV_MAX
59 };
60
61 static struct phy_driver genphy_driver[GENPHY_DRV_MAX];
62
63 static LIST_HEAD(phy_fixup_list);
64 static DEFINE_MUTEX(phy_fixup_lock);
65
66 /**
67  * phy_register_fixup - creates a new phy_fixup and adds it to the list
68  * @bus_id: A string which matches phydev->dev.bus_id (or PHY_ANY_ID)
69  * @phy_uid: Used to match against phydev->phy_id (the UID of the PHY)
70  *      It can also be PHY_ANY_UID
71  * @phy_uid_mask: Applied to phydev->phy_id and fixup->phy_uid before
72  *      comparison
73  * @run: The actual code to be run when a matching PHY is found
74  */
75 int phy_register_fixup(const char *bus_id, u32 phy_uid, u32 phy_uid_mask,
76                        int (*run)(struct phy_device *))
77 {
78         struct phy_fixup *fixup = kzalloc(sizeof(*fixup), GFP_KERNEL);
79
80         if (!fixup)
81                 return -ENOMEM;
82
83         strlcpy(fixup->bus_id, bus_id, sizeof(fixup->bus_id));
84         fixup->phy_uid = phy_uid;
85         fixup->phy_uid_mask = phy_uid_mask;
86         fixup->run = run;
87
88         mutex_lock(&phy_fixup_lock);
89         list_add_tail(&fixup->list, &phy_fixup_list);
90         mutex_unlock(&phy_fixup_lock);
91
92         return 0;
93 }
94 EXPORT_SYMBOL(phy_register_fixup);
95
96 /* Registers a fixup to be run on any PHY with the UID in phy_uid */
97 int phy_register_fixup_for_uid(u32 phy_uid, u32 phy_uid_mask,
98                                int (*run)(struct phy_device *))
99 {
100         return phy_register_fixup(PHY_ANY_ID, phy_uid, phy_uid_mask, run);
101 }
102 EXPORT_SYMBOL(phy_register_fixup_for_uid);
103
104 /* Registers a fixup to be run on the PHY with id string bus_id */
105 int phy_register_fixup_for_id(const char *bus_id,
106                               int (*run)(struct phy_device *))
107 {
108         return phy_register_fixup(bus_id, PHY_ANY_UID, 0xffffffff, run);
109 }
110 EXPORT_SYMBOL(phy_register_fixup_for_id);
111
112 /* Returns 1 if fixup matches phydev in bus_id and phy_uid.
113  * Fixups can be set to match any in one or more fields.
114  */
115 static int phy_needs_fixup(struct phy_device *phydev, struct phy_fixup *fixup)
116 {
117         if (strcmp(fixup->bus_id, dev_name(&phydev->dev)) != 0)
118                 if (strcmp(fixup->bus_id, PHY_ANY_ID) != 0)
119                         return 0;
120
121         if ((fixup->phy_uid & fixup->phy_uid_mask) !=
122             (phydev->phy_id & fixup->phy_uid_mask))
123                 if (fixup->phy_uid != PHY_ANY_UID)
124                         return 0;
125
126         return 1;
127 }
128
129 /* Runs any matching fixups for this phydev */
130 static int phy_scan_fixups(struct phy_device *phydev)
131 {
132         struct phy_fixup *fixup;
133
134         mutex_lock(&phy_fixup_lock);
135         list_for_each_entry(fixup, &phy_fixup_list, list) {
136                 if (phy_needs_fixup(phydev, fixup)) {
137                         int err = fixup->run(phydev);
138
139                         if (err < 0) {
140                                 mutex_unlock(&phy_fixup_lock);
141                                 return err;
142                         }
143                         phydev->has_fixups = true;
144                 }
145         }
146         mutex_unlock(&phy_fixup_lock);
147
148         return 0;
149 }
150
151 struct phy_device *phy_device_create(struct mii_bus *bus, int addr, int phy_id,
152                                      bool is_c45,
153                                      struct phy_c45_device_ids *c45_ids)
154 {
155         struct phy_device *dev;
156
157         /* We allocate the device, and initialize the default values */
158         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
159         if (!dev)
160                 return ERR_PTR(-ENOMEM);
161
162         dev->dev.release = phy_device_release;
163
164         dev->speed = 0;
165         dev->duplex = -1;
166         dev->pause = 0;
167         dev->asym_pause = 0;
168         dev->link = 1;
169         dev->interface = PHY_INTERFACE_MODE_GMII;
170
171         dev->autoneg = AUTONEG_ENABLE;
172
173         dev->is_c45 = is_c45;
174         dev->addr = addr;
175         dev->phy_id = phy_id;
176         if (c45_ids)
177                 dev->c45_ids = *c45_ids;
178         dev->bus = bus;
179         dev->dev.parent = &bus->dev;
180         dev->dev.bus = &mdio_bus_type;
181         dev->irq = bus->irq ? bus->irq[addr] : PHY_POLL;
182         dev_set_name(&dev->dev, PHY_ID_FMT, bus->id, addr);
183
184         dev->state = PHY_DOWN;
185
186         mutex_init(&dev->lock);
187         INIT_DELAYED_WORK(&dev->state_queue, phy_state_machine);
188         INIT_WORK(&dev->phy_queue, phy_change);
189
190         /* Request the appropriate module unconditionally; don't
191          * bother trying to do so only if it isn't already loaded,
192          * because that gets complicated. A hotplug event would have
193          * done an unconditional modprobe anyway.
194          * We don't do normal hotplug because it won't work for MDIO
195          * -- because it relies on the device staying around for long
196          * enough for the driver to get loaded. With MDIO, the NIC
197          * driver will get bored and give up as soon as it finds that
198          * there's no driver _already_ loaded.
199          */
200         request_module(MDIO_MODULE_PREFIX MDIO_ID_FMT, MDIO_ID_ARGS(phy_id));
201
202         device_initialize(&dev->dev);
203
204         return dev;
205 }
206 EXPORT_SYMBOL(phy_device_create);
207
208 /**
209  * get_phy_c45_ids - reads the specified addr for its 802.3-c45 IDs.
210  * @bus: the target MII bus
211  * @addr: PHY address on the MII bus
212  * @phy_id: where to store the ID retrieved.
213  * @c45_ids: where to store the c45 ID information.
214  *
215  *   If the PHY devices-in-package appears to be valid, it and the
216  *   corresponding identifiers are stored in @c45_ids, zero is stored
217  *   in @phy_id.  Otherwise 0xffffffff is stored in @phy_id.  Returns
218  *   zero on success.
219  *
220  */
221 static int get_phy_c45_ids(struct mii_bus *bus, int addr, u32 *phy_id,
222                            struct phy_c45_device_ids *c45_ids) {
223         int phy_reg;
224         int i, reg_addr;
225         const int num_ids = ARRAY_SIZE(c45_ids->device_ids);
226
227         /* Find first non-zero Devices In package.  Device
228          * zero is reserved, so don't probe it.
229          */
230         for (i = 1;
231              i < num_ids && c45_ids->devices_in_package == 0;
232              i++) {
233 retry:          reg_addr = MII_ADDR_C45 | i << 16 | MDIO_DEVS2;
234                 phy_reg = mdiobus_read(bus, addr, reg_addr);
235                 if (phy_reg < 0)
236                         return -EIO;
237                 c45_ids->devices_in_package = (phy_reg & 0xffff) << 16;
238
239                 reg_addr = MII_ADDR_C45 | i << 16 | MDIO_DEVS1;
240                 phy_reg = mdiobus_read(bus, addr, reg_addr);
241                 if (phy_reg < 0)
242                         return -EIO;
243                 c45_ids->devices_in_package |= (phy_reg & 0xffff);
244
245                 if ((c45_ids->devices_in_package & 0x1fffffff) == 0x1fffffff) {
246                         if (i) {
247                                 /*  If mostly Fs, there is no device there,
248                                  *  then let's continue to probe more, as some
249                                  *  10G PHYs have zero Devices In package,
250                                  *  e.g. Cortina CS4315/CS4340 PHY.
251                                  */
252                                 i = 0;
253                                 goto retry;
254                         } else {
255                                 /* no device there, let's get out of here */
256                                 *phy_id = 0xffffffff;
257                                 return 0;
258                         }
259                 }
260         }
261
262         /* Now probe Device Identifiers for each device present. */
263         for (i = 1; i < num_ids; i++) {
264                 if (!(c45_ids->devices_in_package & (1 << i)))
265                         continue;
266
267                 reg_addr = MII_ADDR_C45 | i << 16 | MII_PHYSID1;
268                 phy_reg = mdiobus_read(bus, addr, reg_addr);
269                 if (phy_reg < 0)
270                         return -EIO;
271                 c45_ids->device_ids[i] = (phy_reg & 0xffff) << 16;
272
273                 reg_addr = MII_ADDR_C45 | i << 16 | MII_PHYSID2;
274                 phy_reg = mdiobus_read(bus, addr, reg_addr);
275                 if (phy_reg < 0)
276                         return -EIO;
277                 c45_ids->device_ids[i] |= (phy_reg & 0xffff);
278         }
279         *phy_id = 0;
280         return 0;
281 }
282
283 /**
284  * get_phy_id - reads the specified addr for its ID.
285  * @bus: the target MII bus
286  * @addr: PHY address on the MII bus
287  * @phy_id: where to store the ID retrieved.
288  * @is_c45: If true the PHY uses the 802.3 clause 45 protocol
289  * @c45_ids: where to store the c45 ID information.
290  *
291  * Description: In the case of a 802.3-c22 PHY, reads the ID registers
292  *   of the PHY at @addr on the @bus, stores it in @phy_id and returns
293  *   zero on success.
294  *
295  *   In the case of a 802.3-c45 PHY, get_phy_c45_ids() is invoked, and
296  *   its return value is in turn returned.
297  *
298  */
299 static int get_phy_id(struct mii_bus *bus, int addr, u32 *phy_id,
300                       bool is_c45, struct phy_c45_device_ids *c45_ids)
301 {
302         int phy_reg;
303
304         if (is_c45)
305                 return get_phy_c45_ids(bus, addr, phy_id, c45_ids);
306
307         /* Grab the bits from PHYIR1, and put them in the upper half */
308         phy_reg = mdiobus_read(bus, addr, MII_PHYSID1);
309         if (phy_reg < 0)
310                 return -EIO;
311
312         *phy_id = (phy_reg & 0xffff) << 16;
313
314         /* Grab the bits from PHYIR2, and put them in the lower half */
315         phy_reg = mdiobus_read(bus, addr, MII_PHYSID2);
316         if (phy_reg < 0)
317                 return -EIO;
318
319         *phy_id |= (phy_reg & 0xffff);
320
321         return 0;
322 }
323
324 /**
325  * get_phy_device - reads the specified PHY device and returns its @phy_device
326  *                  struct
327  * @bus: the target MII bus
328  * @addr: PHY address on the MII bus
329  * @is_c45: If true the PHY uses the 802.3 clause 45 protocol
330  *
331  * Description: Reads the ID registers of the PHY at @addr on the
332  *   @bus, then allocates and returns the phy_device to represent it.
333  */
334 struct phy_device *get_phy_device(struct mii_bus *bus, int addr, bool is_c45)
335 {
336         struct phy_c45_device_ids c45_ids = {0};
337         u32 phy_id = 0;
338         int r;
339
340         r = get_phy_id(bus, addr, &phy_id, is_c45, &c45_ids);
341         if (r)
342                 return ERR_PTR(r);
343
344         /* If the phy_id is mostly Fs, there is no device there */
345         if ((phy_id & 0x1fffffff) == 0x1fffffff)
346                 return NULL;
347
348         return phy_device_create(bus, addr, phy_id, is_c45, &c45_ids);
349 }
350 EXPORT_SYMBOL(get_phy_device);
351
352 /**
353  * phy_device_register - Register the phy device on the MDIO bus
354  * @phydev: phy_device structure to be added to the MDIO bus
355  */
356 int phy_device_register(struct phy_device *phydev)
357 {
358         int err;
359
360         /* Don't register a phy if one is already registered at this address */
361         if (phydev->bus->phy_map[phydev->addr])
362                 return -EINVAL;
363         phydev->bus->phy_map[phydev->addr] = phydev;
364
365         /* Run all of the fixups for this PHY */
366         err = phy_scan_fixups(phydev);
367         if (err) {
368                 pr_err("PHY %d failed to initialize\n", phydev->addr);
369                 goto out;
370         }
371
372         err = device_add(&phydev->dev);
373         if (err) {
374                 pr_err("PHY %d failed to add\n", phydev->addr);
375                 goto out;
376         }
377
378         return 0;
379
380  out:
381         phydev->bus->phy_map[phydev->addr] = NULL;
382         return err;
383 }
384 EXPORT_SYMBOL(phy_device_register);
385
386 /**
387  * phy_find_first - finds the first PHY device on the bus
388  * @bus: the target MII bus
389  */
390 struct phy_device *phy_find_first(struct mii_bus *bus)
391 {
392         int addr;
393
394         for (addr = 0; addr < PHY_MAX_ADDR; addr++) {
395                 if (bus->phy_map[addr])
396                         return bus->phy_map[addr];
397         }
398         return NULL;
399 }
400 EXPORT_SYMBOL(phy_find_first);
401
402 /**
403  * phy_prepare_link - prepares the PHY layer to monitor link status
404  * @phydev: target phy_device struct
405  * @handler: callback function for link status change notifications
406  *
407  * Description: Tells the PHY infrastructure to handle the
408  *   gory details on monitoring link status (whether through
409  *   polling or an interrupt), and to call back to the
410  *   connected device driver when the link status changes.
411  *   If you want to monitor your own link state, don't call
412  *   this function.
413  */
414 static void phy_prepare_link(struct phy_device *phydev,
415                              void (*handler)(struct net_device *))
416 {
417         phydev->adjust_link = handler;
418 }
419
420 /**
421  * phy_connect_direct - connect an ethernet device to a specific phy_device
422  * @dev: the network device to connect
423  * @phydev: the pointer to the phy device
424  * @handler: callback function for state change notifications
425  * @interface: PHY device's interface
426  */
427 int phy_connect_direct(struct net_device *dev, struct phy_device *phydev,
428                        void (*handler)(struct net_device *),
429                        phy_interface_t interface)
430 {
431         int rc;
432
433         rc = phy_attach_direct(dev, phydev, phydev->dev_flags, interface);
434         if (rc)
435                 return rc;
436
437         phy_prepare_link(phydev, handler);
438         phy_start_machine(phydev);
439         if (phydev->irq > 0)
440                 phy_start_interrupts(phydev);
441
442         return 0;
443 }
444 EXPORT_SYMBOL(phy_connect_direct);
445
446 /**
447  * phy_connect - connect an ethernet device to a PHY device
448  * @dev: the network device to connect
449  * @bus_id: the id string of the PHY device to connect
450  * @handler: callback function for state change notifications
451  * @interface: PHY device's interface
452  *
453  * Description: Convenience function for connecting ethernet
454  *   devices to PHY devices.  The default behavior is for
455  *   the PHY infrastructure to handle everything, and only notify
456  *   the connected driver when the link status changes.  If you
457  *   don't want, or can't use the provided functionality, you may
458  *   choose to call only the subset of functions which provide
459  *   the desired functionality.
460  */
461 struct phy_device *phy_connect(struct net_device *dev, const char *bus_id,
462                                void (*handler)(struct net_device *),
463                                phy_interface_t interface)
464 {
465         struct phy_device *phydev;
466         struct device *d;
467         int rc;
468
469         /* Search the list of PHY devices on the mdio bus for the
470          * PHY with the requested name
471          */
472         d = bus_find_device_by_name(&mdio_bus_type, NULL, bus_id);
473         if (!d) {
474                 pr_err("PHY %s not found\n", bus_id);
475                 return ERR_PTR(-ENODEV);
476         }
477         phydev = to_phy_device(d);
478
479         rc = phy_connect_direct(dev, phydev, handler, interface);
480         if (rc)
481                 return ERR_PTR(rc);
482
483         return phydev;
484 }
485 EXPORT_SYMBOL(phy_connect);
486
487 /**
488  * phy_disconnect - disable interrupts, stop state machine, and detach a PHY
489  *                  device
490  * @phydev: target phy_device struct
491  */
492 void phy_disconnect(struct phy_device *phydev)
493 {
494         if (phydev->irq > 0)
495                 phy_stop_interrupts(phydev);
496
497         phy_stop_machine(phydev);
498
499         phydev->adjust_link = NULL;
500
501         phy_detach(phydev);
502 }
503 EXPORT_SYMBOL(phy_disconnect);
504
505 /**
506  * phy_poll_reset - Safely wait until a PHY reset has properly completed
507  * @phydev: The PHY device to poll
508  *
509  * Description: According to IEEE 802.3, Section 2, Subsection 22.2.4.1.1, as
510  *   published in 2008, a PHY reset may take up to 0.5 seconds.  The MII BMCR
511  *   register must be polled until the BMCR_RESET bit clears.
512  *
513  *   Furthermore, any attempts to write to PHY registers may have no effect
514  *   or even generate MDIO bus errors until this is complete.
515  *
516  *   Some PHYs (such as the Marvell 88E1111) don't entirely conform to the
517  *   standard and do not fully reset after the BMCR_RESET bit is set, and may
518  *   even *REQUIRE* a soft-reset to properly restart autonegotiation.  In an
519  *   effort to support such broken PHYs, this function is separate from the
520  *   standard phy_init_hw() which will zero all the other bits in the BMCR
521  *   and reapply all driver-specific and board-specific fixups.
522  */
523 static int phy_poll_reset(struct phy_device *phydev)
524 {
525         /* Poll until the reset bit clears (50ms per retry == 0.6 sec) */
526         unsigned int retries = 12;
527         int ret;
528
529         do {
530                 msleep(50);
531                 ret = phy_read(phydev, MII_BMCR);
532                 if (ret < 0)
533                         return ret;
534         } while (ret & BMCR_RESET && --retries);
535         if (ret & BMCR_RESET)
536                 return -ETIMEDOUT;
537
538         /* Some chips (smsc911x) may still need up to another 1ms after the
539          * BMCR_RESET bit is cleared before they are usable.
540          */
541         msleep(1);
542         return 0;
543 }
544
545 int phy_init_hw(struct phy_device *phydev)
546 {
547         int ret = 0;
548
549         if (!phydev->drv || !phydev->drv->config_init)
550                 return 0;
551
552         if (phydev->drv->soft_reset)
553                 ret = phydev->drv->soft_reset(phydev);
554         else
555                 ret = genphy_soft_reset(phydev);
556
557         if (ret < 0)
558                 return ret;
559
560         ret = phy_scan_fixups(phydev);
561         if (ret < 0)
562                 return ret;
563
564         return phydev->drv->config_init(phydev);
565 }
566 EXPORT_SYMBOL(phy_init_hw);
567
568 /**
569  * phy_attach_direct - attach a network device to a given PHY device pointer
570  * @dev: network device to attach
571  * @phydev: Pointer to phy_device to attach
572  * @flags: PHY device's dev_flags
573  * @interface: PHY device's interface
574  *
575  * Description: Called by drivers to attach to a particular PHY
576  *     device. The phy_device is found, and properly hooked up
577  *     to the phy_driver.  If no driver is attached, then a
578  *     generic driver is used.  The phy_device is given a ptr to
579  *     the attaching device, and given a callback for link status
580  *     change.  The phy_device is returned to the attaching driver.
581  *     This function takes a reference on the phy device.
582  */
583 int phy_attach_direct(struct net_device *dev, struct phy_device *phydev,
584                       u32 flags, phy_interface_t interface)
585 {
586         struct mii_bus *bus = phydev->bus;
587         struct device *d = &phydev->dev;
588         int err;
589
590         if (!try_module_get(bus->owner)) {
591                 dev_err(&dev->dev, "failed to get the bus module\n");
592                 return -EIO;
593         }
594
595         get_device(d);
596
597         /* Assume that if there is no driver, that it doesn't
598          * exist, and we should use the genphy driver.
599          */
600         if (!d->driver) {
601                 if (phydev->is_c45)
602                         d->driver = &genphy_driver[GENPHY_DRV_10G].driver;
603                 else
604                         d->driver = &genphy_driver[GENPHY_DRV_1G].driver;
605
606                 err = d->driver->probe(d);
607                 if (err >= 0)
608                         err = device_bind_driver(d);
609
610                 if (err)
611                         goto error;
612         }
613
614         if (phydev->attached_dev) {
615                 dev_err(&dev->dev, "PHY already attached\n");
616                 err = -EBUSY;
617                 goto error;
618         }
619
620         phydev->attached_dev = dev;
621         dev->phydev = phydev;
622
623         phydev->dev_flags = flags;
624
625         phydev->interface = interface;
626
627         phydev->state = PHY_READY;
628
629         /* Do initial configuration here, now that
630          * we have certain key parameters
631          * (dev_flags and interface)
632          */
633         err = phy_init_hw(phydev);
634         if (err)
635                 phy_detach(phydev);
636         else
637                 phy_resume(phydev);
638
639         return err;
640
641 error:
642         put_device(d);
643         module_put(bus->owner);
644         return err;
645 }
646 EXPORT_SYMBOL(phy_attach_direct);
647
648 /**
649  * phy_attach - attach a network device to a particular PHY device
650  * @dev: network device to attach
651  * @bus_id: Bus ID of PHY device to attach
652  * @interface: PHY device's interface
653  *
654  * Description: Same as phy_attach_direct() except that a PHY bus_id
655  *     string is passed instead of a pointer to a struct phy_device.
656  */
657 struct phy_device *phy_attach(struct net_device *dev, const char *bus_id,
658                               phy_interface_t interface)
659 {
660         struct bus_type *bus = &mdio_bus_type;
661         struct phy_device *phydev;
662         struct device *d;
663         int rc;
664
665         /* Search the list of PHY devices on the mdio bus for the
666          * PHY with the requested name
667          */
668         d = bus_find_device_by_name(bus, NULL, bus_id);
669         if (!d) {
670                 pr_err("PHY %s not found\n", bus_id);
671                 return ERR_PTR(-ENODEV);
672         }
673         phydev = to_phy_device(d);
674
675         rc = phy_attach_direct(dev, phydev, phydev->dev_flags, interface);
676         if (rc)
677                 return ERR_PTR(rc);
678
679         return phydev;
680 }
681 EXPORT_SYMBOL(phy_attach);
682
683 /**
684  * phy_detach - detach a PHY device from its network device
685  * @phydev: target phy_device struct
686  *
687  * This detaches the phy device from its network device and the phy
688  * driver, and drops the reference count taken in phy_attach_direct().
689  */
690 void phy_detach(struct phy_device *phydev)
691 {
692         struct mii_bus *bus;
693         int i;
694
695         phydev->attached_dev->phydev = NULL;
696         phydev->attached_dev = NULL;
697         phy_suspend(phydev);
698
699         /* If the device had no specific driver before (i.e. - it
700          * was using the generic driver), we unbind the device
701          * from the generic driver so that there's a chance a
702          * real driver could be loaded
703          */
704         for (i = 0; i < ARRAY_SIZE(genphy_driver); i++) {
705                 if (phydev->dev.driver == &genphy_driver[i].driver) {
706                         device_release_driver(&phydev->dev);
707                         break;
708                 }
709         }
710
711         /*
712          * The phydev might go away on the put_device() below, so avoid
713          * a use-after-free bug by reading the underlying bus first.
714          */
715         bus = phydev->bus;
716
717         put_device(&phydev->dev);
718         module_put(bus->owner);
719 }
720 EXPORT_SYMBOL(phy_detach);
721
722 int phy_suspend(struct phy_device *phydev)
723 {
724         struct phy_driver *phydrv = to_phy_driver(phydev->dev.driver);
725         struct ethtool_wolinfo wol = { .cmd = ETHTOOL_GWOL };
726         int ret = 0;
727
728         /* If the device has WOL enabled, we cannot suspend the PHY */
729         phy_ethtool_get_wol(phydev, &wol);
730         if (wol.wolopts)
731                 return -EBUSY;
732
733         if (phydrv->suspend)
734                 ret = phydrv->suspend(phydev);
735
736         if (ret)
737                 return ret;
738
739         phydev->suspended = true;
740
741         return ret;
742 }
743 EXPORT_SYMBOL(phy_suspend);
744
745 int phy_resume(struct phy_device *phydev)
746 {
747         struct phy_driver *phydrv = to_phy_driver(phydev->dev.driver);
748         int ret = 0;
749
750         if (phydrv->resume)
751                 ret = phydrv->resume(phydev);
752
753         if (ret)
754                 return ret;
755
756         phydev->suspended = false;
757
758         return ret;
759 }
760 EXPORT_SYMBOL(phy_resume);
761
762 /* Generic PHY support and helper functions */
763
764 /**
765  * genphy_config_advert - sanitize and advertise auto-negotiation parameters
766  * @phydev: target phy_device struct
767  *
768  * Description: Writes MII_ADVERTISE with the appropriate values,
769  *   after sanitizing the values to make sure we only advertise
770  *   what is supported.  Returns < 0 on error, 0 if the PHY's advertisement
771  *   hasn't changed, and > 0 if it has changed.
772  */
773 static int genphy_config_advert(struct phy_device *phydev)
774 {
775         u32 advertise;
776         int oldadv, adv, bmsr;
777         int err, changed = 0;
778
779         /* Only allow advertising what this PHY supports */
780         phydev->advertising &= phydev->supported;
781         advertise = phydev->advertising;
782
783         /* Setup standard advertisement */
784         adv = phy_read(phydev, MII_ADVERTISE);
785         if (adv < 0)
786                 return adv;
787
788         oldadv = adv;
789         adv &= ~(ADVERTISE_ALL | ADVERTISE_100BASE4 | ADVERTISE_PAUSE_CAP |
790                  ADVERTISE_PAUSE_ASYM);
791         adv |= ethtool_adv_to_mii_adv_t(advertise);
792
793         if (adv != oldadv) {
794                 err = phy_write(phydev, MII_ADVERTISE, adv);
795
796                 if (err < 0)
797                         return err;
798                 changed = 1;
799         }
800
801         bmsr = phy_read(phydev, MII_BMSR);
802         if (bmsr < 0)
803                 return bmsr;
804
805         /* Per 802.3-2008, Section 22.2.4.2.16 Extended status all
806          * 1000Mbits/sec capable PHYs shall have the BMSR_ESTATEN bit set to a
807          * logical 1.
808          */
809         if (!(bmsr & BMSR_ESTATEN))
810                 return changed;
811
812         /* Configure gigabit if it's supported */
813         adv = phy_read(phydev, MII_CTRL1000);
814         if (adv < 0)
815                 return adv;
816
817         oldadv = adv;
818         adv &= ~(ADVERTISE_1000FULL | ADVERTISE_1000HALF);
819
820         if (phydev->supported & (SUPPORTED_1000baseT_Half |
821                                  SUPPORTED_1000baseT_Full)) {
822                 adv |= ethtool_adv_to_mii_ctrl1000_t(advertise);
823         }
824
825         if (adv != oldadv)
826                 changed = 1;
827
828         err = phy_write(phydev, MII_CTRL1000, adv);
829         if (err < 0)
830                 return err;
831
832         return changed;
833 }
834
835 /**
836  * genphy_setup_forced - configures/forces speed/duplex from @phydev
837  * @phydev: target phy_device struct
838  *
839  * Description: Configures MII_BMCR to force speed/duplex
840  *   to the values in phydev. Assumes that the values are valid.
841  *   Please see phy_sanitize_settings().
842  */
843 int genphy_setup_forced(struct phy_device *phydev)
844 {
845         int ctl = 0;
846
847         phydev->pause = 0;
848         phydev->asym_pause = 0;
849
850         if (SPEED_1000 == phydev->speed)
851                 ctl |= BMCR_SPEED1000;
852         else if (SPEED_100 == phydev->speed)
853                 ctl |= BMCR_SPEED100;
854
855         if (DUPLEX_FULL == phydev->duplex)
856                 ctl |= BMCR_FULLDPLX;
857
858         return phy_write(phydev, MII_BMCR, ctl);
859 }
860 EXPORT_SYMBOL(genphy_setup_forced);
861
862 /**
863  * genphy_restart_aneg - Enable and Restart Autonegotiation
864  * @phydev: target phy_device struct
865  */
866 int genphy_restart_aneg(struct phy_device *phydev)
867 {
868         int ctl = phy_read(phydev, MII_BMCR);
869
870         if (ctl < 0)
871                 return ctl;
872
873         ctl |= BMCR_ANENABLE | BMCR_ANRESTART;
874
875         /* Don't isolate the PHY if we're negotiating */
876         ctl &= ~BMCR_ISOLATE;
877
878         return phy_write(phydev, MII_BMCR, ctl);
879 }
880 EXPORT_SYMBOL(genphy_restart_aneg);
881
882 /**
883  * genphy_config_aneg - restart auto-negotiation or write BMCR
884  * @phydev: target phy_device struct
885  *
886  * Description: If auto-negotiation is enabled, we configure the
887  *   advertising, and then restart auto-negotiation.  If it is not
888  *   enabled, then we write the BMCR.
889  */
890 int genphy_config_aneg(struct phy_device *phydev)
891 {
892         int result;
893
894         if (AUTONEG_ENABLE != phydev->autoneg)
895                 return genphy_setup_forced(phydev);
896
897         result = genphy_config_advert(phydev);
898         if (result < 0) /* error */
899                 return result;
900         if (result == 0) {
901                 /* Advertisement hasn't changed, but maybe aneg was never on to
902                  * begin with?  Or maybe phy was isolated?
903                  */
904                 int ctl = phy_read(phydev, MII_BMCR);
905
906                 if (ctl < 0)
907                         return ctl;
908
909                 if (!(ctl & BMCR_ANENABLE) || (ctl & BMCR_ISOLATE))
910                         result = 1; /* do restart aneg */
911         }
912
913         /* Only restart aneg if we are advertising something different
914          * than we were before.
915          */
916         if (result > 0)
917                 result = genphy_restart_aneg(phydev);
918
919         return result;
920 }
921 EXPORT_SYMBOL(genphy_config_aneg);
922
923 /**
924  * genphy_aneg_done - return auto-negotiation status
925  * @phydev: target phy_device struct
926  *
927  * Description: Reads the status register and returns 0 either if
928  *   auto-negotiation is incomplete, or if there was an error.
929  *   Returns BMSR_ANEGCOMPLETE if auto-negotiation is done.
930  */
931 int genphy_aneg_done(struct phy_device *phydev)
932 {
933         int retval = phy_read(phydev, MII_BMSR);
934
935         return (retval < 0) ? retval : (retval & BMSR_ANEGCOMPLETE);
936 }
937 EXPORT_SYMBOL(genphy_aneg_done);
938
939 static int gen10g_config_aneg(struct phy_device *phydev)
940 {
941         return 0;
942 }
943
944 /**
945  * genphy_update_link - update link status in @phydev
946  * @phydev: target phy_device struct
947  *
948  * Description: Update the value in phydev->link to reflect the
949  *   current link value.  In order to do this, we need to read
950  *   the status register twice, keeping the second value.
951  */
952 int genphy_update_link(struct phy_device *phydev)
953 {
954         int status;
955
956         /* Do a fake read */
957         status = phy_read(phydev, MII_BMSR);
958         if (status < 0)
959                 return status;
960
961         /* Read link and autonegotiation status */
962         status = phy_read(phydev, MII_BMSR);
963         if (status < 0)
964                 return status;
965
966         if ((status & BMSR_LSTATUS) == 0)
967                 phydev->link = 0;
968         else
969                 phydev->link = 1;
970
971         return 0;
972 }
973 EXPORT_SYMBOL(genphy_update_link);
974
975 /**
976  * genphy_read_status - check the link status and update current link state
977  * @phydev: target phy_device struct
978  *
979  * Description: Check the link, then figure out the current state
980  *   by comparing what we advertise with what the link partner
981  *   advertises.  Start by checking the gigabit possibilities,
982  *   then move on to 10/100.
983  */
984 int genphy_read_status(struct phy_device *phydev)
985 {
986         int adv;
987         int err;
988         int lpa;
989         int lpagb = 0;
990         int common_adv;
991         int common_adv_gb = 0;
992
993         /* Update the link, but return if there was an error */
994         err = genphy_update_link(phydev);
995         if (err)
996                 return err;
997
998         phydev->lp_advertising = 0;
999
1000         if (AUTONEG_ENABLE == phydev->autoneg) {
1001                 if (phydev->supported & (SUPPORTED_1000baseT_Half
1002                                         | SUPPORTED_1000baseT_Full)) {
1003                         lpagb = phy_read(phydev, MII_STAT1000);
1004                         if (lpagb < 0)
1005                                 return lpagb;
1006
1007                         adv = phy_read(phydev, MII_CTRL1000);
1008                         if (adv < 0)
1009                                 return adv;
1010
1011                         phydev->lp_advertising =
1012                                 mii_stat1000_to_ethtool_lpa_t(lpagb);
1013                         common_adv_gb = lpagb & adv << 2;
1014                 }
1015
1016                 lpa = phy_read(phydev, MII_LPA);
1017                 if (lpa < 0)
1018                         return lpa;
1019
1020                 phydev->lp_advertising |= mii_lpa_to_ethtool_lpa_t(lpa);
1021
1022                 adv = phy_read(phydev, MII_ADVERTISE);
1023                 if (adv < 0)
1024                         return adv;
1025
1026                 common_adv = lpa & adv;
1027
1028                 phydev->speed = SPEED_10;
1029                 phydev->duplex = DUPLEX_HALF;
1030                 phydev->pause = 0;
1031                 phydev->asym_pause = 0;
1032
1033                 if (common_adv_gb & (LPA_1000FULL | LPA_1000HALF)) {
1034                         phydev->speed = SPEED_1000;
1035
1036                         if (common_adv_gb & LPA_1000FULL)
1037                                 phydev->duplex = DUPLEX_FULL;
1038                 } else if (common_adv & (LPA_100FULL | LPA_100HALF)) {
1039                         phydev->speed = SPEED_100;
1040
1041                         if (common_adv & LPA_100FULL)
1042                                 phydev->duplex = DUPLEX_FULL;
1043                 } else
1044                         if (common_adv & LPA_10FULL)
1045                                 phydev->duplex = DUPLEX_FULL;
1046
1047                 if (phydev->duplex == DUPLEX_FULL) {
1048                         phydev->pause = lpa & LPA_PAUSE_CAP ? 1 : 0;
1049                         phydev->asym_pause = lpa & LPA_PAUSE_ASYM ? 1 : 0;
1050                 }
1051         } else {
1052                 int bmcr = phy_read(phydev, MII_BMCR);
1053
1054                 if (bmcr < 0)
1055                         return bmcr;
1056
1057                 if (bmcr & BMCR_FULLDPLX)
1058                         phydev->duplex = DUPLEX_FULL;
1059                 else
1060                         phydev->duplex = DUPLEX_HALF;
1061
1062                 if (bmcr & BMCR_SPEED1000)
1063                         phydev->speed = SPEED_1000;
1064                 else if (bmcr & BMCR_SPEED100)
1065                         phydev->speed = SPEED_100;
1066                 else
1067                         phydev->speed = SPEED_10;
1068
1069                 phydev->pause = 0;
1070                 phydev->asym_pause = 0;
1071         }
1072
1073         return 0;
1074 }
1075 EXPORT_SYMBOL(genphy_read_status);
1076
1077 static int gen10g_read_status(struct phy_device *phydev)
1078 {
1079         int devad, reg;
1080         u32 mmd_mask = phydev->c45_ids.devices_in_package;
1081
1082         phydev->link = 1;
1083
1084         /* For now just lie and say it's 10G all the time */
1085         phydev->speed = SPEED_10000;
1086         phydev->duplex = DUPLEX_FULL;
1087
1088         for (devad = 0; mmd_mask; devad++, mmd_mask = mmd_mask >> 1) {
1089                 if (!(mmd_mask & 1))
1090                         continue;
1091
1092                 /* Read twice because link state is latched and a
1093                  * read moves the current state into the register
1094                  */
1095                 phy_read_mmd(phydev, devad, MDIO_STAT1);
1096                 reg = phy_read_mmd(phydev, devad, MDIO_STAT1);
1097                 if (reg < 0 || !(reg & MDIO_STAT1_LSTATUS))
1098                         phydev->link = 0;
1099         }
1100
1101         return 0;
1102 }
1103
1104 /**
1105  * genphy_soft_reset - software reset the PHY via BMCR_RESET bit
1106  * @phydev: target phy_device struct
1107  *
1108  * Description: Perform a software PHY reset using the standard
1109  * BMCR_RESET bit and poll for the reset bit to be cleared.
1110  *
1111  * Returns: 0 on success, < 0 on failure
1112  */
1113 int genphy_soft_reset(struct phy_device *phydev)
1114 {
1115         int ret;
1116
1117         ret = phy_write(phydev, MII_BMCR, BMCR_RESET);
1118         if (ret < 0)
1119                 return ret;
1120
1121         return phy_poll_reset(phydev);
1122 }
1123 EXPORT_SYMBOL(genphy_soft_reset);
1124
1125 int genphy_config_init(struct phy_device *phydev)
1126 {
1127         int val;
1128         u32 features;
1129
1130         features = (SUPPORTED_TP | SUPPORTED_MII
1131                         | SUPPORTED_AUI | SUPPORTED_FIBRE |
1132                         SUPPORTED_BNC);
1133
1134         /* Do we support autonegotiation? */
1135         val = phy_read(phydev, MII_BMSR);
1136         if (val < 0)
1137                 return val;
1138
1139         if (val & BMSR_ANEGCAPABLE)
1140                 features |= SUPPORTED_Autoneg;
1141
1142         if (val & BMSR_100FULL)
1143                 features |= SUPPORTED_100baseT_Full;
1144         if (val & BMSR_100HALF)
1145                 features |= SUPPORTED_100baseT_Half;
1146         if (val & BMSR_10FULL)
1147                 features |= SUPPORTED_10baseT_Full;
1148         if (val & BMSR_10HALF)
1149                 features |= SUPPORTED_10baseT_Half;
1150
1151         if (val & BMSR_ESTATEN) {
1152                 val = phy_read(phydev, MII_ESTATUS);
1153                 if (val < 0)
1154                         return val;
1155
1156                 if (val & ESTATUS_1000_TFULL)
1157                         features |= SUPPORTED_1000baseT_Full;
1158                 if (val & ESTATUS_1000_THALF)
1159                         features |= SUPPORTED_1000baseT_Half;
1160         }
1161
1162         phydev->supported &= features;
1163         phydev->advertising &= features;
1164
1165         return 0;
1166 }
1167
1168 static int gen10g_soft_reset(struct phy_device *phydev)
1169 {
1170         /* Do nothing for now */
1171         return 0;
1172 }
1173 EXPORT_SYMBOL(genphy_config_init);
1174
1175 static int gen10g_config_init(struct phy_device *phydev)
1176 {
1177         /* Temporarily just say we support everything */
1178         phydev->supported = SUPPORTED_10000baseT_Full;
1179         phydev->advertising = SUPPORTED_10000baseT_Full;
1180
1181         return 0;
1182 }
1183
1184 int genphy_suspend(struct phy_device *phydev)
1185 {
1186         int value;
1187
1188         mutex_lock(&phydev->lock);
1189
1190         value = phy_read(phydev, MII_BMCR);
1191         phy_write(phydev, MII_BMCR, value | BMCR_PDOWN);
1192
1193         mutex_unlock(&phydev->lock);
1194
1195         return 0;
1196 }
1197 EXPORT_SYMBOL(genphy_suspend);
1198
1199 static int gen10g_suspend(struct phy_device *phydev)
1200 {
1201         return 0;
1202 }
1203
1204 int genphy_resume(struct phy_device *phydev)
1205 {
1206         int value;
1207
1208         mutex_lock(&phydev->lock);
1209
1210         value = phy_read(phydev, MII_BMCR);
1211         phy_write(phydev, MII_BMCR, value & ~BMCR_PDOWN);
1212
1213         mutex_unlock(&phydev->lock);
1214
1215         return 0;
1216 }
1217 EXPORT_SYMBOL(genphy_resume);
1218
1219 static int gen10g_resume(struct phy_device *phydev)
1220 {
1221         return 0;
1222 }
1223
1224 static void of_set_phy_supported(struct phy_device *phydev)
1225 {
1226         struct device_node *node = phydev->dev.of_node;
1227         u32 max_speed;
1228
1229         if (!IS_ENABLED(CONFIG_OF_MDIO))
1230                 return;
1231
1232         if (!node)
1233                 return;
1234
1235         if (!of_property_read_u32(node, "max-speed", &max_speed)) {
1236                 /* The default values for phydev->supported are provided by the PHY
1237                  * driver "features" member, we want to reset to sane defaults fist
1238                  * before supporting higher speeds.
1239                  */
1240                 phydev->supported &= PHY_DEFAULT_FEATURES;
1241
1242                 switch (max_speed) {
1243                 default:
1244                         return;
1245
1246                 case SPEED_1000:
1247                         phydev->supported |= PHY_1000BT_FEATURES;
1248                 case SPEED_100:
1249                         phydev->supported |= PHY_100BT_FEATURES;
1250                 case SPEED_10:
1251                         phydev->supported |= PHY_10BT_FEATURES;
1252                 }
1253         }
1254 }
1255
1256 /**
1257  * phy_probe - probe and init a PHY device
1258  * @dev: device to probe and init
1259  *
1260  * Description: Take care of setting up the phy_device structure,
1261  *   set the state to READY (the driver's init function should
1262  *   set it to STARTING if needed).
1263  */
1264 static int phy_probe(struct device *dev)
1265 {
1266         struct phy_device *phydev = to_phy_device(dev);
1267         struct device_driver *drv = phydev->dev.driver;
1268         struct phy_driver *phydrv = to_phy_driver(drv);
1269         int err = 0;
1270
1271         phydev->drv = phydrv;
1272
1273         /* Disable the interrupt if the PHY doesn't support it
1274          * but the interrupt is still a valid one
1275          */
1276         if (!(phydrv->flags & PHY_HAS_INTERRUPT) &&
1277             phy_interrupt_is_valid(phydev))
1278                 phydev->irq = PHY_POLL;
1279
1280         if (phydrv->flags & PHY_IS_INTERNAL)
1281                 phydev->is_internal = true;
1282
1283         mutex_lock(&phydev->lock);
1284
1285         /* Start out supporting everything. Eventually,
1286          * a controller will attach, and may modify one
1287          * or both of these values
1288          */
1289         phydev->supported = phydrv->features;
1290         of_set_phy_supported(phydev);
1291         phydev->advertising = phydev->supported;
1292
1293         /* Set the state to READY by default */
1294         phydev->state = PHY_READY;
1295
1296         if (phydev->drv->probe)
1297                 err = phydev->drv->probe(phydev);
1298
1299         mutex_unlock(&phydev->lock);
1300
1301         return err;
1302 }
1303
1304 static int phy_remove(struct device *dev)
1305 {
1306         struct phy_device *phydev = to_phy_device(dev);
1307
1308         mutex_lock(&phydev->lock);
1309         phydev->state = PHY_DOWN;
1310         mutex_unlock(&phydev->lock);
1311
1312         if (phydev->drv->remove)
1313                 phydev->drv->remove(phydev);
1314         phydev->drv = NULL;
1315
1316         return 0;
1317 }
1318
1319 /**
1320  * phy_driver_register - register a phy_driver with the PHY layer
1321  * @new_driver: new phy_driver to register
1322  */
1323 int phy_driver_register(struct phy_driver *new_driver)
1324 {
1325         int retval;
1326
1327         new_driver->driver.name = new_driver->name;
1328         new_driver->driver.bus = &mdio_bus_type;
1329         new_driver->driver.probe = phy_probe;
1330         new_driver->driver.remove = phy_remove;
1331
1332         retval = driver_register(&new_driver->driver);
1333         if (retval) {
1334                 pr_err("%s: Error %d in registering driver\n",
1335                        new_driver->name, retval);
1336
1337                 return retval;
1338         }
1339
1340         pr_debug("%s: Registered new driver\n", new_driver->name);
1341
1342         return 0;
1343 }
1344 EXPORT_SYMBOL(phy_driver_register);
1345
1346 int phy_drivers_register(struct phy_driver *new_driver, int n)
1347 {
1348         int i, ret = 0;
1349
1350         for (i = 0; i < n; i++) {
1351                 ret = phy_driver_register(new_driver + i);
1352                 if (ret) {
1353                         while (i-- > 0)
1354                                 phy_driver_unregister(new_driver + i);
1355                         break;
1356                 }
1357         }
1358         return ret;
1359 }
1360 EXPORT_SYMBOL(phy_drivers_register);
1361
1362 void phy_driver_unregister(struct phy_driver *drv)
1363 {
1364         driver_unregister(&drv->driver);
1365 }
1366 EXPORT_SYMBOL(phy_driver_unregister);
1367
1368 void phy_drivers_unregister(struct phy_driver *drv, int n)
1369 {
1370         int i;
1371
1372         for (i = 0; i < n; i++)
1373                 phy_driver_unregister(drv + i);
1374 }
1375 EXPORT_SYMBOL(phy_drivers_unregister);
1376
1377 static struct phy_driver genphy_driver[] = {
1378 {
1379         .phy_id         = 0xffffffff,
1380         .phy_id_mask    = 0xffffffff,
1381         .name           = "Generic PHY",
1382         .soft_reset     = genphy_soft_reset,
1383         .config_init    = genphy_config_init,
1384         .features       = PHY_GBIT_FEATURES | SUPPORTED_MII |
1385                           SUPPORTED_AUI | SUPPORTED_FIBRE |
1386                           SUPPORTED_BNC,
1387         .config_aneg    = genphy_config_aneg,
1388         .aneg_done      = genphy_aneg_done,
1389         .read_status    = genphy_read_status,
1390         .suspend        = genphy_suspend,
1391         .resume         = genphy_resume,
1392         .driver         = { .owner = THIS_MODULE, },
1393 }, {
1394         .phy_id         = 0xffffffff,
1395         .phy_id_mask    = 0xffffffff,
1396         .name           = "Generic 10G PHY",
1397         .soft_reset     = gen10g_soft_reset,
1398         .config_init    = gen10g_config_init,
1399         .features       = 0,
1400         .config_aneg    = gen10g_config_aneg,
1401         .read_status    = gen10g_read_status,
1402         .suspend        = gen10g_suspend,
1403         .resume         = gen10g_resume,
1404         .driver         = {.owner = THIS_MODULE, },
1405 } };
1406
1407 static int __init phy_init(void)
1408 {
1409         int rc;
1410
1411         rc = mdio_bus_init();
1412         if (rc)
1413                 return rc;
1414
1415         rc = phy_drivers_register(genphy_driver,
1416                                   ARRAY_SIZE(genphy_driver));
1417         if (rc)
1418                 mdio_bus_exit();
1419
1420         return rc;
1421 }
1422
1423 static void __exit phy_exit(void)
1424 {
1425         phy_drivers_unregister(genphy_driver,
1426                                ARRAY_SIZE(genphy_driver));
1427         mdio_bus_exit();
1428 }
1429
1430 subsys_initcall(phy_init);
1431 module_exit(phy_exit);