]> rtime.felk.cvut.cz Git - zynq/linux.git/blob - drivers/net/ethernet/cadence/macb_main.c
net: macb: Use net_device_stats from struct net_device
[zynq/linux.git] / drivers / net / ethernet / cadence / macb_main.c
1 /*
2  * Cadence MACB/GEM Ethernet Controller driver
3  *
4  * Copyright (C) 2004-2006 Atmel Corporation
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  */
10
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 #include <linux/clk.h>
13 #include <linux/module.h>
14 #include <linux/moduleparam.h>
15 #include <linux/kernel.h>
16 #include <linux/types.h>
17 #include <linux/circ_buf.h>
18 #include <linux/slab.h>
19 #include <linux/init.h>
20 #include <linux/io.h>
21 #include <linux/gpio.h>
22 #include <linux/gpio/consumer.h>
23 #include <linux/interrupt.h>
24 #include <linux/netdevice.h>
25 #include <linux/etherdevice.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/platform_data/macb.h>
28 #include <linux/platform_device.h>
29 #include <linux/phy.h>
30 #include <linux/of.h>
31 #include <linux/of_device.h>
32 #include <linux/of_gpio.h>
33 #include <linux/of_mdio.h>
34 #include <linux/of_net.h>
35 #include <linux/ip.h>
36 #include <linux/udp.h>
37 #include <linux/tcp.h>
38 #include <linux/pm_runtime.h>
39 #include <linux/crc32.h>
40 #include <linux/inetdevice.h>
41 #include "macb.h"
42
43 #define MACB_RX_BUFFER_SIZE     128
44 #define RX_BUFFER_MULTIPLE      64  /* bytes */
45
46 #define DEFAULT_RX_RING_SIZE    512 /* must be power of 2 */
47 #define MIN_RX_RING_SIZE        64
48 #define MAX_RX_RING_SIZE        8192
49 #define RX_RING_BYTES(bp)       (macb_dma_desc_get_size(bp)     \
50                                  * (bp)->rx_ring_size)
51
52 #define DEFAULT_TX_RING_SIZE    512 /* must be power of 2 */
53 #define MIN_TX_RING_SIZE        64
54 #define MAX_TX_RING_SIZE        4096
55 #define TX_RING_BYTES(bp)       (macb_dma_desc_get_size(bp)     \
56                                  * (bp)->tx_ring_size)
57
58 /* level of occupied TX descriptors under which we wake up TX process */
59 #define MACB_TX_WAKEUP_THRESH(bp)       (3 * (bp)->tx_ring_size / 4)
60
61 #define MACB_RX_INT_FLAGS       (MACB_BIT(RCOMP) | MACB_BIT(RXUBR)      \
62                                  | MACB_BIT(ISR_ROVR))
63 #define MACB_TX_ERR_FLAGS       (MACB_BIT(ISR_TUND)                     \
64                                         | MACB_BIT(ISR_RLE)             \
65                                         | MACB_BIT(TXERR))
66 #define MACB_TX_INT_FLAGS       (MACB_TX_ERR_FLAGS | MACB_BIT(TCOMP))
67
68 /* Max length of transmit frame must be a multiple of 8 bytes */
69 #define MACB_TX_LEN_ALIGN       8
70 #define MACB_MAX_TX_LEN         ((unsigned int)((1 << MACB_TX_FRMLEN_SIZE) - 1) & ~((unsigned int)(MACB_TX_LEN_ALIGN - 1)))
71 #define GEM_MAX_TX_LEN          ((unsigned int)((1 << GEM_TX_FRMLEN_SIZE) - 1) & ~((unsigned int)(MACB_TX_LEN_ALIGN - 1)))
72
73 #define GEM_MTU_MIN_SIZE        ETH_MIN_MTU
74 #define MACB_NETIF_LSO          NETIF_F_TSO
75
76 /* Graceful stop timeouts in us. We should allow up to
77  * 1 frame time (10 Mbits/s, full-duplex, ignoring collisions)
78  */
79 #define MACB_HALT_TIMEOUT       1230
80 #define MACB_PM_TIMEOUT  100 /* ms */
81
82 /* DMA buffer descriptor might be different size
83  * depends on hardware configuration:
84  *
85  * 1. dma address width 32 bits:
86  *    word 1: 32 bit address of Data Buffer
87  *    word 2: control
88  *
89  * 2. dma address width 64 bits:
90  *    word 1: 32 bit address of Data Buffer
91  *    word 2: control
92  *    word 3: upper 32 bit address of Data Buffer
93  *    word 4: unused
94  *
95  * 3. dma address width 32 bits with hardware timestamping:
96  *    word 1: 32 bit address of Data Buffer
97  *    word 2: control
98  *    word 3: timestamp word 1
99  *    word 4: timestamp word 2
100  *
101  * 4. dma address width 64 bits with hardware timestamping:
102  *    word 1: 32 bit address of Data Buffer
103  *    word 2: control
104  *    word 3: upper 32 bit address of Data Buffer
105  *    word 4: unused
106  *    word 5: timestamp word 1
107  *    word 6: timestamp word 2
108  */
109 static unsigned int macb_dma_desc_get_size(struct macb *bp)
110 {
111 #ifdef MACB_EXT_DESC
112         unsigned int desc_size;
113
114         switch (bp->hw_dma_cap) {
115         case HW_DMA_CAP_64B:
116                 desc_size = sizeof(struct macb_dma_desc)
117                         + sizeof(struct macb_dma_desc_64);
118                 break;
119         case HW_DMA_CAP_PTP:
120                 desc_size = sizeof(struct macb_dma_desc)
121                         + sizeof(struct macb_dma_desc_ptp);
122                 break;
123         case HW_DMA_CAP_64B_PTP:
124                 desc_size = sizeof(struct macb_dma_desc)
125                         + sizeof(struct macb_dma_desc_64)
126                         + sizeof(struct macb_dma_desc_ptp);
127                 break;
128         default:
129                 desc_size = sizeof(struct macb_dma_desc);
130         }
131         return desc_size;
132 #endif
133         return sizeof(struct macb_dma_desc);
134 }
135
136 static unsigned int macb_adj_dma_desc_idx(struct macb *bp, unsigned int desc_idx)
137 {
138 #ifdef MACB_EXT_DESC
139         switch (bp->hw_dma_cap) {
140         case HW_DMA_CAP_64B:
141         case HW_DMA_CAP_PTP:
142                 desc_idx <<= 1;
143                 break;
144         case HW_DMA_CAP_64B_PTP:
145                 desc_idx *= 3;
146                 break;
147         default:
148                 break;
149         }
150 #endif
151         return desc_idx;
152 }
153
154 #ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
155 static struct macb_dma_desc_64 *macb_64b_desc(struct macb *bp, struct macb_dma_desc *desc)
156 {
157         if (bp->hw_dma_cap & HW_DMA_CAP_64B)
158                 return (struct macb_dma_desc_64 *)((void *)desc + sizeof(struct macb_dma_desc));
159         return NULL;
160 }
161 #endif
162
163 /* Ring buffer accessors */
164 static unsigned int macb_tx_ring_wrap(struct macb *bp, unsigned int index)
165 {
166         return index & (bp->tx_ring_size - 1);
167 }
168
169 static struct macb_dma_desc *macb_tx_desc(struct macb_queue *queue,
170                                           unsigned int index)
171 {
172         index = macb_tx_ring_wrap(queue->bp, index);
173         index = macb_adj_dma_desc_idx(queue->bp, index);
174         return &queue->tx_ring[index];
175 }
176
177 static struct macb_tx_skb *macb_tx_skb(struct macb_queue *queue,
178                                        unsigned int index)
179 {
180         return &queue->tx_skb[macb_tx_ring_wrap(queue->bp, index)];
181 }
182
183 static dma_addr_t macb_tx_dma(struct macb_queue *queue, unsigned int index)
184 {
185         dma_addr_t offset;
186
187         offset = macb_tx_ring_wrap(queue->bp, index) *
188                         macb_dma_desc_get_size(queue->bp);
189
190         return queue->tx_ring_dma + offset;
191 }
192
193 static unsigned int macb_rx_ring_wrap(struct macb *bp, unsigned int index)
194 {
195         return index & (bp->rx_ring_size - 1);
196 }
197
198 static struct macb_dma_desc *macb_rx_desc(struct macb *bp, unsigned int index)
199 {
200         index = macb_rx_ring_wrap(bp, index);
201         index = macb_adj_dma_desc_idx(bp, index);
202         return &bp->rx_ring[index];
203 }
204
205 static void *macb_rx_buffer(struct macb *bp, unsigned int index)
206 {
207         return bp->rx_buffers + bp->rx_buffer_size *
208                macb_rx_ring_wrap(bp, index);
209 }
210
211 /* I/O accessors */
212 static u32 hw_readl_native(struct macb *bp, int offset)
213 {
214         return __raw_readl(bp->regs + offset);
215 }
216
217 static void hw_writel_native(struct macb *bp, int offset, u32 value)
218 {
219         __raw_writel(value, bp->regs + offset);
220 }
221
222 static u32 hw_readl(struct macb *bp, int offset)
223 {
224         return readl_relaxed(bp->regs + offset);
225 }
226
227 static void hw_writel(struct macb *bp, int offset, u32 value)
228 {
229         writel_relaxed(value, bp->regs + offset);
230 }
231
232 /* Find the CPU endianness by using the loopback bit of NCR register. When the
233  * CPU is in big endian we need to program swapped mode for management
234  * descriptor access.
235  */
236 static bool hw_is_native_io(void __iomem *addr)
237 {
238         u32 value = MACB_BIT(LLB);
239
240         __raw_writel(value, addr + MACB_NCR);
241         value = __raw_readl(addr + MACB_NCR);
242
243         /* Write 0 back to disable everything */
244         __raw_writel(0, addr + MACB_NCR);
245
246         return value == MACB_BIT(LLB);
247 }
248
249 static bool hw_is_gem(void __iomem *addr, bool native_io)
250 {
251         u32 id;
252
253         if (native_io)
254                 id = __raw_readl(addr + MACB_MID);
255         else
256                 id = readl_relaxed(addr + MACB_MID);
257
258         return MACB_BFEXT(IDNUM, id) >= 0x2;
259 }
260
261 static void macb_set_hwaddr(struct macb *bp)
262 {
263         u32 bottom;
264         u16 top;
265
266         bottom = cpu_to_le32(*((u32 *)bp->dev->dev_addr));
267         macb_or_gem_writel(bp, SA1B, bottom);
268         top = cpu_to_le16(*((u16 *)(bp->dev->dev_addr + 4)));
269         macb_or_gem_writel(bp, SA1T, top);
270
271         gem_writel(bp, RXPTPUNI, bottom);
272         gem_writel(bp, TXPTPUNI, bottom);
273
274         /* Clear unused address register sets */
275         macb_or_gem_writel(bp, SA2B, 0);
276         macb_or_gem_writel(bp, SA2T, 0);
277         macb_or_gem_writel(bp, SA3B, 0);
278         macb_or_gem_writel(bp, SA3T, 0);
279         macb_or_gem_writel(bp, SA4B, 0);
280         macb_or_gem_writel(bp, SA4T, 0);
281 }
282
283 static void macb_get_hwaddr(struct macb *bp)
284 {
285         struct macb_platform_data *pdata;
286         u32 bottom;
287         u16 top;
288         u8 addr[6];
289         int i;
290
291         pdata = dev_get_platdata(&bp->pdev->dev);
292
293         /* Check all 4 address register for valid address */
294         for (i = 0; i < 4; i++) {
295                 bottom = macb_or_gem_readl(bp, SA1B + i * 8);
296                 top = macb_or_gem_readl(bp, SA1T + i * 8);
297
298                 if (pdata && pdata->rev_eth_addr) {
299                         addr[5] = bottom & 0xff;
300                         addr[4] = (bottom >> 8) & 0xff;
301                         addr[3] = (bottom >> 16) & 0xff;
302                         addr[2] = (bottom >> 24) & 0xff;
303                         addr[1] = top & 0xff;
304                         addr[0] = (top & 0xff00) >> 8;
305                 } else {
306                         addr[0] = bottom & 0xff;
307                         addr[1] = (bottom >> 8) & 0xff;
308                         addr[2] = (bottom >> 16) & 0xff;
309                         addr[3] = (bottom >> 24) & 0xff;
310                         addr[4] = top & 0xff;
311                         addr[5] = (top >> 8) & 0xff;
312                 }
313
314                 if (is_valid_ether_addr(addr)) {
315                         memcpy(bp->dev->dev_addr, addr, sizeof(addr));
316                         return;
317                 }
318         }
319
320         dev_info(&bp->pdev->dev, "invalid hw address, using random\n");
321         eth_hw_addr_random(bp->dev);
322 }
323
324 static int macb_mdio_read(struct mii_bus *bus, int mii_id, int regnum)
325 {
326         struct macb *bp = bus->priv;
327         int value;
328         int err;
329         ulong timeout;
330
331         err = pm_runtime_get_sync(&bp->pdev->dev);
332         if (err < 0)
333                 return err;
334
335         timeout = jiffies + msecs_to_jiffies(1000);
336         /* wait for end of transfer */
337         do {
338                 if (MACB_BFEXT(IDLE, macb_readl(bp, NSR)))
339                         break;
340
341                 cpu_relax();
342         } while (!time_after_eq(jiffies, timeout));
343
344         if (time_after_eq(jiffies, timeout)) {
345                 netdev_err(bp->dev, "wait for end of transfer timed out\n");
346                 pm_runtime_mark_last_busy(&bp->pdev->dev);
347                 pm_runtime_put_autosuspend(&bp->pdev->dev);
348                 return -ETIMEDOUT;
349         }
350
351         macb_writel(bp, MAN, (MACB_BF(SOF, MACB_MAN_SOF)
352                               | MACB_BF(RW, MACB_MAN_READ)
353                               | MACB_BF(PHYA, mii_id)
354                               | MACB_BF(REGA, regnum)
355                               | MACB_BF(CODE, MACB_MAN_CODE)));
356
357         timeout = jiffies + msecs_to_jiffies(1000);
358         /* wait for end of transfer */
359         do {
360                 if (MACB_BFEXT(IDLE, macb_readl(bp, NSR)))
361                         break;
362
363                 cpu_relax();
364         } while (!time_after_eq(jiffies, timeout));
365
366         if (time_after_eq(jiffies, timeout)) {
367                 netdev_err(bp->dev, "wait for end of transfer timed out\n");
368                 pm_runtime_mark_last_busy(&bp->pdev->dev);
369                 pm_runtime_put_autosuspend(&bp->pdev->dev);
370                 return -ETIMEDOUT;
371         }
372
373         value = MACB_BFEXT(DATA, macb_readl(bp, MAN));
374
375         pm_runtime_mark_last_busy(&bp->pdev->dev);
376         pm_runtime_put_autosuspend(&bp->pdev->dev);
377         return value;
378 }
379
380 static int macb_mdio_write(struct mii_bus *bus, int mii_id, int regnum,
381                            u16 value)
382 {
383         struct macb *bp = bus->priv;
384         int err;
385         ulong timeout;
386
387         err = pm_runtime_get_sync(&bp->pdev->dev);
388         if (err < 0)
389                 return err;
390
391         timeout = jiffies + msecs_to_jiffies(1000);
392         /* wait for end of transfer */
393         do {
394                 if (MACB_BFEXT(IDLE, macb_readl(bp, NSR)))
395                         break;
396
397                 cpu_relax();
398         } while (!time_after_eq(jiffies, timeout));
399
400         if (time_after_eq(jiffies, timeout)) {
401                 netdev_err(bp->dev, "wait for end of transfer timed out\n");
402                 pm_runtime_mark_last_busy(&bp->pdev->dev);
403                 pm_runtime_put_autosuspend(&bp->pdev->dev);
404                 return -ETIMEDOUT;
405         }
406
407         macb_writel(bp, MAN, (MACB_BF(SOF, MACB_MAN_SOF)
408                               | MACB_BF(RW, MACB_MAN_WRITE)
409                               | MACB_BF(PHYA, mii_id)
410                               | MACB_BF(REGA, regnum)
411                               | MACB_BF(CODE, MACB_MAN_CODE)
412                               | MACB_BF(DATA, value)));
413
414         timeout = jiffies + msecs_to_jiffies(1000);
415         /* wait for end of transfer */
416         do {
417                 if (MACB_BFEXT(IDLE, macb_readl(bp, NSR)))
418                         break;
419
420                 cpu_relax();
421         } while (!time_after_eq(jiffies, timeout));
422
423         if (time_after_eq(jiffies, timeout)) {
424                 netdev_err(bp->dev, "wait for end of transfer timed out\n");
425                 pm_runtime_mark_last_busy(&bp->pdev->dev);
426                 pm_runtime_put_autosuspend(&bp->pdev->dev);
427                 return -ETIMEDOUT;
428         }
429
430         pm_runtime_mark_last_busy(&bp->pdev->dev);
431         pm_runtime_put_autosuspend(&bp->pdev->dev);
432         return 0;
433 }
434
435 /**
436  * macb_set_tx_clk - Set a clock to a new frequency
437  * @clk:        Pointer to the clock to change
438  * @speed:      New frequency in Hz
439  * @dev:        Pointer to the struct net_device
440  */
441 static void macb_set_tx_clk(struct clk *clk, int speed, struct net_device *dev)
442 {
443         long ferr, rate, rate_rounded;
444
445         if (!clk)
446                 return;
447
448         switch (speed) {
449         case SPEED_10:
450                 rate = 2500000;
451                 break;
452         case SPEED_100:
453                 rate = 25000000;
454                 break;
455         case SPEED_1000:
456                 rate = 125000000;
457                 break;
458         default:
459                 return;
460         }
461
462         rate_rounded = clk_round_rate(clk, rate);
463         if (rate_rounded < 0)
464                 return;
465
466         /* RGMII allows 50 ppm frequency error. Test and warn if this limit
467          * is not satisfied.
468          */
469         ferr = abs(rate_rounded - rate);
470         ferr = DIV_ROUND_UP(ferr, rate / 100000);
471         if (ferr > 5)
472                 netdev_warn(dev, "unable to generate target frequency: %ld Hz\n",
473                             rate);
474
475         if (clk_set_rate(clk, rate_rounded))
476                 netdev_err(dev, "adjusting tx_clk failed.\n");
477 }
478
479 static void macb_handle_link_change(struct net_device *dev)
480 {
481         struct macb *bp = netdev_priv(dev);
482         struct phy_device *phydev = bp->phy_dev;
483         unsigned long flags;
484         int status_change = 0;
485
486         spin_lock_irqsave(&bp->lock, flags);
487
488         if (phydev->link) {
489                 if ((bp->speed != phydev->speed) ||
490                     (bp->duplex != phydev->duplex)) {
491                         u32 reg;
492
493                         reg = macb_readl(bp, NCFGR);
494                         reg &= ~(MACB_BIT(SPD) | MACB_BIT(FD));
495                         if (macb_is_gem(bp))
496                                 reg &= ~GEM_BIT(GBE);
497
498                         if (phydev->duplex)
499                                 reg |= MACB_BIT(FD);
500                         if (phydev->speed == SPEED_100)
501                                 reg |= MACB_BIT(SPD);
502                         if (phydev->speed == SPEED_1000 &&
503                             bp->caps & MACB_CAPS_GIGABIT_MODE_AVAILABLE)
504                                 reg |= GEM_BIT(GBE);
505
506                         macb_or_gem_writel(bp, NCFGR, reg);
507
508                         bp->speed = phydev->speed;
509                         bp->duplex = phydev->duplex;
510                         status_change = 1;
511                 }
512         }
513
514         if (phydev->link != bp->link) {
515                 if (!phydev->link) {
516                         bp->speed = 0;
517                         bp->duplex = -1;
518                 }
519                 bp->link = phydev->link;
520
521                 status_change = 1;
522         }
523
524         spin_unlock_irqrestore(&bp->lock, flags);
525
526         if (status_change) {
527                 if (phydev->link) {
528                         /* Update the TX clock rate if and only if the link is
529                          * up and there has been a link change.
530                          */
531                         macb_set_tx_clk(bp->tx_clk, phydev->speed, dev);
532
533                         netif_carrier_on(dev);
534                         netdev_info(dev, "link up (%d/%s)\n",
535                                     phydev->speed,
536                                     phydev->duplex == DUPLEX_FULL ?
537                                     "Full" : "Half");
538                 } else {
539                         netif_carrier_off(dev);
540                         netdev_info(dev, "link down\n");
541                 }
542         }
543 }
544
545 /* based on au1000_eth. c*/
546 static int macb_mii_probe(struct net_device *dev)
547 {
548         struct macb *bp = netdev_priv(dev);
549         struct macb_platform_data *pdata;
550         struct phy_device *phydev;
551         int phy_irq;
552         int ret;
553
554         if (bp->phy_node) {
555                 phydev = of_phy_connect(dev, bp->phy_node,
556                                         &macb_handle_link_change, 0,
557                                         bp->phy_interface);
558                 if (!phydev)
559                         return -ENODEV;
560         } else {
561                 phydev = phy_find_first(bp->mii_bus);
562                 if (!phydev) {
563                         netdev_err(dev, "no PHY found\n");
564                         return -ENXIO;
565                 }
566
567                 pdata = dev_get_platdata(&bp->pdev->dev);
568                 if (pdata && gpio_is_valid(pdata->phy_irq_pin)) {
569                         ret = devm_gpio_request(&bp->pdev->dev,
570                                                 pdata->phy_irq_pin, "phy int");
571                         if (!ret) {
572                                 phy_irq = gpio_to_irq(pdata->phy_irq_pin);
573                                 phydev->irq = (phy_irq < 0) ?
574                                               PHY_POLL : phy_irq;
575                         }
576                 }
577
578                 /* attach the mac to the phy */
579                 ret = phy_connect_direct(dev, phydev, &macb_handle_link_change,
580                                          bp->phy_interface);
581                 if (ret) {
582                         netdev_err(dev, "Could not attach to PHY\n");
583                         return ret;
584                 }
585         }
586
587         /* mask with MAC supported features */
588         if (macb_is_gem(bp) && bp->caps & MACB_CAPS_GIGABIT_MODE_AVAILABLE)
589                 phydev->supported &= PHY_GBIT_FEATURES;
590         else
591                 phydev->supported &= PHY_BASIC_FEATURES;
592
593         if (bp->caps & MACB_CAPS_NO_GIGABIT_HALF)
594                 phydev->supported &= ~SUPPORTED_1000baseT_Half;
595
596         phydev->advertising = phydev->supported;
597
598         bp->link = 0;
599         bp->speed = 0;
600         bp->duplex = -1;
601         bp->phy_dev = phydev;
602
603         return 0;
604 }
605
606 static int macb_mii_init(struct macb *bp)
607 {
608         struct macb_platform_data *pdata;
609         struct device_node *np, *mdio_np;
610         int err = -ENXIO, i;
611
612         /* Enable management port */
613         macb_writel(bp, NCR, MACB_BIT(MPE));
614
615         bp->mii_bus = mdiobus_alloc();
616         if (!bp->mii_bus) {
617                 err = -ENOMEM;
618                 goto err_out;
619         }
620
621         bp->mii_bus->name = "MACB_mii_bus";
622         bp->mii_bus->read = &macb_mdio_read;
623         bp->mii_bus->write = &macb_mdio_write;
624         snprintf(bp->mii_bus->id, MII_BUS_ID_SIZE, "%s-%x",
625                  bp->pdev->name, bp->pdev->id);
626         bp->mii_bus->priv = bp;
627         bp->mii_bus->parent = &bp->dev->dev;
628         pdata = dev_get_platdata(&bp->pdev->dev);
629
630         dev_set_drvdata(&bp->dev->dev, bp->mii_bus);
631
632         np = bp->pdev->dev.of_node;
633         mdio_np = of_get_child_by_name(np, "mdio");
634         if (mdio_np) {
635                 of_node_put(mdio_np);
636                 err = of_mdiobus_register(bp->mii_bus, mdio_np);
637                 if (err)
638                         goto err_out_unregister_bus;
639         } else if (np) {
640                 /* try dt phy registration */
641                 err = of_mdiobus_register(bp->mii_bus, np);
642
643                 /* fallback to standard phy registration if no phy were
644                  * found during dt phy registration
645                  */
646                 if (!err && !phy_find_first(bp->mii_bus)) {
647                         for (i = 0; i < PHY_MAX_ADDR; i++) {
648                                 struct phy_device *phydev;
649
650                                 phydev = mdiobus_scan(bp->mii_bus, i);
651                                 if (IS_ERR(phydev) &&
652                                     PTR_ERR(phydev) != -ENODEV) {
653                                         err = PTR_ERR(phydev);
654                                         break;
655                                 }
656                         }
657
658                         if (err)
659                                 goto err_out_unregister_bus;
660                 }
661         } else {
662                 if (pdata)
663                         bp->mii_bus->phy_mask = pdata->phy_mask;
664
665                 err = mdiobus_register(bp->mii_bus);
666         }
667
668         if (err)
669                 goto err_out_free_mdiobus;
670
671         err = macb_mii_probe(bp->dev);
672         if (err)
673                 goto err_out_unregister_bus;
674
675         return 0;
676
677 err_out_unregister_bus:
678         mdiobus_unregister(bp->mii_bus);
679 err_out_free_mdiobus:
680         mdiobus_free(bp->mii_bus);
681 err_out:
682         return err;
683 }
684
685 static void macb_update_stats(struct macb *bp)
686 {
687         u32 *p = &bp->hw_stats.macb.rx_pause_frames;
688         u32 *end = &bp->hw_stats.macb.tx_pause_frames + 1;
689         int offset = MACB_PFR;
690
691         WARN_ON((unsigned long)(end - p - 1) != (MACB_TPF - MACB_PFR) / 4);
692
693         for (; p < end; p++, offset += 4)
694                 *p += bp->macb_reg_readl(bp, offset);
695 }
696
697 static int macb_halt_tx(struct macb *bp)
698 {
699         unsigned long   halt_time, timeout;
700         u32             status;
701
702         macb_writel(bp, NCR, macb_readl(bp, NCR) | MACB_BIT(THALT));
703
704         timeout = jiffies + usecs_to_jiffies(MACB_HALT_TIMEOUT);
705         do {
706                 halt_time = jiffies;
707                 status = macb_readl(bp, TSR);
708                 if (!(status & MACB_BIT(TGO)))
709                         return 0;
710
711                 usleep_range(10, 250);
712         } while (time_before(halt_time, timeout));
713
714         return -ETIMEDOUT;
715 }
716
717 static void macb_tx_unmap(struct macb *bp, struct macb_tx_skb *tx_skb)
718 {
719         if (tx_skb->mapping) {
720                 if (tx_skb->mapped_as_page)
721                         dma_unmap_page(&bp->pdev->dev, tx_skb->mapping,
722                                        tx_skb->size, DMA_TO_DEVICE);
723                 else
724                         dma_unmap_single(&bp->pdev->dev, tx_skb->mapping,
725                                          tx_skb->size, DMA_TO_DEVICE);
726                 tx_skb->mapping = 0;
727         }
728
729         if (tx_skb->skb) {
730                 dev_kfree_skb_any(tx_skb->skb);
731                 tx_skb->skb = NULL;
732         }
733 }
734
735 static void macb_set_addr(struct macb *bp, struct macb_dma_desc *desc, dma_addr_t addr)
736 {
737 #ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
738         struct macb_dma_desc_64 *desc_64;
739
740         if (bp->hw_dma_cap & HW_DMA_CAP_64B) {
741                 desc_64 = macb_64b_desc(bp, desc);
742                 desc_64->addrh = upper_32_bits(addr);
743         }
744 #endif
745         desc->addr = lower_32_bits(addr);
746 }
747
748 static dma_addr_t macb_get_addr(struct macb *bp, struct macb_dma_desc *desc)
749 {
750         dma_addr_t addr = 0;
751 #ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
752         struct macb_dma_desc_64 *desc_64;
753
754         if (bp->hw_dma_cap & HW_DMA_CAP_64B) {
755                 desc_64 = macb_64b_desc(bp, desc);
756                 addr = ((u64)(desc_64->addrh) << 32);
757         }
758 #endif
759         addr |= MACB_BF(RX_WADDR, MACB_BFEXT(RX_WADDR, desc->addr));
760         return addr;
761 }
762
763 static void macb_tx_error_task(struct work_struct *work)
764 {
765         struct macb_queue       *queue = container_of(work, struct macb_queue,
766                                                       tx_error_task);
767         struct macb             *bp = queue->bp;
768         struct macb_tx_skb      *tx_skb;
769         struct macb_dma_desc    *desc;
770         struct sk_buff          *skb;
771         unsigned int            tail;
772         unsigned long           flags;
773
774         netdev_vdbg(bp->dev, "macb_tx_error_task: q = %u, t = %u, h = %u\n",
775                     (unsigned int)(queue - bp->queues),
776                     queue->tx_tail, queue->tx_head);
777
778         /* Prevent the queue IRQ handlers from running: each of them may call
779          * macb_tx_interrupt(), which in turn may call netif_wake_subqueue().
780          * As explained below, we have to halt the transmission before updating
781          * TBQP registers so we call netif_tx_stop_all_queues() to notify the
782          * network engine about the macb/gem being halted.
783          */
784         spin_lock_irqsave(&bp->lock, flags);
785
786         /* Make sure nobody is trying to queue up new packets */
787         netif_tx_stop_all_queues(bp->dev);
788
789         /* Stop transmission now
790          * (in case we have just queued new packets)
791          * macb/gem must be halted to write TBQP register
792          */
793         if (macb_halt_tx(bp))
794                 /* Just complain for now, reinitializing TX path can be good */
795                 netdev_err(bp->dev, "BUG: halt tx timed out\n");
796
797         /* Treat frames in TX queue including the ones that caused the error.
798          * Free transmit buffers in upper layer.
799          */
800         for (tail = queue->tx_tail; tail != queue->tx_head; tail++) {
801                 u32     ctrl;
802
803                 desc = macb_tx_desc(queue, tail);
804                 ctrl = desc->ctrl;
805                 tx_skb = macb_tx_skb(queue, tail);
806                 skb = tx_skb->skb;
807
808                 if (ctrl & MACB_BIT(TX_USED)) {
809                         /* skb is set for the last buffer of the frame */
810                         while (!skb) {
811                                 macb_tx_unmap(bp, tx_skb);
812                                 tail++;
813                                 tx_skb = macb_tx_skb(queue, tail);
814                                 skb = tx_skb->skb;
815                         }
816
817                         /* ctrl still refers to the first buffer descriptor
818                          * since it's the only one written back by the hardware
819                          */
820                         if (!(ctrl & MACB_BIT(TX_BUF_EXHAUSTED))) {
821                                 netdev_vdbg(bp->dev, "txerr skb %u (data %p) TX complete\n",
822                                             macb_tx_ring_wrap(bp, tail),
823                                             skb->data);
824                                 bp->dev->stats.tx_packets++;
825                                 bp->dev->stats.tx_bytes += skb->len;
826                         }
827                 } else {
828                         /* "Buffers exhausted mid-frame" errors may only happen
829                          * if the driver is buggy, so complain loudly about
830                          * those. Statistics are updated by hardware.
831                          */
832                         if (ctrl & MACB_BIT(TX_BUF_EXHAUSTED))
833                                 netdev_err(bp->dev,
834                                            "BUG: TX buffers exhausted mid-frame\n");
835
836                         desc->ctrl = ctrl | MACB_BIT(TX_USED);
837                 }
838
839                 macb_tx_unmap(bp, tx_skb);
840         }
841
842         /* Set end of TX queue */
843         desc = macb_tx_desc(queue, 0);
844         macb_set_addr(bp, desc, 0);
845         desc->ctrl = MACB_BIT(TX_USED);
846
847         /* Make descriptor updates visible to hardware */
848         wmb();
849
850         /* Reinitialize the TX desc queue */
851         queue_writel(queue, TBQP, lower_32_bits(queue->tx_ring_dma));
852 #ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
853         if (bp->hw_dma_cap & HW_DMA_CAP_64B)
854                 queue_writel(queue, TBQPH, upper_32_bits(queue->tx_ring_dma));
855 #endif
856         /* Make TX ring reflect state of hardware */
857         queue->tx_head = 0;
858         queue->tx_tail = 0;
859
860         /* Housework before enabling TX IRQ */
861         macb_writel(bp, TSR, macb_readl(bp, TSR));
862         queue_writel(queue, IER, MACB_TX_INT_FLAGS);
863
864         /* Now we are ready to start transmission again */
865         netif_tx_start_all_queues(bp->dev);
866         macb_writel(bp, NCR, macb_readl(bp, NCR) | MACB_BIT(TSTART));
867
868         spin_unlock_irqrestore(&bp->lock, flags);
869 }
870
871 static void macb_tx_interrupt(struct macb_queue *queue)
872 {
873         unsigned int tail;
874         unsigned int head;
875         u32 status;
876         struct macb *bp = queue->bp;
877         u16 queue_index = queue - bp->queues;
878
879         status = macb_readl(bp, TSR);
880         macb_writel(bp, TSR, status);
881
882         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
883                 queue_writel(queue, ISR, MACB_BIT(TCOMP));
884
885         netdev_vdbg(bp->dev, "macb_tx_interrupt status = 0x%03lx\n",
886                     (unsigned long)status);
887
888         head = queue->tx_head;
889         for (tail = queue->tx_tail; tail != head; tail++) {
890                 struct macb_tx_skb      *tx_skb;
891                 struct sk_buff          *skb;
892                 struct macb_dma_desc    *desc;
893                 u32                     ctrl;
894
895                 desc = macb_tx_desc(queue, tail);
896
897                 /* Make hw descriptor updates visible to CPU */
898                 rmb();
899
900                 ctrl = desc->ctrl;
901
902                 /* TX_USED bit is only set by hardware on the very first buffer
903                  * descriptor of the transmitted frame.
904                  */
905                 if (!(ctrl & MACB_BIT(TX_USED)))
906                         break;
907
908                 /* Process all buffers of the current transmitted frame */
909                 for (;; tail++) {
910                         tx_skb = macb_tx_skb(queue, tail);
911                         skb = tx_skb->skb;
912
913                         /* First, update TX stats if needed */
914                         if (skb) {
915                                 if (gem_ptp_do_txstamp(queue, skb, desc) == 0) {
916                                         /* skb now belongs to timestamp buffer
917                                          * and will be removed later
918                                          */
919                                         tx_skb->skb = NULL;
920                                 }
921                                 netdev_vdbg(bp->dev, "skb %u (data %p) TX complete\n",
922                                             macb_tx_ring_wrap(bp, tail),
923                                             skb->data);
924                                 bp->dev->stats.tx_packets++;
925                                 bp->dev->stats.tx_bytes += skb->len;
926                         }
927
928                         /* Now we can safely release resources */
929                         macb_tx_unmap(bp, tx_skb);
930
931                         /* skb is set only for the last buffer of the frame.
932                          * WARNING: at this point skb has been freed by
933                          * macb_tx_unmap().
934                          */
935                         if (skb)
936                                 break;
937                 }
938         }
939
940         queue->tx_tail = tail;
941         if (__netif_subqueue_stopped(bp->dev, queue_index) &&
942             CIRC_CNT(queue->tx_head, queue->tx_tail,
943                      bp->tx_ring_size) <= MACB_TX_WAKEUP_THRESH(bp))
944                 netif_wake_subqueue(bp->dev, queue_index);
945 }
946
947 static void gem_rx_refill(struct macb *bp)
948 {
949         unsigned int            entry;
950         struct sk_buff          *skb;
951         dma_addr_t              paddr;
952         struct macb_dma_desc *desc;
953
954         while (CIRC_SPACE(bp->rx_prepared_head, bp->rx_tail,
955                           bp->rx_ring_size) > 0) {
956                 entry = macb_rx_ring_wrap(bp, bp->rx_prepared_head);
957
958                 /* Make hw descriptor updates visible to CPU */
959                 rmb();
960
961                 bp->rx_prepared_head++;
962                 desc = macb_rx_desc(bp, entry);
963
964                 if (!bp->rx_skbuff[entry]) {
965                         /* allocate sk_buff for this free entry in ring */
966                         skb = netdev_alloc_skb(bp->dev, bp->rx_buffer_size);
967                         if (unlikely(!skb)) {
968                                 netdev_err(bp->dev,
969                                            "Unable to allocate sk_buff\n");
970                                 break;
971                         }
972
973                         /* now fill corresponding descriptor entry */
974                         paddr = dma_map_single(&bp->pdev->dev, skb->data,
975                                                bp->rx_buffer_size,
976                                                DMA_FROM_DEVICE);
977                         if (dma_mapping_error(&bp->pdev->dev, paddr)) {
978                                 dev_kfree_skb(skb);
979                                 break;
980                         }
981
982                         bp->rx_skbuff[entry] = skb;
983
984                         if (entry == bp->rx_ring_size - 1)
985                                 paddr |= MACB_BIT(RX_WRAP);
986                         macb_set_addr(bp, desc, paddr);
987                         desc->ctrl = 0;
988
989                         /* properly align Ethernet header */
990                         skb_reserve(skb, NET_IP_ALIGN);
991                 } else {
992                         desc->addr &= ~MACB_BIT(RX_USED);
993                         desc->ctrl = 0;
994                 }
995         }
996
997         /* Make descriptor updates visible to hardware */
998         wmb();
999
1000         netdev_vdbg(bp->dev, "rx ring: prepared head %d, tail %d\n",
1001                     bp->rx_prepared_head, bp->rx_tail);
1002 }
1003
1004 /* Mark DMA descriptors from begin up to and not including end as unused */
1005 static void discard_partial_frame(struct macb *bp, unsigned int begin,
1006                                   unsigned int end)
1007 {
1008         unsigned int frag;
1009
1010         for (frag = begin; frag != end; frag++) {
1011                 struct macb_dma_desc *desc = macb_rx_desc(bp, frag);
1012
1013                 desc->addr &= ~MACB_BIT(RX_USED);
1014         }
1015
1016         /* Make descriptor updates visible to hardware */
1017         wmb();
1018
1019         /* When this happens, the hardware stats registers for
1020          * whatever caused this is updated, so we don't have to record
1021          * anything.
1022          */
1023 }
1024
1025
1026 static int macb_validate_hw_csum(struct sk_buff *skb)
1027 {
1028         u32 pkt_csum = *((u32 *)&skb->data[skb->len - ETH_FCS_LEN]);
1029         u32 csum  = ~crc32_le(~0, skb_mac_header(skb),
1030                         skb->len + ETH_HLEN - ETH_FCS_LEN);
1031
1032         return (pkt_csum != csum);
1033 }
1034
1035 static int gem_rx(struct macb *bp, int budget)
1036 {
1037         unsigned int            len;
1038         unsigned int            entry;
1039         struct sk_buff          *skb;
1040         struct macb_dma_desc    *desc;
1041         int                     count = 0;
1042
1043         while (count < budget) {
1044                 u32 ctrl;
1045                 dma_addr_t addr;
1046                 bool rxused;
1047
1048                 entry = macb_rx_ring_wrap(bp, bp->rx_tail);
1049
1050                 desc = macb_rx_desc(bp, entry);
1051
1052                 /* Make hw descriptor updates visible to CPU */
1053                 rmb();
1054
1055                 rxused = (desc->addr & MACB_BIT(RX_USED)) ? true : false;
1056                 addr = macb_get_addr(bp, desc);
1057                 ctrl = desc->ctrl;
1058
1059                 if (!rxused)
1060                         break;
1061
1062                 bp->rx_tail++;
1063                 count++;
1064
1065                 if (!(ctrl & MACB_BIT(RX_SOF) && ctrl & MACB_BIT(RX_EOF))) {
1066                         netdev_err(bp->dev,
1067                                    "not whole frame pointed by descriptor\n");
1068                         bp->dev->stats.rx_dropped++;
1069                         break;
1070                 }
1071                 skb = bp->rx_skbuff[entry];
1072                 if (unlikely(!skb)) {
1073                         netdev_err(bp->dev,
1074                                    "inconsistent Rx descriptor chain\n");
1075                         bp->dev->stats.rx_dropped++;
1076                         break;
1077                 }
1078                 /* now everything is ready for receiving packet */
1079                 bp->rx_skbuff[entry] = NULL;
1080                 len = ctrl & bp->rx_frm_len_mask;
1081
1082                 netdev_vdbg(bp->dev, "gem_rx %u (len %u)\n", entry, len);
1083
1084                 skb_put(skb, len);
1085                 dma_unmap_single(&bp->pdev->dev, addr,
1086                                  bp->rx_buffer_size, DMA_FROM_DEVICE);
1087
1088                 skb->protocol = eth_type_trans(skb, bp->dev);
1089
1090                 /* Validate MAC fcs if RX checsum offload disabled */
1091                 if (!(bp->dev->features & NETIF_F_RXCSUM)) {
1092                         if (macb_validate_hw_csum(skb)) {
1093                                 netdev_err(bp->dev, "incorrect FCS\n");
1094                                 bp->dev->stats.rx_dropped++;
1095                                 break;
1096                         }
1097                 }
1098
1099                 skb_checksum_none_assert(skb);
1100                 if (bp->dev->features & NETIF_F_RXCSUM &&
1101                     !(bp->dev->flags & IFF_PROMISC) &&
1102                     GEM_BFEXT(RX_CSUM, ctrl) & GEM_RX_CSUM_CHECKED_MASK)
1103                         skb->ip_summed = CHECKSUM_UNNECESSARY;
1104
1105                 bp->dev->stats.rx_packets++;
1106                 bp->dev->stats.rx_bytes += skb->len;
1107
1108                 gem_ptp_do_rxstamp(bp, skb, desc);
1109
1110 #if defined(DEBUG) && defined(VERBOSE_DEBUG)
1111                 netdev_vdbg(bp->dev, "received skb of length %u, csum: %08x\n",
1112                             skb->len, skb->csum);
1113                 print_hex_dump(KERN_DEBUG, " mac: ", DUMP_PREFIX_ADDRESS, 16, 1,
1114                                skb_mac_header(skb), 16, true);
1115                 print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_ADDRESS, 16, 1,
1116                                skb->data, 32, true);
1117 #endif
1118
1119                 netif_receive_skb(skb);
1120         }
1121
1122         gem_rx_refill(bp);
1123
1124         return count;
1125 }
1126
1127 static int macb_rx_frame(struct macb *bp, unsigned int first_frag,
1128                          unsigned int last_frag)
1129 {
1130         unsigned int len;
1131         unsigned int frag;
1132         unsigned int offset;
1133         struct sk_buff *skb;
1134         struct macb_dma_desc *desc;
1135
1136         desc = macb_rx_desc(bp, last_frag);
1137         len = desc->ctrl & bp->rx_frm_len_mask;
1138
1139         netdev_vdbg(bp->dev, "macb_rx_frame frags %u - %u (len %u)\n",
1140                 macb_rx_ring_wrap(bp, first_frag),
1141                 macb_rx_ring_wrap(bp, last_frag), len);
1142
1143         /* The ethernet header starts NET_IP_ALIGN bytes into the
1144          * first buffer. Since the header is 14 bytes, this makes the
1145          * payload word-aligned.
1146          *
1147          * Instead of calling skb_reserve(NET_IP_ALIGN), we just copy
1148          * the two padding bytes into the skb so that we avoid hitting
1149          * the slowpath in memcpy(), and pull them off afterwards.
1150          */
1151         skb = netdev_alloc_skb(bp->dev, len + NET_IP_ALIGN);
1152         if (!skb) {
1153                 bp->dev->stats.rx_dropped++;
1154                 for (frag = first_frag; ; frag++) {
1155                         desc = macb_rx_desc(bp, frag);
1156                         desc->addr &= ~MACB_BIT(RX_USED);
1157                         if (frag == last_frag)
1158                                 break;
1159                 }
1160
1161                 /* Make descriptor updates visible to hardware */
1162                 wmb();
1163
1164                 return 1;
1165         }
1166
1167         offset = 0;
1168         len += NET_IP_ALIGN;
1169         skb_checksum_none_assert(skb);
1170         skb_put(skb, len);
1171
1172         for (frag = first_frag; ; frag++) {
1173                 unsigned int frag_len = bp->rx_buffer_size;
1174
1175                 if (offset + frag_len > len) {
1176                         if (unlikely(frag != last_frag)) {
1177                                 dev_kfree_skb_any(skb);
1178                                 return -1;
1179                         }
1180                         frag_len = len - offset;
1181                 }
1182                 skb_copy_to_linear_data_offset(skb, offset,
1183                                                macb_rx_buffer(bp, frag),
1184                                                frag_len);
1185                 offset += bp->rx_buffer_size;
1186                 desc = macb_rx_desc(bp, frag);
1187                 desc->addr &= ~MACB_BIT(RX_USED);
1188
1189                 if (frag == last_frag)
1190                         break;
1191         }
1192
1193         /* Validate MAC fcs if RX checsum offload disabled */
1194         if (!(bp->dev->features & NETIF_F_RXCSUM)) {
1195                 if (macb_validate_hw_csum(skb)) {
1196                         netdev_err(bp->dev, "incorrect FCS\n");
1197                         bp->dev->stats.rx_dropped++;
1198
1199                         /* Make descriptor updates visible to hardware */
1200                         wmb();
1201
1202                         return 1;
1203                 }
1204         }
1205
1206         /* Make descriptor updates visible to hardware */
1207         wmb();
1208
1209         __skb_pull(skb, NET_IP_ALIGN);
1210         skb->protocol = eth_type_trans(skb, bp->dev);
1211
1212         bp->dev->stats.rx_packets++;
1213         bp->dev->stats.rx_bytes += skb->len;
1214         netdev_vdbg(bp->dev, "received skb of length %u, csum: %08x\n",
1215                     skb->len, skb->csum);
1216         netif_receive_skb(skb);
1217
1218         return 0;
1219 }
1220
1221 static inline void macb_init_rx_ring(struct macb *bp)
1222 {
1223         dma_addr_t addr;
1224         struct macb_dma_desc *desc = NULL;
1225         int i;
1226
1227         addr = bp->rx_buffers_dma;
1228         for (i = 0; i < bp->rx_ring_size; i++) {
1229                 desc = macb_rx_desc(bp, i);
1230                 macb_set_addr(bp, desc, addr);
1231                 desc->ctrl = 0;
1232                 addr += bp->rx_buffer_size;
1233         }
1234         desc->addr |= MACB_BIT(RX_WRAP);
1235         bp->rx_tail = 0;
1236 }
1237
1238 static int macb_rx(struct macb *bp, int budget)
1239 {
1240         bool reset_rx_queue = false;
1241         int received = 0;
1242         unsigned int tail;
1243         int first_frag = -1;
1244
1245         for (tail = bp->rx_tail; budget > 0; tail++) {
1246                 struct macb_dma_desc *desc = macb_rx_desc(bp, tail);
1247                 u32 ctrl;
1248
1249                 /* Make hw descriptor updates visible to CPU */
1250                 rmb();
1251
1252                 ctrl = desc->ctrl;
1253
1254                 if (!(desc->addr & MACB_BIT(RX_USED)))
1255                         break;
1256
1257                 if (ctrl & MACB_BIT(RX_SOF)) {
1258                         if (first_frag != -1)
1259                                 discard_partial_frame(bp, first_frag, tail);
1260                         first_frag = tail;
1261                 }
1262
1263                 if (ctrl & MACB_BIT(RX_EOF)) {
1264                         int dropped;
1265
1266                         if (unlikely(first_frag == -1)) {
1267                                 reset_rx_queue = true;
1268                                 continue;
1269                         }
1270
1271                         dropped = macb_rx_frame(bp, first_frag, tail);
1272                         first_frag = -1;
1273                         if (unlikely(dropped < 0)) {
1274                                 reset_rx_queue = true;
1275                                 continue;
1276                         }
1277                         if (!dropped) {
1278                                 received++;
1279                                 budget--;
1280                         }
1281                 }
1282         }
1283
1284         if (unlikely(reset_rx_queue)) {
1285                 unsigned long flags;
1286                 u32 ctrl;
1287
1288                 netdev_err(bp->dev, "RX queue corruption: reset it\n");
1289
1290                 spin_lock_irqsave(&bp->lock, flags);
1291
1292                 ctrl = macb_readl(bp, NCR);
1293                 macb_writel(bp, NCR, ctrl & ~MACB_BIT(RE));
1294
1295                 macb_init_rx_ring(bp);
1296                 macb_writel(bp, RBQP, bp->rx_ring_dma);
1297
1298                 macb_writel(bp, NCR, ctrl | MACB_BIT(RE));
1299
1300                 spin_unlock_irqrestore(&bp->lock, flags);
1301                 return received;
1302         }
1303
1304         if (first_frag != -1)
1305                 bp->rx_tail = first_frag;
1306         else
1307                 bp->rx_tail = tail;
1308
1309         return received;
1310 }
1311
1312 static int macb_poll(struct napi_struct *napi, int budget)
1313 {
1314         struct macb *bp = container_of(napi, struct macb, napi);
1315         int work_done;
1316         u32 status;
1317
1318         status = macb_readl(bp, RSR);
1319         macb_writel(bp, RSR, status);
1320
1321         work_done = 0;
1322
1323         netdev_vdbg(bp->dev, "poll: status = %08lx, budget = %d\n",
1324                     (unsigned long)status, budget);
1325
1326         work_done = bp->macbgem_ops.mog_rx(bp, budget);
1327         if (work_done < budget) {
1328                 napi_complete(napi);
1329
1330                 /* Packets received while interrupts were disabled */
1331                 status = macb_readl(bp, RSR);
1332                 if (status) {
1333                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1334                                 macb_writel(bp, ISR, MACB_BIT(RCOMP));
1335                         napi_reschedule(napi);
1336                 } else {
1337                         macb_writel(bp, IER, MACB_RX_INT_FLAGS);
1338                 }
1339         }
1340
1341         /* TODO: Handle errors */
1342
1343         return work_done;
1344 }
1345
1346 static void macb_hresp_error_task(unsigned long data)
1347 {
1348         struct macb *bp = (struct macb *)data;
1349         struct net_device *dev = bp->dev;
1350         struct macb_queue *queue = bp->queues;
1351         unsigned int q;
1352         u32 ctrl;
1353
1354         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) {
1355                 queue_writel(queue, IDR, MACB_RX_INT_FLAGS |
1356                                          MACB_TX_INT_FLAGS |
1357                                          MACB_BIT(HRESP));
1358         }
1359         ctrl = macb_readl(bp, NCR);
1360         ctrl &= ~(MACB_BIT(RE) | MACB_BIT(TE));
1361         macb_writel(bp, NCR, ctrl);
1362
1363         netif_tx_stop_all_queues(dev);
1364         netif_carrier_off(dev);
1365
1366         bp->macbgem_ops.mog_init_rings(bp);
1367
1368         macb_writel(bp, RBQP, lower_32_bits(bp->rx_ring_dma));
1369 #ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
1370         if (bp->hw_dma_cap & HW_DMA_CAP_64B)
1371                 macb_writel(bp, RBQPH, upper_32_bits(bp->rx_ring_dma));
1372 #endif
1373         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) {
1374                 queue_writel(queue, TBQP, lower_32_bits(queue->tx_ring_dma));
1375 #ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
1376                 if (bp->hw_dma_cap & HW_DMA_CAP_64B)
1377                         queue_writel(queue, TBQPH, upper_32_bits(queue->tx_ring_dma));
1378 #endif
1379                 /* We only use the first queue at the moment. Remaining
1380                  * queues must be tied-off before we enable the receiver.
1381                  *
1382                  * See the documentation for receive_q1_ptr for more info.
1383                  */
1384                 if (q)
1385                         queue_writel(queue, RBQP,
1386                                      lower_32_bits(bp->rx_ring_tieoff_dma));
1387
1388                 /* Enable interrupts */
1389                 queue_writel(queue, IER,
1390                              MACB_RX_INT_FLAGS |
1391                              MACB_TX_INT_FLAGS |
1392                              MACB_BIT(HRESP));
1393         }
1394
1395         ctrl |= MACB_BIT(RE) | MACB_BIT(TE);
1396         macb_writel(bp, NCR, ctrl);
1397
1398         netif_carrier_on(dev);
1399         netif_tx_start_all_queues(dev);
1400 }
1401
1402 static irqreturn_t macb_interrupt(int irq, void *dev_id)
1403 {
1404         struct macb_queue *queue = dev_id;
1405         struct macb *bp = queue->bp;
1406         struct net_device *dev = bp->dev;
1407         u32 status, ctrl;
1408
1409         status = queue_readl(queue, ISR);
1410
1411         if (unlikely(!status))
1412                 return IRQ_NONE;
1413
1414         spin_lock(&bp->lock);
1415
1416         while (status) {
1417                 if (status & MACB_BIT(WOL)) {
1418                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1419                                 queue_writel(queue, ISR, MACB_BIT(WOL));
1420                         break;
1421                 }
1422
1423                 /* close possible race with dev_close */
1424                 if (unlikely(!netif_running(dev))) {
1425                         queue_writel(queue, IDR, -1);
1426                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1427                                 queue_writel(queue, ISR, -1);
1428                         break;
1429                 }
1430
1431                 netdev_vdbg(bp->dev, "queue = %u, isr = 0x%08lx\n",
1432                             (unsigned int)(queue - bp->queues),
1433                             (unsigned long)status);
1434
1435                 if (status & MACB_RX_INT_FLAGS) {
1436                         /* There's no point taking any more interrupts
1437                          * until we have processed the buffers. The
1438                          * scheduling call may fail if the poll routine
1439                          * is already scheduled, so disable interrupts
1440                          * now.
1441                          */
1442                         queue_writel(queue, IDR, MACB_RX_INT_FLAGS);
1443                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1444                                 queue_writel(queue, ISR, MACB_BIT(RCOMP));
1445
1446                         if (napi_schedule_prep(&bp->napi)) {
1447                                 netdev_vdbg(bp->dev, "scheduling RX softirq\n");
1448                                 __napi_schedule(&bp->napi);
1449                         }
1450                 }
1451
1452                 if (unlikely(status & (MACB_TX_ERR_FLAGS))) {
1453                         queue_writel(queue, IDR, MACB_TX_INT_FLAGS);
1454                         schedule_work(&queue->tx_error_task);
1455
1456                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1457                                 queue_writel(queue, ISR, MACB_TX_ERR_FLAGS);
1458
1459                         break;
1460                 }
1461
1462                 if (status & MACB_BIT(TCOMP))
1463                         macb_tx_interrupt(queue);
1464
1465                 /* Link change detection isn't possible with RMII, so we'll
1466                  * add that if/when we get our hands on a full-blown MII PHY.
1467                  */
1468
1469                 /* There is a hardware issue under heavy load where DMA can
1470                  * stop, this causes endless "used buffer descriptor read"
1471                  * interrupts but it can be cleared by re-enabling RX. See
1472                  * the at91 manual, section 41.3.1 or the Zynq manual
1473                  * section 16.7.4 for details.
1474                  */
1475                 if (status & MACB_BIT(RXUBR)) {
1476                         ctrl = macb_readl(bp, NCR);
1477                         macb_writel(bp, NCR, ctrl & ~MACB_BIT(RE));
1478                         wmb();
1479                         macb_writel(bp, NCR, ctrl | MACB_BIT(RE));
1480
1481                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1482                                 queue_writel(queue, ISR, MACB_BIT(RXUBR));
1483                 }
1484
1485                 if (status & MACB_BIT(ISR_ROVR)) {
1486                         /* We missed at least one packet */
1487                         if (macb_is_gem(bp))
1488                                 bp->hw_stats.gem.rx_overruns++;
1489                         else
1490                                 bp->hw_stats.macb.rx_overruns++;
1491
1492                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1493                                 queue_writel(queue, ISR, MACB_BIT(ISR_ROVR));
1494                 }
1495
1496                 if (status & MACB_BIT(HRESP)) {
1497                         tasklet_schedule(&bp->hresp_err_tasklet);
1498                         netdev_err(dev, "DMA bus error: HRESP not OK\n");
1499
1500                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1501                                 queue_writel(queue, ISR, MACB_BIT(HRESP));
1502                 }
1503                 status = queue_readl(queue, ISR);
1504         }
1505
1506         spin_unlock(&bp->lock);
1507
1508         return IRQ_HANDLED;
1509 }
1510
1511 #ifdef CONFIG_NET_POLL_CONTROLLER
1512 /* Polling receive - used by netconsole and other diagnostic tools
1513  * to allow network i/o with interrupts disabled.
1514  */
1515 static void macb_poll_controller(struct net_device *dev)
1516 {
1517         struct macb *bp = netdev_priv(dev);
1518         struct macb_queue *queue;
1519         unsigned long flags;
1520         unsigned int q;
1521
1522         local_irq_save(flags);
1523         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue)
1524                 macb_interrupt(dev->irq, queue);
1525         local_irq_restore(flags);
1526 }
1527 #endif
1528
1529 static unsigned int macb_tx_map(struct macb *bp,
1530                                 struct macb_queue *queue,
1531                                 struct sk_buff *skb,
1532                                 unsigned int hdrlen)
1533 {
1534         dma_addr_t mapping;
1535         unsigned int len, entry, i, tx_head = queue->tx_head;
1536         struct macb_tx_skb *tx_skb = NULL;
1537         struct macb_dma_desc *desc;
1538         unsigned int offset, size, count = 0;
1539         unsigned int f, nr_frags = skb_shinfo(skb)->nr_frags;
1540         unsigned int eof = 1, mss_mfs = 0;
1541         u32 ctrl, lso_ctrl = 0, seq_ctrl = 0;
1542
1543         /* LSO */
1544         if (skb_shinfo(skb)->gso_size != 0) {
1545                 if (ip_hdr(skb)->protocol == IPPROTO_UDP)
1546                         /* UDP - UFO */
1547                         lso_ctrl = MACB_LSO_UFO_ENABLE;
1548                 else
1549                         /* TCP - TSO */
1550                         lso_ctrl = MACB_LSO_TSO_ENABLE;
1551         }
1552
1553         /* First, map non-paged data */
1554         len = skb_headlen(skb);
1555
1556         /* first buffer length */
1557         size = hdrlen;
1558
1559         offset = 0;
1560         while (len) {
1561                 entry = macb_tx_ring_wrap(bp, tx_head);
1562                 tx_skb = &queue->tx_skb[entry];
1563
1564                 mapping = dma_map_single(&bp->pdev->dev,
1565                                          skb->data + offset,
1566                                          size, DMA_TO_DEVICE);
1567                 if (dma_mapping_error(&bp->pdev->dev, mapping))
1568                         goto dma_error;
1569
1570                 /* Save info to properly release resources */
1571                 tx_skb->skb = NULL;
1572                 tx_skb->mapping = mapping;
1573                 tx_skb->size = size;
1574                 tx_skb->mapped_as_page = false;
1575
1576                 len -= size;
1577                 offset += size;
1578                 count++;
1579                 tx_head++;
1580
1581                 size = min(len, bp->max_tx_length);
1582         }
1583
1584         /* Then, map paged data from fragments */
1585         for (f = 0; f < nr_frags; f++) {
1586                 const skb_frag_t *frag = &skb_shinfo(skb)->frags[f];
1587
1588                 len = skb_frag_size(frag);
1589                 offset = 0;
1590                 while (len) {
1591                         size = min(len, bp->max_tx_length);
1592                         entry = macb_tx_ring_wrap(bp, tx_head);
1593                         tx_skb = &queue->tx_skb[entry];
1594
1595                         mapping = skb_frag_dma_map(&bp->pdev->dev, frag,
1596                                                    offset, size, DMA_TO_DEVICE);
1597                         if (dma_mapping_error(&bp->pdev->dev, mapping))
1598                                 goto dma_error;
1599
1600                         /* Save info to properly release resources */
1601                         tx_skb->skb = NULL;
1602                         tx_skb->mapping = mapping;
1603                         tx_skb->size = size;
1604                         tx_skb->mapped_as_page = true;
1605
1606                         len -= size;
1607                         offset += size;
1608                         count++;
1609                         tx_head++;
1610                 }
1611         }
1612
1613         /* Should never happen */
1614         if (unlikely(!tx_skb)) {
1615                 netdev_err(bp->dev, "BUG! empty skb!\n");
1616                 return 0;
1617         }
1618
1619         /* This is the last buffer of the frame: save socket buffer */
1620         tx_skb->skb = skb;
1621
1622         /* Update TX ring: update buffer descriptors in reverse order
1623          * to avoid race condition
1624          */
1625
1626         /* Set 'TX_USED' bit in buffer descriptor at tx_head position
1627          * to set the end of TX queue
1628          */
1629         i = tx_head;
1630         entry = macb_tx_ring_wrap(bp, i);
1631         ctrl = MACB_BIT(TX_USED);
1632         desc = macb_tx_desc(queue, entry);
1633         desc->ctrl = ctrl;
1634
1635         if (lso_ctrl) {
1636                 if (lso_ctrl == MACB_LSO_UFO_ENABLE)
1637                         /* include header and FCS in value given to h/w */
1638                         mss_mfs = skb_shinfo(skb)->gso_size +
1639                                         skb_transport_offset(skb) +
1640                                         ETH_FCS_LEN;
1641                 else /* TSO */ {
1642                         mss_mfs = skb_shinfo(skb)->gso_size;
1643                         /* TCP Sequence Number Source Select
1644                          * can be set only for TSO
1645                          */
1646                         seq_ctrl = 0;
1647                 }
1648         }
1649
1650         do {
1651                 i--;
1652                 entry = macb_tx_ring_wrap(bp, i);
1653                 tx_skb = &queue->tx_skb[entry];
1654                 desc = macb_tx_desc(queue, entry);
1655
1656                 ctrl = (u32)tx_skb->size;
1657                 if (eof) {
1658                         ctrl |= MACB_BIT(TX_LAST);
1659                         eof = 0;
1660                 }
1661                 if (unlikely(entry == (bp->tx_ring_size - 1)))
1662                         ctrl |= MACB_BIT(TX_WRAP);
1663
1664                 /* First descriptor is header descriptor */
1665                 if (i == queue->tx_head) {
1666                         ctrl |= MACB_BF(TX_LSO, lso_ctrl);
1667                         ctrl |= MACB_BF(TX_TCP_SEQ_SRC, seq_ctrl);
1668                 } else
1669                         /* Only set MSS/MFS on payload descriptors
1670                          * (second or later descriptor)
1671                          */
1672                         ctrl |= MACB_BF(MSS_MFS, mss_mfs);
1673
1674                 /* Set TX buffer descriptor */
1675                 macb_set_addr(bp, desc, tx_skb->mapping);
1676                 /* desc->addr must be visible to hardware before clearing
1677                  * 'TX_USED' bit in desc->ctrl.
1678                  */
1679                 wmb();
1680                 desc->ctrl = ctrl;
1681         } while (i != queue->tx_head);
1682
1683         queue->tx_head = tx_head;
1684
1685         return count;
1686
1687 dma_error:
1688         netdev_err(bp->dev, "TX DMA map failed\n");
1689
1690         for (i = queue->tx_head; i != tx_head; i++) {
1691                 tx_skb = macb_tx_skb(queue, i);
1692
1693                 macb_tx_unmap(bp, tx_skb);
1694         }
1695
1696         return 0;
1697 }
1698
1699 static netdev_features_t macb_features_check(struct sk_buff *skb,
1700                                              struct net_device *dev,
1701                                              netdev_features_t features)
1702 {
1703         unsigned int nr_frags, f;
1704         unsigned int hdrlen;
1705
1706         /* Validate LSO compatibility */
1707
1708         /* there is only one buffer */
1709         if (!skb_is_nonlinear(skb))
1710                 return features;
1711
1712         /* length of header */
1713         hdrlen = skb_transport_offset(skb);
1714         if (ip_hdr(skb)->protocol == IPPROTO_TCP)
1715                 hdrlen += tcp_hdrlen(skb);
1716
1717         /* For LSO:
1718          * When software supplies two or more payload buffers all payload buffers
1719          * apart from the last must be a multiple of 8 bytes in size.
1720          */
1721         if (!IS_ALIGNED(skb_headlen(skb) - hdrlen, MACB_TX_LEN_ALIGN))
1722                 return features & ~MACB_NETIF_LSO;
1723
1724         nr_frags = skb_shinfo(skb)->nr_frags;
1725         /* No need to check last fragment */
1726         nr_frags--;
1727         for (f = 0; f < nr_frags; f++) {
1728                 const skb_frag_t *frag = &skb_shinfo(skb)->frags[f];
1729
1730                 if (!IS_ALIGNED(skb_frag_size(frag), MACB_TX_LEN_ALIGN))
1731                         return features & ~MACB_NETIF_LSO;
1732         }
1733         return features;
1734 }
1735
1736 static inline int macb_clear_csum(struct sk_buff *skb)
1737 {
1738         /* no change for packets without checksum offloading */
1739         if (skb->ip_summed != CHECKSUM_PARTIAL)
1740                 return 0;
1741
1742         /* make sure we can modify the header */
1743         if (unlikely(skb_cow_head(skb, 0)))
1744                 return -1;
1745
1746         /* initialize checksum field
1747          * This is required - at least for Zynq, which otherwise calculates
1748          * wrong UDP header checksums for UDP packets with UDP data len <=2
1749          */
1750         *(__sum16 *)(skb_checksum_start(skb) + skb->csum_offset) = 0;
1751         return 0;
1752 }
1753
1754 static int macb_start_xmit(struct sk_buff *skb, struct net_device *dev)
1755 {
1756         u16 queue_index = skb_get_queue_mapping(skb);
1757         struct macb *bp = netdev_priv(dev);
1758         struct macb_queue *queue = &bp->queues[queue_index];
1759         unsigned long flags;
1760         unsigned int desc_cnt, nr_frags, frag_size, f;
1761         unsigned int hdrlen;
1762         bool is_lso, is_udp = 0;
1763
1764         is_lso = (skb_shinfo(skb)->gso_size != 0);
1765
1766         if (is_lso) {
1767                 is_udp = !!(ip_hdr(skb)->protocol == IPPROTO_UDP);
1768
1769                 /* length of headers */
1770                 if (is_udp)
1771                         /* only queue eth + ip headers separately for UDP */
1772                         hdrlen = skb_transport_offset(skb);
1773                 else
1774                         hdrlen = skb_transport_offset(skb) + tcp_hdrlen(skb);
1775                 if (skb_headlen(skb) < hdrlen) {
1776                         netdev_err(bp->dev, "Error - LSO headers fragmented!!!\n");
1777                         /* if this is required, would need to copy to single buffer */
1778                         return NETDEV_TX_BUSY;
1779                 }
1780         } else
1781                 hdrlen = min(skb_headlen(skb), bp->max_tx_length);
1782
1783 #if defined(DEBUG) && defined(VERBOSE_DEBUG)
1784         netdev_vdbg(bp->dev,
1785                     "start_xmit: queue %hu len %u head %p data %p tail %p end %p\n",
1786                     queue_index, skb->len, skb->head, skb->data,
1787                     skb_tail_pointer(skb), skb_end_pointer(skb));
1788         print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_OFFSET, 16, 1,
1789                        skb->data, 16, true);
1790 #endif
1791
1792         /* Count how many TX buffer descriptors are needed to send this
1793          * socket buffer: skb fragments of jumbo frames may need to be
1794          * split into many buffer descriptors.
1795          */
1796         if (is_lso && (skb_headlen(skb) > hdrlen))
1797                 /* extra header descriptor if also payload in first buffer */
1798                 desc_cnt = DIV_ROUND_UP((skb_headlen(skb) - hdrlen), bp->max_tx_length) + 1;
1799         else
1800                 desc_cnt = DIV_ROUND_UP(skb_headlen(skb), bp->max_tx_length);
1801         nr_frags = skb_shinfo(skb)->nr_frags;
1802         for (f = 0; f < nr_frags; f++) {
1803                 frag_size = skb_frag_size(&skb_shinfo(skb)->frags[f]);
1804                 desc_cnt += DIV_ROUND_UP(frag_size, bp->max_tx_length);
1805         }
1806
1807         spin_lock_irqsave(&bp->lock, flags);
1808
1809         /* This is a hard error, log it. */
1810         if (CIRC_SPACE(queue->tx_head, queue->tx_tail,
1811                        bp->tx_ring_size) < desc_cnt) {
1812                 netif_stop_subqueue(dev, queue_index);
1813                 spin_unlock_irqrestore(&bp->lock, flags);
1814                 netdev_dbg(bp->dev, "tx_head = %u, tx_tail = %u\n",
1815                            queue->tx_head, queue->tx_tail);
1816                 return NETDEV_TX_BUSY;
1817         }
1818
1819         if (macb_clear_csum(skb)) {
1820                 dev_kfree_skb_any(skb);
1821                 goto unlock;
1822         }
1823
1824         /* Map socket buffer for DMA transfer */
1825         if (!macb_tx_map(bp, queue, skb, hdrlen)) {
1826                 dev_kfree_skb_any(skb);
1827                 goto unlock;
1828         }
1829
1830         /* Make newly initialized descriptor visible to hardware */
1831         wmb();
1832         skb_tx_timestamp(skb);
1833
1834         macb_writel(bp, NCR, macb_readl(bp, NCR) | MACB_BIT(TSTART));
1835
1836         if (CIRC_SPACE(queue->tx_head, queue->tx_tail, bp->tx_ring_size) < 1)
1837                 netif_stop_subqueue(dev, queue_index);
1838
1839 unlock:
1840         spin_unlock_irqrestore(&bp->lock, flags);
1841
1842         return NETDEV_TX_OK;
1843 }
1844
1845 static void macb_init_rx_buffer_size(struct macb *bp, size_t size)
1846 {
1847         if (!macb_is_gem(bp)) {
1848                 bp->rx_buffer_size = MACB_RX_BUFFER_SIZE;
1849         } else {
1850                 bp->rx_buffer_size = size;
1851
1852                 if (bp->rx_buffer_size % RX_BUFFER_MULTIPLE) {
1853                         netdev_dbg(bp->dev,
1854                                    "RX buffer must be multiple of %d bytes, expanding\n",
1855                                    RX_BUFFER_MULTIPLE);
1856                         bp->rx_buffer_size =
1857                                 roundup(bp->rx_buffer_size, RX_BUFFER_MULTIPLE);
1858                 }
1859         }
1860
1861         netdev_dbg(bp->dev, "mtu [%u] rx_buffer_size [%Zu]\n",
1862                    bp->dev->mtu, bp->rx_buffer_size);
1863 }
1864
1865 static void gem_free_rx_buffers(struct macb *bp)
1866 {
1867         struct sk_buff          *skb;
1868         struct macb_dma_desc    *desc;
1869         dma_addr_t              addr;
1870         int i;
1871
1872         if (!bp->rx_skbuff)
1873                 return;
1874
1875         for (i = 0; i < bp->rx_ring_size; i++) {
1876                 skb = bp->rx_skbuff[i];
1877
1878                 if (!skb)
1879                         continue;
1880
1881                 desc = macb_rx_desc(bp, i);
1882                 addr = macb_get_addr(bp, desc);
1883
1884                 dma_unmap_single(&bp->pdev->dev, addr, bp->rx_buffer_size,
1885                                  DMA_FROM_DEVICE);
1886                 dev_kfree_skb_any(skb);
1887                 skb = NULL;
1888         }
1889
1890         kfree(bp->rx_skbuff);
1891         bp->rx_skbuff = NULL;
1892 }
1893
1894 static void macb_free_rx_buffers(struct macb *bp)
1895 {
1896         if (bp->rx_buffers) {
1897                 dma_free_coherent(&bp->pdev->dev,
1898                                   bp->rx_ring_size * bp->rx_buffer_size,
1899                                   bp->rx_buffers, bp->rx_buffers_dma);
1900                 bp->rx_buffers = NULL;
1901         }
1902 }
1903
1904 static void macb_free_consistent(struct macb *bp)
1905 {
1906         struct macb_queue *queue;
1907         unsigned int q;
1908
1909         bp->macbgem_ops.mog_free_rx_buffers(bp);
1910         if (bp->rx_ring) {
1911                 dma_free_coherent(&bp->pdev->dev, RX_RING_BYTES(bp),
1912                                   bp->rx_ring, bp->rx_ring_dma);
1913                 bp->rx_ring = NULL;
1914         }
1915
1916         if (bp->rx_ring_tieoff) {
1917                 dma_free_coherent(&bp->pdev->dev, macb_dma_desc_get_size(bp),
1918                                   bp->rx_ring_tieoff, bp->rx_ring_tieoff_dma);
1919                 bp->rx_ring_tieoff = NULL;
1920         }
1921
1922         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) {
1923                 kfree(queue->tx_skb);
1924                 queue->tx_skb = NULL;
1925                 if (queue->tx_ring) {
1926                         dma_free_coherent(&bp->pdev->dev, TX_RING_BYTES(bp),
1927                                           queue->tx_ring, queue->tx_ring_dma);
1928                         queue->tx_ring = NULL;
1929                 }
1930         }
1931 }
1932
1933 static int gem_alloc_rx_buffers(struct macb *bp)
1934 {
1935         int size;
1936
1937         size = bp->rx_ring_size * sizeof(struct sk_buff *);
1938         bp->rx_skbuff = kzalloc(size, GFP_KERNEL);
1939         if (!bp->rx_skbuff)
1940                 return -ENOMEM;
1941         else
1942                 netdev_dbg(bp->dev,
1943                            "Allocated %d RX struct sk_buff entries at %p\n",
1944                            bp->rx_ring_size, bp->rx_skbuff);
1945         return 0;
1946 }
1947
1948 static int macb_alloc_rx_buffers(struct macb *bp)
1949 {
1950         int size;
1951
1952         size = bp->rx_ring_size * bp->rx_buffer_size;
1953         bp->rx_buffers = dma_alloc_coherent(&bp->pdev->dev, size,
1954                                             &bp->rx_buffers_dma, GFP_KERNEL);
1955         if (!bp->rx_buffers)
1956                 return -ENOMEM;
1957
1958         netdev_dbg(bp->dev,
1959                    "Allocated RX buffers of %d bytes at %08lx (mapped %p)\n",
1960                    size, (unsigned long)bp->rx_buffers_dma, bp->rx_buffers);
1961         return 0;
1962 }
1963
1964 static int macb_alloc_consistent(struct macb *bp)
1965 {
1966         struct macb_queue *queue;
1967         unsigned int q;
1968         int size;
1969
1970         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) {
1971                 size = TX_RING_BYTES(bp);
1972                 queue->tx_ring = dma_alloc_coherent(&bp->pdev->dev, size,
1973                                                     &queue->tx_ring_dma,
1974                                                     GFP_KERNEL);
1975                 if (!queue->tx_ring)
1976                         goto out_err;
1977                 netdev_dbg(bp->dev,
1978                            "Allocated TX ring for queue %u of %d bytes at %08lx (mapped %p)\n",
1979                            q, size, (unsigned long)queue->tx_ring_dma,
1980                            queue->tx_ring);
1981
1982                 size = bp->tx_ring_size * sizeof(struct macb_tx_skb);
1983                 queue->tx_skb = kmalloc(size, GFP_KERNEL);
1984                 if (!queue->tx_skb)
1985                         goto out_err;
1986         }
1987
1988         size = RX_RING_BYTES(bp);
1989         bp->rx_ring = dma_alloc_coherent(&bp->pdev->dev, size,
1990                                          &bp->rx_ring_dma, GFP_KERNEL);
1991         if (!bp->rx_ring)
1992                 goto out_err;
1993
1994         /* If we have more than one queue, allocate a tie off descriptor
1995          * that will be used to disable unused RX queues.
1996          */
1997         if (bp->num_queues > 1) {
1998                 bp->rx_ring_tieoff = dma_alloc_coherent(&bp->pdev->dev,
1999                                                 macb_dma_desc_get_size(bp),
2000                                                 &bp->rx_ring_tieoff_dma,
2001                                                 GFP_KERNEL);
2002                 if (!bp->rx_ring_tieoff)
2003                         goto out_err;
2004         }
2005
2006         netdev_dbg(bp->dev,
2007                    "Allocated RX ring of %d bytes at %08lx (mapped %p)\n",
2008                    size, (unsigned long)bp->rx_ring_dma, bp->rx_ring);
2009
2010         if (bp->macbgem_ops.mog_alloc_rx_buffers(bp))
2011                 goto out_err;
2012
2013         return 0;
2014
2015 out_err:
2016         macb_free_consistent(bp);
2017         return -ENOMEM;
2018 }
2019
2020 static void macb_init_tieoff(struct macb *bp)
2021 {
2022         struct macb_dma_desc *d = bp->rx_ring_tieoff;
2023
2024         if (bp->num_queues > 1) {
2025                 /* Setup a wrapping descriptor with no free slots
2026                  * (WRAP and USED) to tie off/disable unused RX queues.
2027                  */
2028                 macb_set_addr(bp, d, MACB_BIT(RX_WRAP) | MACB_BIT(RX_USED));
2029                 d->ctrl = 0;
2030         }
2031 }
2032
2033 static void gem_init_rings(struct macb *bp)
2034 {
2035         struct macb_queue *queue;
2036         struct macb_dma_desc *desc = NULL;
2037         unsigned int q;
2038         int i;
2039
2040         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) {
2041                 for (i = 0; i < bp->tx_ring_size; i++) {
2042                         desc = macb_tx_desc(queue, i);
2043                         macb_set_addr(bp, desc, 0);
2044                         desc->ctrl = MACB_BIT(TX_USED);
2045                 }
2046                 desc->ctrl |= MACB_BIT(TX_WRAP);
2047                 queue->tx_head = 0;
2048                 queue->tx_tail = 0;
2049         }
2050
2051         bp->rx_tail = 0;
2052         bp->rx_prepared_head = 0;
2053
2054         gem_rx_refill(bp);
2055         macb_init_tieoff(bp);
2056 }
2057
2058 static void macb_init_rings(struct macb *bp)
2059 {
2060         int i;
2061         struct macb_dma_desc *desc = NULL;
2062
2063         macb_init_rx_ring(bp);
2064
2065         for (i = 0; i < bp->tx_ring_size; i++) {
2066                 desc = macb_tx_desc(&bp->queues[0], i);
2067                 macb_set_addr(bp, desc, 0);
2068                 desc->ctrl = MACB_BIT(TX_USED);
2069         }
2070         bp->queues[0].tx_head = 0;
2071         bp->queues[0].tx_tail = 0;
2072         desc->ctrl |= MACB_BIT(TX_WRAP);
2073
2074         bp->rx_tail = 0;
2075         macb_init_tieoff(bp);
2076 }
2077
2078 static void macb_reset_hw(struct macb *bp)
2079 {
2080         struct macb_queue *queue;
2081         unsigned int q;
2082
2083         /* Disable RX and TX (XXX: Should we halt the transmission
2084          * more gracefully?)
2085          */
2086         macb_writel(bp, NCR, 0);
2087
2088         /* Clear the stats registers (XXX: Update stats first?) */
2089         macb_writel(bp, NCR, MACB_BIT(CLRSTAT));
2090
2091         /* Clear all status flags */
2092         macb_writel(bp, TSR, -1);
2093         macb_writel(bp, RSR, -1);
2094
2095         /* Disable RX partial store and forward and reset watermark value */
2096         if (bp->caps & MACB_CAPS_PARTIAL_STORE_FORWARD)
2097                 gem_writel(bp, PBUFRXCUT, 0xFFF);
2098
2099         /* Disable all interrupts */
2100         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) {
2101                 queue_writel(queue, IDR, -1);
2102                 queue_readl(queue, ISR);
2103                 if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
2104                         queue_writel(queue, ISR, -1);
2105         }
2106 }
2107
2108 static u32 gem_mdc_clk_div(struct macb *bp)
2109 {
2110         u32 config;
2111         unsigned long pclk_hz = clk_get_rate(bp->pclk);
2112
2113         if (pclk_hz <= 20000000)
2114                 config = GEM_BF(CLK, GEM_CLK_DIV8);
2115         else if (pclk_hz <= 40000000)
2116                 config = GEM_BF(CLK, GEM_CLK_DIV16);
2117         else if (pclk_hz <= 80000000)
2118                 config = GEM_BF(CLK, GEM_CLK_DIV32);
2119         else if (pclk_hz <= 120000000)
2120                 config = GEM_BF(CLK, GEM_CLK_DIV48);
2121         else if (pclk_hz <= 160000000)
2122                 config = GEM_BF(CLK, GEM_CLK_DIV64);
2123         else
2124                 config = GEM_BF(CLK, GEM_CLK_DIV96);
2125
2126         return config;
2127 }
2128
2129 static u32 macb_mdc_clk_div(struct macb *bp)
2130 {
2131         u32 config;
2132         unsigned long pclk_hz;
2133
2134         if (macb_is_gem(bp))
2135                 return gem_mdc_clk_div(bp);
2136
2137         pclk_hz = clk_get_rate(bp->pclk);
2138         if (pclk_hz <= 20000000)
2139                 config = MACB_BF(CLK, MACB_CLK_DIV8);
2140         else if (pclk_hz <= 40000000)
2141                 config = MACB_BF(CLK, MACB_CLK_DIV16);
2142         else if (pclk_hz <= 80000000)
2143                 config = MACB_BF(CLK, MACB_CLK_DIV32);
2144         else
2145                 config = MACB_BF(CLK, MACB_CLK_DIV64);
2146
2147         return config;
2148 }
2149
2150 /* Get the DMA bus width field of the network configuration register that we
2151  * should program.  We find the width from decoding the design configuration
2152  * register to find the maximum supported data bus width.
2153  */
2154 static u32 macb_dbw(struct macb *bp)
2155 {
2156         if (!macb_is_gem(bp))
2157                 return 0;
2158
2159         switch (GEM_BFEXT(DBWDEF, gem_readl(bp, DCFG1))) {
2160         case 4:
2161                 return GEM_BF(DBW, GEM_DBW128);
2162         case 2:
2163                 return GEM_BF(DBW, GEM_DBW64);
2164         case 1:
2165         default:
2166                 return GEM_BF(DBW, GEM_DBW32);
2167         }
2168 }
2169
2170 /* Configure the receive DMA engine
2171  * - use the correct receive buffer size
2172  * - set best burst length for DMA operations
2173  *   (if not supported by FIFO, it will fallback to default)
2174  * - set both rx/tx packet buffers to full memory size
2175  * These are configurable parameters for GEM.
2176  */
2177 static void macb_configure_dma(struct macb *bp)
2178 {
2179         u32 dmacfg;
2180
2181         if (macb_is_gem(bp)) {
2182                 dmacfg = gem_readl(bp, DMACFG) & ~GEM_BF(RXBS, -1L);
2183                 dmacfg |= GEM_BF(RXBS, bp->rx_buffer_size / RX_BUFFER_MULTIPLE);
2184                 if (bp->dma_burst_length)
2185                         dmacfg = GEM_BFINS(FBLDO, bp->dma_burst_length, dmacfg);
2186                 dmacfg |= GEM_BIT(TXPBMS) | GEM_BF(RXBMS, -1L);
2187                 dmacfg &= ~GEM_BIT(ENDIA_PKT);
2188
2189                 if (bp->native_io)
2190                         dmacfg &= ~GEM_BIT(ENDIA_DESC);
2191                 else
2192                         dmacfg |= GEM_BIT(ENDIA_DESC); /* CPU in big endian */
2193
2194                 if (bp->dev->features & NETIF_F_HW_CSUM)
2195                         dmacfg |= GEM_BIT(TXCOEN);
2196                 else
2197                         dmacfg &= ~GEM_BIT(TXCOEN);
2198
2199 #ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
2200                 if (bp->hw_dma_cap & HW_DMA_CAP_64B)
2201                         dmacfg |= GEM_BIT(ADDR64);
2202 #endif
2203 #ifdef CONFIG_MACB_USE_HWSTAMP
2204                 if (bp->hw_dma_cap & HW_DMA_CAP_PTP)
2205                         dmacfg |= GEM_BIT(RXEXT) | GEM_BIT(TXEXT);
2206 #endif
2207                 netdev_dbg(bp->dev, "Cadence configure DMA with 0x%08x\n",
2208                            dmacfg);
2209                 gem_writel(bp, DMACFG, dmacfg);
2210         }
2211 }
2212
2213 static void macb_init_hw(struct macb *bp)
2214 {
2215         struct macb_queue *queue;
2216         unsigned int q;
2217
2218         u32 config;
2219
2220         macb_reset_hw(bp);
2221         macb_set_hwaddr(bp);
2222
2223         config = macb_mdc_clk_div(bp);
2224         if (bp->phy_interface == PHY_INTERFACE_MODE_SGMII)
2225                 config |= GEM_BIT(SGMIIEN) | GEM_BIT(PCSSEL);
2226         config |= MACB_BF(RBOF, NET_IP_ALIGN);  /* Make eth data aligned */
2227         config |= MACB_BIT(PAE);                /* PAuse Enable */
2228
2229         /* Do not discard Rx FCS if RX checsum offload disabled */
2230         if (bp->dev->features & NETIF_F_RXCSUM)
2231                 config |= MACB_BIT(DRFCS);              /* Discard Rx FCS */
2232
2233         if (bp->caps & MACB_CAPS_JUMBO)
2234                 config |= MACB_BIT(JFRAME);     /* Enable jumbo frames */
2235         else
2236                 config |= MACB_BIT(BIG);        /* Receive oversized frames */
2237         if (bp->dev->flags & IFF_PROMISC)
2238                 config |= MACB_BIT(CAF);        /* Copy All Frames */
2239         else if (macb_is_gem(bp) && bp->dev->features & NETIF_F_RXCSUM)
2240                 config |= GEM_BIT(RXCOEN);
2241         if (!(bp->dev->flags & IFF_BROADCAST))
2242                 config |= MACB_BIT(NBC);        /* No BroadCast */
2243         config |= macb_dbw(bp);
2244         macb_writel(bp, NCFGR, config);
2245         if ((bp->caps & MACB_CAPS_JUMBO) && bp->jumbo_max_len)
2246                 gem_writel(bp, JML, bp->jumbo_max_len);
2247         bp->speed = SPEED_10;
2248         if (bp->caps & MACB_CAPS_PARTIAL_STORE_FORWARD)
2249                 bp->duplex = DUPLEX_FULL;
2250         else
2251                 bp->duplex = DUPLEX_HALF;
2252         bp->rx_frm_len_mask = MACB_RX_FRMLEN_MASK;
2253         if (bp->caps & MACB_CAPS_JUMBO)
2254                 bp->rx_frm_len_mask = MACB_RX_JFRMLEN_MASK;
2255
2256         macb_configure_dma(bp);
2257
2258         /* Enable RX partial store and forward and set watermark */
2259         if (bp->caps & MACB_CAPS_PARTIAL_STORE_FORWARD) {
2260                 gem_writel(bp, PBUFRXCUT,
2261                            (gem_readl(bp, PBUFRXCUT) &
2262                            GEM_BF(WTRMRK, bp->rx_watermark)) |
2263                            GEM_BIT(ENCUTTHRU));
2264         }
2265
2266         /* Initialize TX and RX buffers */
2267         macb_writel(bp, RBQP, lower_32_bits(bp->rx_ring_dma));
2268 #ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
2269         if (bp->hw_dma_cap & HW_DMA_CAP_64B)
2270                 macb_writel(bp, RBQPH, upper_32_bits(bp->rx_ring_dma));
2271 #endif
2272         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) {
2273                 queue_writel(queue, TBQP, lower_32_bits(queue->tx_ring_dma));
2274 #ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
2275                 if (bp->hw_dma_cap & HW_DMA_CAP_64B)
2276                         queue_writel(queue, TBQPH, upper_32_bits(queue->tx_ring_dma));
2277 #endif
2278                 /* We only use the first queue at the moment. Remaining
2279                  * queues must be tied-off before we enable the receiver.
2280                  *
2281                  * See the documentation for receive_q1_ptr for more info.
2282                  */
2283                 if (q)
2284                         queue_writel(queue, RBQP,
2285                                      lower_32_bits(bp->rx_ring_tieoff_dma));
2286
2287                 /* Enable interrupts */
2288                 queue_writel(queue, IER,
2289                              MACB_RX_INT_FLAGS |
2290                              MACB_TX_INT_FLAGS |
2291                              MACB_BIT(HRESP));
2292         }
2293
2294         if ((bp->phy_interface == PHY_INTERFACE_MODE_SGMII) &&
2295             (bp->caps & MACB_CAPS_PCS))
2296                 gem_writel(bp, PCSCNTRL,
2297                            gem_readl(bp, PCSCNTRL) | GEM_BIT(PCSAUTONEG));
2298
2299         /* Enable TX and RX */
2300         macb_writel(bp, NCR, MACB_BIT(RE) | MACB_BIT(TE) | MACB_BIT(MPE) |
2301                     MACB_BIT(PTPUNI));
2302 }
2303
2304 /* The hash address register is 64 bits long and takes up two
2305  * locations in the memory map.  The least significant bits are stored
2306  * in EMAC_HSL and the most significant bits in EMAC_HSH.
2307  *
2308  * The unicast hash enable and the multicast hash enable bits in the
2309  * network configuration register enable the reception of hash matched
2310  * frames. The destination address is reduced to a 6 bit index into
2311  * the 64 bit hash register using the following hash function.  The
2312  * hash function is an exclusive or of every sixth bit of the
2313  * destination address.
2314  *
2315  * hi[5] = da[5] ^ da[11] ^ da[17] ^ da[23] ^ da[29] ^ da[35] ^ da[41] ^ da[47]
2316  * hi[4] = da[4] ^ da[10] ^ da[16] ^ da[22] ^ da[28] ^ da[34] ^ da[40] ^ da[46]
2317  * hi[3] = da[3] ^ da[09] ^ da[15] ^ da[21] ^ da[27] ^ da[33] ^ da[39] ^ da[45]
2318  * hi[2] = da[2] ^ da[08] ^ da[14] ^ da[20] ^ da[26] ^ da[32] ^ da[38] ^ da[44]
2319  * hi[1] = da[1] ^ da[07] ^ da[13] ^ da[19] ^ da[25] ^ da[31] ^ da[37] ^ da[43]
2320  * hi[0] = da[0] ^ da[06] ^ da[12] ^ da[18] ^ da[24] ^ da[30] ^ da[36] ^ da[42]
2321  *
2322  * da[0] represents the least significant bit of the first byte
2323  * received, that is, the multicast/unicast indicator, and da[47]
2324  * represents the most significant bit of the last byte received.  If
2325  * the hash index, hi[n], points to a bit that is set in the hash
2326  * register then the frame will be matched according to whether the
2327  * frame is multicast or unicast.  A multicast match will be signalled
2328  * if the multicast hash enable bit is set, da[0] is 1 and the hash
2329  * index points to a bit set in the hash register.  A unicast match
2330  * will be signalled if the unicast hash enable bit is set, da[0] is 0
2331  * and the hash index points to a bit set in the hash register.  To
2332  * receive all multicast frames, the hash register should be set with
2333  * all ones and the multicast hash enable bit should be set in the
2334  * network configuration register.
2335  */
2336
2337 static inline int hash_bit_value(int bitnr, __u8 *addr)
2338 {
2339         if (addr[bitnr / 8] & (1 << (bitnr % 8)))
2340                 return 1;
2341         return 0;
2342 }
2343
2344 /* Return the hash index value for the specified address. */
2345 static int hash_get_index(__u8 *addr)
2346 {
2347         int i, j, bitval;
2348         int hash_index = 0;
2349
2350         for (j = 0; j < 6; j++) {
2351                 for (i = 0, bitval = 0; i < 8; i++)
2352                         bitval ^= hash_bit_value(i * 6 + j, addr);
2353
2354                 hash_index |= (bitval << j);
2355         }
2356
2357         return hash_index;
2358 }
2359
2360 /* Add multicast addresses to the internal multicast-hash table. */
2361 static void macb_sethashtable(struct net_device *dev)
2362 {
2363         struct netdev_hw_addr *ha;
2364         unsigned long mc_filter[2];
2365         unsigned int bitnr;
2366         struct macb *bp = netdev_priv(dev);
2367
2368         mc_filter[0] = 0;
2369         mc_filter[1] = 0;
2370
2371         netdev_for_each_mc_addr(ha, dev) {
2372                 bitnr = hash_get_index(ha->addr);
2373                 mc_filter[bitnr >> 5] |= 1 << (bitnr & 31);
2374         }
2375
2376         macb_or_gem_writel(bp, HRB, mc_filter[0]);
2377         macb_or_gem_writel(bp, HRT, mc_filter[1]);
2378 }
2379
2380 /* Enable/Disable promiscuous and multicast modes. */
2381 static void macb_set_rx_mode(struct net_device *dev)
2382 {
2383         unsigned long cfg;
2384         struct macb *bp = netdev_priv(dev);
2385
2386         cfg = macb_readl(bp, NCFGR);
2387
2388         if (dev->flags & IFF_PROMISC) {
2389                 /* Enable promiscuous mode */
2390                 cfg |= MACB_BIT(CAF);
2391
2392                 /* Disable RX checksum offload */
2393                 if (macb_is_gem(bp))
2394                         cfg &= ~GEM_BIT(RXCOEN);
2395         } else {
2396                 /* Disable promiscuous mode */
2397                 cfg &= ~MACB_BIT(CAF);
2398
2399                 /* Enable RX checksum offload only if requested */
2400                 if (macb_is_gem(bp) && dev->features & NETIF_F_RXCSUM)
2401                         cfg |= GEM_BIT(RXCOEN);
2402         }
2403
2404         if (dev->flags & IFF_ALLMULTI) {
2405                 /* Enable all multicast mode */
2406                 macb_or_gem_writel(bp, HRB, -1);
2407                 macb_or_gem_writel(bp, HRT, -1);
2408                 cfg |= MACB_BIT(NCFGR_MTI);
2409         } else if (!netdev_mc_empty(dev)) {
2410                 /* Enable specific multicasts */
2411                 macb_sethashtable(dev);
2412                 cfg |= MACB_BIT(NCFGR_MTI);
2413         } else if (dev->flags & (~IFF_ALLMULTI)) {
2414                 /* Disable all multicast mode */
2415                 macb_or_gem_writel(bp, HRB, 0);
2416                 macb_or_gem_writel(bp, HRT, 0);
2417                 cfg &= ~MACB_BIT(NCFGR_MTI);
2418         }
2419
2420         macb_writel(bp, NCFGR, cfg);
2421 }
2422
2423 static int macb_open(struct net_device *dev)
2424 {
2425         struct macb *bp = netdev_priv(dev);
2426         size_t bufsz = dev->mtu + ETH_HLEN + ETH_FCS_LEN + NET_IP_ALIGN;
2427         int err;
2428
2429         netdev_dbg(bp->dev, "open\n");
2430
2431         err = pm_runtime_get_sync(&bp->pdev->dev);
2432         if (err < 0)
2433                 return err;
2434
2435         /* carrier starts down */
2436         netif_carrier_off(dev);
2437
2438         /* if the phy is not yet register, retry later*/
2439         if (!bp->phy_dev)
2440                 return -EAGAIN;
2441
2442         /* RX buffers initialization */
2443         macb_init_rx_buffer_size(bp, bufsz);
2444
2445         err = macb_alloc_consistent(bp);
2446         if (err) {
2447                 netdev_err(dev, "Unable to allocate DMA memory (error %d)\n",
2448                            err);
2449                 return err;
2450         }
2451
2452         napi_enable(&bp->napi);
2453
2454         bp->macbgem_ops.mog_init_rings(bp);
2455         macb_init_hw(bp);
2456
2457         /* schedule a link state check */
2458         phy_start(bp->phy_dev);
2459
2460         netif_tx_start_all_queues(dev);
2461
2462         if (bp->ptp_info)
2463                 bp->ptp_info->ptp_init(dev);
2464
2465         return 0;
2466 }
2467
2468 static int macb_close(struct net_device *dev)
2469 {
2470         struct macb *bp = netdev_priv(dev);
2471         unsigned long flags;
2472
2473         netif_tx_stop_all_queues(dev);
2474         napi_disable(&bp->napi);
2475
2476         if (bp->phy_dev)
2477                 phy_stop(bp->phy_dev);
2478
2479         spin_lock_irqsave(&bp->lock, flags);
2480         macb_reset_hw(bp);
2481         netif_carrier_off(dev);
2482         spin_unlock_irqrestore(&bp->lock, flags);
2483
2484         macb_free_consistent(bp);
2485
2486         if (bp->ptp_info)
2487                 bp->ptp_info->ptp_remove(dev);
2488
2489         pm_runtime_put(&bp->pdev->dev);
2490
2491         return 0;
2492 }
2493
2494 static int macb_change_mtu(struct net_device *dev, int new_mtu)
2495 {
2496         if (netif_running(dev))
2497                 return -EBUSY;
2498
2499         dev->mtu = new_mtu;
2500
2501         return 0;
2502 }
2503
2504 static void gem_update_stats(struct macb *bp)
2505 {
2506         unsigned int i;
2507         u32 *p = &bp->hw_stats.gem.tx_octets_31_0;
2508
2509         for (i = 0; i < GEM_STATS_LEN; ++i, ++p) {
2510                 u32 offset = gem_statistics[i].offset;
2511                 u64 val = bp->macb_reg_readl(bp, offset);
2512
2513                 bp->ethtool_stats[i] += val;
2514                 *p += val;
2515
2516                 if (offset == GEM_OCTTXL || offset == GEM_OCTRXL) {
2517                         /* Add GEM_OCTTXH, GEM_OCTRXH */
2518                         val = bp->macb_reg_readl(bp, offset + 4);
2519                         bp->ethtool_stats[i] += ((u64)val) << 32;
2520                         *(++p) += val;
2521                 }
2522         }
2523 }
2524
2525 static struct net_device_stats *gem_get_stats(struct macb *bp)
2526 {
2527         struct gem_stats *hwstat = &bp->hw_stats.gem;
2528         struct net_device_stats *nstat = &bp->dev->stats;
2529
2530         gem_update_stats(bp);
2531
2532         nstat->rx_errors = (hwstat->rx_frame_check_sequence_errors +
2533                             hwstat->rx_alignment_errors +
2534                             hwstat->rx_resource_errors +
2535                             hwstat->rx_overruns +
2536                             hwstat->rx_oversize_frames +
2537                             hwstat->rx_jabbers +
2538                             hwstat->rx_undersized_frames +
2539                             hwstat->rx_length_field_frame_errors);
2540         nstat->tx_errors = (hwstat->tx_late_collisions +
2541                             hwstat->tx_excessive_collisions +
2542                             hwstat->tx_underrun +
2543                             hwstat->tx_carrier_sense_errors);
2544         nstat->multicast = hwstat->rx_multicast_frames;
2545         nstat->collisions = (hwstat->tx_single_collision_frames +
2546                              hwstat->tx_multiple_collision_frames +
2547                              hwstat->tx_excessive_collisions);
2548         nstat->rx_length_errors = (hwstat->rx_oversize_frames +
2549                                    hwstat->rx_jabbers +
2550                                    hwstat->rx_undersized_frames +
2551                                    hwstat->rx_length_field_frame_errors);
2552         nstat->rx_over_errors = hwstat->rx_resource_errors;
2553         nstat->rx_crc_errors = hwstat->rx_frame_check_sequence_errors;
2554         nstat->rx_frame_errors = hwstat->rx_alignment_errors;
2555         nstat->rx_fifo_errors = hwstat->rx_overruns;
2556         nstat->tx_aborted_errors = hwstat->tx_excessive_collisions;
2557         nstat->tx_carrier_errors = hwstat->tx_carrier_sense_errors;
2558         nstat->tx_fifo_errors = hwstat->tx_underrun;
2559
2560         return nstat;
2561 }
2562
2563 static void gem_get_ethtool_stats(struct net_device *dev,
2564                                   struct ethtool_stats *stats, u64 *data)
2565 {
2566         struct macb *bp;
2567
2568         bp = netdev_priv(dev);
2569         gem_update_stats(bp);
2570         memcpy(data, &bp->ethtool_stats, sizeof(u64) * GEM_STATS_LEN);
2571 }
2572
2573 static int gem_get_sset_count(struct net_device *dev, int sset)
2574 {
2575         switch (sset) {
2576         case ETH_SS_STATS:
2577                 return GEM_STATS_LEN;
2578         default:
2579                 return -EOPNOTSUPP;
2580         }
2581 }
2582
2583 static void gem_get_ethtool_strings(struct net_device *dev, u32 sset, u8 *p)
2584 {
2585         unsigned int i;
2586
2587         switch (sset) {
2588         case ETH_SS_STATS:
2589                 for (i = 0; i < GEM_STATS_LEN; i++, p += ETH_GSTRING_LEN)
2590                         memcpy(p, gem_statistics[i].stat_string,
2591                                ETH_GSTRING_LEN);
2592                 break;
2593         }
2594 }
2595
2596 static struct net_device_stats *macb_get_stats(struct net_device *dev)
2597 {
2598         struct macb *bp = netdev_priv(dev);
2599         struct net_device_stats *nstat = &bp->dev->stats;
2600         struct macb_stats *hwstat = &bp->hw_stats.macb;
2601
2602         if (macb_is_gem(bp))
2603                 return gem_get_stats(bp);
2604
2605         /* read stats from hardware */
2606         macb_update_stats(bp);
2607
2608         /* Convert HW stats into netdevice stats */
2609         nstat->rx_errors = (hwstat->rx_fcs_errors +
2610                             hwstat->rx_align_errors +
2611                             hwstat->rx_resource_errors +
2612                             hwstat->rx_overruns +
2613                             hwstat->rx_oversize_pkts +
2614                             hwstat->rx_jabbers +
2615                             hwstat->rx_undersize_pkts +
2616                             hwstat->rx_length_mismatch);
2617         nstat->tx_errors = (hwstat->tx_late_cols +
2618                             hwstat->tx_excessive_cols +
2619                             hwstat->tx_underruns +
2620                             hwstat->tx_carrier_errors +
2621                             hwstat->sqe_test_errors);
2622         nstat->collisions = (hwstat->tx_single_cols +
2623                              hwstat->tx_multiple_cols +
2624                              hwstat->tx_excessive_cols);
2625         nstat->rx_length_errors = (hwstat->rx_oversize_pkts +
2626                                    hwstat->rx_jabbers +
2627                                    hwstat->rx_undersize_pkts +
2628                                    hwstat->rx_length_mismatch);
2629         nstat->rx_over_errors = hwstat->rx_resource_errors +
2630                                    hwstat->rx_overruns;
2631         nstat->rx_crc_errors = hwstat->rx_fcs_errors;
2632         nstat->rx_frame_errors = hwstat->rx_align_errors;
2633         nstat->rx_fifo_errors = hwstat->rx_overruns;
2634         /* XXX: What does "missed" mean? */
2635         nstat->tx_aborted_errors = hwstat->tx_excessive_cols;
2636         nstat->tx_carrier_errors = hwstat->tx_carrier_errors;
2637         nstat->tx_fifo_errors = hwstat->tx_underruns;
2638         /* Don't know about heartbeat or window errors... */
2639
2640         return nstat;
2641 }
2642
2643 static int macb_get_regs_len(struct net_device *netdev)
2644 {
2645         return MACB_GREGS_NBR * sizeof(u32);
2646 }
2647
2648 static void macb_get_regs(struct net_device *dev, struct ethtool_regs *regs,
2649                           void *p)
2650 {
2651         struct macb *bp = netdev_priv(dev);
2652         unsigned int tail, head;
2653         u32 *regs_buff = p;
2654
2655         regs->version = (macb_readl(bp, MID) & ((1 << MACB_REV_SIZE) - 1))
2656                         | MACB_GREGS_VERSION;
2657
2658         tail = macb_tx_ring_wrap(bp, bp->queues[0].tx_tail);
2659         head = macb_tx_ring_wrap(bp, bp->queues[0].tx_head);
2660
2661         regs_buff[0]  = macb_readl(bp, NCR);
2662         regs_buff[1]  = macb_or_gem_readl(bp, NCFGR);
2663         regs_buff[2]  = macb_readl(bp, NSR);
2664         regs_buff[3]  = macb_readl(bp, TSR);
2665         regs_buff[4]  = macb_readl(bp, RBQP);
2666         regs_buff[5]  = macb_readl(bp, TBQP);
2667         regs_buff[6]  = macb_readl(bp, RSR);
2668         regs_buff[7]  = macb_readl(bp, IMR);
2669
2670         regs_buff[8]  = tail;
2671         regs_buff[9]  = head;
2672         regs_buff[10] = macb_tx_dma(&bp->queues[0], tail);
2673         regs_buff[11] = macb_tx_dma(&bp->queues[0], head);
2674
2675         if (!(bp->caps & MACB_CAPS_USRIO_DISABLED))
2676                 regs_buff[12] = macb_or_gem_readl(bp, USRIO);
2677         if (macb_is_gem(bp))
2678                 regs_buff[13] = gem_readl(bp, DMACFG);
2679 }
2680
2681
2682 static void macb_get_ringparam(struct net_device *netdev,
2683                                struct ethtool_ringparam *ring)
2684 {
2685         struct macb *bp = netdev_priv(netdev);
2686
2687         ring->rx_max_pending = MAX_RX_RING_SIZE;
2688         ring->tx_max_pending = MAX_TX_RING_SIZE;
2689
2690         ring->rx_pending = bp->rx_ring_size;
2691         ring->tx_pending = bp->tx_ring_size;
2692 }
2693
2694 static int macb_set_ringparam(struct net_device *netdev,
2695                               struct ethtool_ringparam *ring)
2696 {
2697         struct macb *bp = netdev_priv(netdev);
2698         u32 new_rx_size, new_tx_size;
2699         unsigned int reset = 0;
2700
2701         if ((ring->rx_mini_pending) || (ring->rx_jumbo_pending))
2702                 return -EINVAL;
2703
2704         new_rx_size = clamp_t(u32, ring->rx_pending,
2705                               MIN_RX_RING_SIZE, MAX_RX_RING_SIZE);
2706         new_rx_size = roundup_pow_of_two(new_rx_size);
2707
2708         new_tx_size = clamp_t(u32, ring->tx_pending,
2709                               MIN_TX_RING_SIZE, MAX_TX_RING_SIZE);
2710         new_tx_size = roundup_pow_of_two(new_tx_size);
2711
2712         if ((new_tx_size == bp->tx_ring_size) &&
2713             (new_rx_size == bp->rx_ring_size)) {
2714                 /* nothing to do */
2715                 return 0;
2716         }
2717
2718         if (netif_running(bp->dev)) {
2719                 reset = 1;
2720                 macb_close(bp->dev);
2721         }
2722
2723         bp->rx_ring_size = new_rx_size;
2724         bp->tx_ring_size = new_tx_size;
2725
2726         if (reset)
2727                 macb_open(bp->dev);
2728
2729         return 0;
2730 }
2731
2732 #ifdef CONFIG_MACB_USE_HWSTAMP
2733 static unsigned int gem_get_tsu_rate(struct macb *bp)
2734 {
2735         struct clk *tsu_clk;
2736         unsigned int tsu_rate;
2737
2738         tsu_clk = devm_clk_get(&bp->pdev->dev, "tsu_clk");
2739         if (!IS_ERR(tsu_clk))
2740                 tsu_rate = clk_get_rate(tsu_clk);
2741         /* try pclk instead */
2742         else if (!IS_ERR(bp->pclk)) {
2743                 tsu_clk = bp->pclk;
2744                 tsu_rate = clk_get_rate(tsu_clk);
2745         } else
2746                 return -ENOTSUPP;
2747         return tsu_rate;
2748 }
2749
2750 static s32 gem_get_ptp_max_adj(void)
2751 {
2752         return 64000000;
2753 }
2754
2755 static int gem_get_ts_info(struct net_device *dev,
2756                            struct ethtool_ts_info *info)
2757 {
2758         struct macb *bp = netdev_priv(dev);
2759
2760         if ((bp->hw_dma_cap & HW_DMA_CAP_PTP) == 0) {
2761                 ethtool_op_get_ts_info(dev, info);
2762                 return 0;
2763         }
2764
2765         info->so_timestamping =
2766                 SOF_TIMESTAMPING_TX_SOFTWARE |
2767                 SOF_TIMESTAMPING_RX_SOFTWARE |
2768                 SOF_TIMESTAMPING_SOFTWARE |
2769                 SOF_TIMESTAMPING_TX_HARDWARE |
2770                 SOF_TIMESTAMPING_RX_HARDWARE |
2771                 SOF_TIMESTAMPING_RAW_HARDWARE;
2772         info->tx_types =
2773                 (1 << HWTSTAMP_TX_ONESTEP_SYNC) |
2774                 (1 << HWTSTAMP_TX_OFF) |
2775                 (1 << HWTSTAMP_TX_ON);
2776         info->rx_filters =
2777                 (1 << HWTSTAMP_FILTER_NONE) |
2778                 (1 << HWTSTAMP_FILTER_ALL);
2779
2780         info->phc_index = bp->ptp_clock ? ptp_clock_index(bp->ptp_clock) : -1;
2781
2782         return 0;
2783 }
2784
2785 static struct macb_ptp_info gem_ptp_info = {
2786         .ptp_init        = gem_ptp_init,
2787         .ptp_remove      = gem_ptp_remove,
2788         .get_ptp_max_adj = gem_get_ptp_max_adj,
2789         .get_tsu_rate    = gem_get_tsu_rate,
2790         .get_ts_info     = gem_get_ts_info,
2791         .get_hwtst       = gem_get_hwtst,
2792         .set_hwtst       = gem_set_hwtst,
2793 };
2794 #endif
2795
2796 static int macb_get_ts_info(struct net_device *netdev,
2797                             struct ethtool_ts_info *info)
2798 {
2799         struct macb *bp = netdev_priv(netdev);
2800
2801         if (bp->ptp_info)
2802                 return bp->ptp_info->get_ts_info(netdev, info);
2803
2804         return ethtool_op_get_ts_info(netdev, info);
2805 }
2806
2807 static const struct ethtool_ops macb_ethtool_ops = {
2808         .get_regs_len           = macb_get_regs_len,
2809         .get_regs               = macb_get_regs,
2810         .get_link               = ethtool_op_get_link,
2811         .get_ts_info            = ethtool_op_get_ts_info,
2812         .get_link_ksettings     = phy_ethtool_get_link_ksettings,
2813         .set_link_ksettings     = phy_ethtool_set_link_ksettings,
2814         .get_ringparam          = macb_get_ringparam,
2815         .set_ringparam          = macb_set_ringparam,
2816 };
2817
2818 static const struct ethtool_ops gem_ethtool_ops = {
2819         .get_regs_len           = macb_get_regs_len,
2820         .get_regs               = macb_get_regs,
2821         .get_link               = ethtool_op_get_link,
2822         .get_ts_info            = macb_get_ts_info,
2823         .get_ethtool_stats      = gem_get_ethtool_stats,
2824         .get_strings            = gem_get_ethtool_strings,
2825         .get_sset_count         = gem_get_sset_count,
2826         .get_link_ksettings     = phy_ethtool_get_link_ksettings,
2827         .set_link_ksettings     = phy_ethtool_set_link_ksettings,
2828         .get_ringparam          = macb_get_ringparam,
2829         .set_ringparam          = macb_set_ringparam,
2830 };
2831
2832 static int macb_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
2833 {
2834         struct phy_device *phydev = dev->phydev;
2835         struct macb *bp = netdev_priv(dev);
2836
2837         if (!netif_running(dev))
2838                 return -EINVAL;
2839
2840         if (!phydev)
2841                 return -ENODEV;
2842
2843         if (!bp->ptp_info)
2844                 return phy_mii_ioctl(phydev, rq, cmd);
2845
2846         switch (cmd) {
2847         case SIOCSHWTSTAMP:
2848                 return bp->ptp_info->set_hwtst(dev, rq, cmd);
2849         case SIOCGHWTSTAMP:
2850                 return bp->ptp_info->get_hwtst(dev, rq);
2851         default:
2852                 return phy_mii_ioctl(phydev, rq, cmd);
2853         }
2854 }
2855
2856 static int macb_set_features(struct net_device *netdev,
2857                              netdev_features_t features)
2858 {
2859         struct macb *bp = netdev_priv(netdev);
2860         netdev_features_t changed = features ^ netdev->features;
2861
2862         /* TX checksum offload */
2863         if ((changed & NETIF_F_HW_CSUM) && macb_is_gem(bp)) {
2864                 u32 dmacfg;
2865
2866                 dmacfg = gem_readl(bp, DMACFG);
2867                 if (features & NETIF_F_HW_CSUM)
2868                         dmacfg |= GEM_BIT(TXCOEN);
2869                 else
2870                         dmacfg &= ~GEM_BIT(TXCOEN);
2871                 gem_writel(bp, DMACFG, dmacfg);
2872         }
2873
2874         /* RX checksum offload */
2875         if ((changed & NETIF_F_RXCSUM) && macb_is_gem(bp)) {
2876                 u32 netcfg;
2877
2878                 netcfg = gem_readl(bp, NCFGR);
2879                 if (features & NETIF_F_RXCSUM &&
2880                     !(netdev->flags & IFF_PROMISC))
2881                         netcfg |= GEM_BIT(RXCOEN);
2882                 else
2883                         netcfg &= ~GEM_BIT(RXCOEN);
2884                 gem_writel(bp, NCFGR, netcfg);
2885         }
2886
2887         return 0;
2888 }
2889
2890 static const struct net_device_ops macb_netdev_ops = {
2891         .ndo_open               = macb_open,
2892         .ndo_stop               = macb_close,
2893         .ndo_start_xmit         = macb_start_xmit,
2894         .ndo_set_rx_mode        = macb_set_rx_mode,
2895         .ndo_get_stats          = macb_get_stats,
2896         .ndo_do_ioctl           = macb_ioctl,
2897         .ndo_validate_addr      = eth_validate_addr,
2898         .ndo_change_mtu         = macb_change_mtu,
2899         .ndo_set_mac_address    = eth_mac_addr,
2900 #ifdef CONFIG_NET_POLL_CONTROLLER
2901         .ndo_poll_controller    = macb_poll_controller,
2902 #endif
2903         .ndo_set_features       = macb_set_features,
2904         .ndo_features_check     = macb_features_check,
2905 };
2906
2907 /* Configure peripheral capabilities according to device tree
2908  * and integration options used
2909  */
2910 static void macb_configure_caps(struct macb *bp,
2911                                 const struct macb_config *dt_conf)
2912 {
2913         u32 dcfg;
2914         int retval;
2915
2916         if (dt_conf)
2917                 bp->caps = dt_conf->caps;
2918
2919         /* By default we set to partial store and forward mode for zynqmp.
2920          * Disable if not set in devicetree.
2921          */
2922         if (bp->caps & MACB_CAPS_PARTIAL_STORE_FORWARD) {
2923                 retval = of_property_read_u16(bp->pdev->dev.of_node,
2924                                               "rx-watermark",
2925                                               &bp->rx_watermark);
2926
2927                 /* Disable partial store and forward in case of error or
2928                  * invalid watermark value
2929                  */
2930                 if (retval || bp->rx_watermark > 0xFFF) {
2931                         dev_info(&bp->pdev->dev,
2932                                  "Not enabling partial store and forward\n");
2933                         bp->caps &= ~MACB_CAPS_PARTIAL_STORE_FORWARD;
2934                 }
2935         }
2936
2937         if (hw_is_gem(bp->regs, bp->native_io)) {
2938                 bp->caps |= MACB_CAPS_MACB_IS_GEM;
2939
2940                 dcfg = gem_readl(bp, DCFG1);
2941                 if (GEM_BFEXT(IRQCOR, dcfg) == 0)
2942                         bp->caps |= MACB_CAPS_ISR_CLEAR_ON_WRITE;
2943                 dcfg = gem_readl(bp, DCFG2);
2944                 if ((dcfg & (GEM_BIT(RX_PKT_BUFF) | GEM_BIT(TX_PKT_BUFF))) == 0)
2945                         bp->caps |= MACB_CAPS_FIFO_MODE;
2946 #ifdef CONFIG_MACB_USE_HWSTAMP
2947                 if (gem_has_ptp(bp)) {
2948                         if (!GEM_BFEXT(TSU, gem_readl(bp, DCFG5)))
2949                                 pr_err("GEM doesn't support hardware ptp.\n");
2950                         else {
2951                                 bp->hw_dma_cap |= HW_DMA_CAP_PTP;
2952                                 bp->ptp_info = &gem_ptp_info;
2953                         }
2954                 }
2955 #endif
2956         }
2957
2958         dev_dbg(&bp->pdev->dev, "Cadence caps 0x%08x\n", bp->caps);
2959 }
2960
2961 #if defined(CONFIG_OF)
2962 static void macb_reset_phy(struct platform_device *pdev)
2963 {
2964         int err, phy_reset, msec = 1;
2965         bool active_low;
2966         struct device_node *np = pdev->dev.of_node;
2967
2968         if (!np)
2969                 return;
2970
2971         of_property_read_u32(np, "phy-reset-duration", &msec);
2972         active_low = of_property_read_bool(np, "phy-reset-active-low");
2973
2974         phy_reset = of_get_named_gpio(np, "phy-reset-gpio", 0);
2975         if (!gpio_is_valid(phy_reset))
2976                 return;
2977
2978         err = devm_gpio_request_one(&pdev->dev, phy_reset,
2979                                     active_low ? GPIOF_OUT_INIT_LOW :
2980                                     GPIOF_OUT_INIT_HIGH, "phy-reset");
2981         if (err) {
2982                 dev_err(&pdev->dev, "failed to get phy-reset-gpio: %d\n", err);
2983                 return;
2984         }
2985         msleep(msec);
2986         gpio_set_value(phy_reset, active_low);
2987 }
2988 #else /* CONFIG_OF */
2989 static void macb_reset_phy(struct platform_device *pdev)
2990 {
2991 }
2992 #endif /* CONFIG_OF */
2993
2994 static void macb_probe_queues(void __iomem *mem,
2995                               bool native_io,
2996                               unsigned int *queue_mask,
2997                               unsigned int *num_queues)
2998 {
2999         unsigned int hw_q;
3000
3001         *queue_mask = 0x1;
3002         *num_queues = 1;
3003
3004         /* is it macb or gem ?
3005          *
3006          * We need to read directly from the hardware here because
3007          * we are early in the probe process and don't have the
3008          * MACB_CAPS_MACB_IS_GEM flag positioned
3009          */
3010         if (!hw_is_gem(mem, native_io))
3011                 return;
3012
3013         /* bit 0 is never set but queue 0 always exists */
3014         *queue_mask = readl_relaxed(mem + GEM_DCFG6) & 0xff;
3015
3016         *queue_mask |= 0x1;
3017
3018         for (hw_q = 1; hw_q < MACB_MAX_QUEUES; ++hw_q)
3019                 if (*queue_mask & (1 << hw_q))
3020                         (*num_queues)++;
3021 }
3022
3023 static int macb_clk_init(struct platform_device *pdev, struct clk **pclk,
3024                          struct clk **hclk, struct clk **tx_clk,
3025                          struct clk **rx_clk, struct clk **tsu_clk)
3026 {
3027         int err;
3028
3029         *pclk = devm_clk_get(&pdev->dev, "pclk");
3030         if (IS_ERR(*pclk)) {
3031                 err = PTR_ERR(*pclk);
3032                 dev_err(&pdev->dev, "failed to get macb_clk (%u)\n", err);
3033                 return err;
3034         }
3035
3036         *hclk = devm_clk_get(&pdev->dev, "hclk");
3037         if (IS_ERR(*hclk)) {
3038                 err = PTR_ERR(*hclk);
3039                 dev_err(&pdev->dev, "failed to get hclk (%u)\n", err);
3040                 return err;
3041         }
3042
3043         *tx_clk = devm_clk_get(&pdev->dev, "tx_clk");
3044         if (IS_ERR(*tx_clk))
3045                 *tx_clk = NULL;
3046
3047         *rx_clk = devm_clk_get(&pdev->dev, "rx_clk");
3048         if (IS_ERR(*rx_clk))
3049                 *rx_clk = NULL;
3050
3051         *tsu_clk = devm_clk_get(&pdev->dev, "tsu_clk");
3052         if (IS_ERR(*tsu_clk))
3053                 *tsu_clk = NULL;
3054
3055         err = clk_prepare_enable(*pclk);
3056         if (err) {
3057                 dev_err(&pdev->dev, "failed to enable pclk (%u)\n", err);
3058                 return err;
3059         }
3060
3061         err = clk_prepare_enable(*hclk);
3062         if (err) {
3063                 dev_err(&pdev->dev, "failed to enable hclk (%u)\n", err);
3064                 goto err_disable_pclk;
3065         }
3066
3067         err = clk_prepare_enable(*tx_clk);
3068         if (err) {
3069                 dev_err(&pdev->dev, "failed to enable tx_clk (%u)\n", err);
3070                 goto err_disable_hclk;
3071         }
3072
3073         err = clk_prepare_enable(*rx_clk);
3074         if (err) {
3075                 dev_err(&pdev->dev, "failed to enable rx_clk (%u)\n", err);
3076                 goto err_disable_txclk;
3077         }
3078
3079         err = clk_prepare_enable(*tsu_clk);
3080         if (err) {
3081                 dev_err(&pdev->dev, "failed to enable tsu_clk (%u)\n", err);
3082                 goto err_disable_rxclk;
3083         }
3084
3085         return 0;
3086
3087 err_disable_rxclk:
3088         clk_disable_unprepare(*rx_clk);
3089
3090 err_disable_txclk:
3091         clk_disable_unprepare(*tx_clk);
3092
3093 err_disable_hclk:
3094         clk_disable_unprepare(*hclk);
3095
3096 err_disable_pclk:
3097         clk_disable_unprepare(*pclk);
3098
3099         return err;
3100 }
3101
3102 static int macb_init(struct platform_device *pdev)
3103 {
3104         struct net_device *dev = platform_get_drvdata(pdev);
3105         unsigned int hw_q, q;
3106         struct macb *bp = netdev_priv(dev);
3107         struct macb_queue *queue;
3108         int err;
3109         u32 val;
3110
3111         bp->tx_ring_size = DEFAULT_TX_RING_SIZE;
3112         bp->rx_ring_size = DEFAULT_RX_RING_SIZE;
3113
3114         /* set the queue register mapping once for all: queue0 has a special
3115          * register mapping but we don't want to test the queue index then
3116          * compute the corresponding register offset at run time.
3117          */
3118         for (hw_q = 0, q = 0; hw_q < MACB_MAX_QUEUES; ++hw_q) {
3119                 if (!(bp->queue_mask & (1 << hw_q)))
3120                         continue;
3121
3122                 queue = &bp->queues[q];
3123                 queue->bp = bp;
3124                 if (hw_q) {
3125                         queue->ISR  = GEM_ISR(hw_q - 1);
3126                         queue->IER  = GEM_IER(hw_q - 1);
3127                         queue->IDR  = GEM_IDR(hw_q - 1);
3128                         queue->IMR  = GEM_IMR(hw_q - 1);
3129                         queue->TBQP = GEM_TBQP(hw_q - 1);
3130 #ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
3131                         if (bp->hw_dma_cap & HW_DMA_CAP_64B)
3132                                 queue->TBQPH = GEM_TBQPH(hw_q - 1);
3133 #endif
3134                         queue->RBQP = GEM_RBQP(hw_q - 1);
3135                 } else {
3136                         /* queue0 uses legacy registers */
3137                         queue->ISR  = MACB_ISR;
3138                         queue->IER  = MACB_IER;
3139                         queue->IDR  = MACB_IDR;
3140                         queue->IMR  = MACB_IMR;
3141                         queue->TBQP = MACB_TBQP;
3142 #ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
3143                         if (bp->hw_dma_cap & HW_DMA_CAP_64B)
3144                                 queue->TBQPH = MACB_TBQPH;
3145 #endif
3146                         queue->RBQP = MACB_RBQP;
3147                 }
3148
3149                 /* get irq: here we use the linux queue index, not the hardware
3150                  * queue index. the queue irq definitions in the device tree
3151                  * must remove the optional gaps that could exist in the
3152                  * hardware queue mask.
3153                  */
3154                 queue->irq = platform_get_irq(pdev, q);
3155                 err = devm_request_irq(&pdev->dev, queue->irq, macb_interrupt,
3156                                        IRQF_SHARED, dev->name, queue);
3157                 if (err) {
3158                         dev_err(&pdev->dev,
3159                                 "Unable to request IRQ %d (error %d)\n",
3160                                 queue->irq, err);
3161                         return err;
3162                 }
3163
3164                 INIT_WORK(&queue->tx_error_task, macb_tx_error_task);
3165                 q++;
3166         }
3167
3168         dev->netdev_ops = &macb_netdev_ops;
3169         netif_napi_add(dev, &bp->napi, macb_poll, 64);
3170
3171         /* setup appropriated routines according to adapter type */
3172         if (macb_is_gem(bp)) {
3173                 bp->max_tx_length = GEM_MAX_TX_LEN;
3174                 bp->macbgem_ops.mog_alloc_rx_buffers = gem_alloc_rx_buffers;
3175                 bp->macbgem_ops.mog_free_rx_buffers = gem_free_rx_buffers;
3176                 bp->macbgem_ops.mog_init_rings = gem_init_rings;
3177                 bp->macbgem_ops.mog_rx = gem_rx;
3178                 dev->ethtool_ops = &gem_ethtool_ops;
3179         } else {
3180                 bp->max_tx_length = MACB_MAX_TX_LEN;
3181                 bp->macbgem_ops.mog_alloc_rx_buffers = macb_alloc_rx_buffers;
3182                 bp->macbgem_ops.mog_free_rx_buffers = macb_free_rx_buffers;
3183                 bp->macbgem_ops.mog_init_rings = macb_init_rings;
3184                 bp->macbgem_ops.mog_rx = macb_rx;
3185                 dev->ethtool_ops = &macb_ethtool_ops;
3186         }
3187
3188         /* Set features */
3189         dev->hw_features = NETIF_F_SG;
3190
3191         /* Check LSO capability */
3192         if (GEM_BFEXT(PBUF_LSO, gem_readl(bp, DCFG6)))
3193                 dev->hw_features |= MACB_NETIF_LSO;
3194
3195         /* Checksum offload is only available on gem with packet buffer */
3196         if (macb_is_gem(bp) && !(bp->caps & MACB_CAPS_FIFO_MODE))
3197                 dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_RXCSUM;
3198         if (bp->caps & MACB_CAPS_PARTIAL_STORE_FORWARD)
3199                 dev->hw_features &= ~NETIF_F_RXCSUM;
3200         if (bp->caps & MACB_CAPS_SG_DISABLED)
3201                 dev->hw_features &= ~NETIF_F_SG;
3202         dev->features = dev->hw_features;
3203
3204         if (!(bp->caps & MACB_CAPS_USRIO_DISABLED)) {
3205                 val = 0;
3206                 if (bp->phy_interface == PHY_INTERFACE_MODE_RGMII)
3207                         val = GEM_BIT(RGMII);
3208                 else if (bp->phy_interface == PHY_INTERFACE_MODE_RMII &&
3209                          (bp->caps & MACB_CAPS_USRIO_DEFAULT_IS_MII_GMII))
3210                         val = MACB_BIT(RMII);
3211                 else if (!(bp->caps & MACB_CAPS_USRIO_DEFAULT_IS_MII_GMII))
3212                         val = MACB_BIT(MII);
3213
3214                 if (bp->caps & MACB_CAPS_USRIO_HAS_CLKEN)
3215                         val |= MACB_BIT(CLKEN);
3216
3217                 macb_or_gem_writel(bp, USRIO, val);
3218         }
3219
3220         /* Set MII management clock divider */
3221         val = macb_mdc_clk_div(bp);
3222         val |= macb_dbw(bp);
3223         if (bp->phy_interface == PHY_INTERFACE_MODE_SGMII)
3224                 val |= GEM_BIT(SGMIIEN) | GEM_BIT(PCSSEL);
3225         macb_writel(bp, NCFGR, val);
3226
3227         if ((bp->phy_interface == PHY_INTERFACE_MODE_SGMII) &&
3228             (bp->caps & MACB_CAPS_PCS))
3229                 gem_writel(bp, PCSCNTRL,
3230                            gem_readl(bp, PCSCNTRL) | GEM_BIT(PCSAUTONEG));
3231
3232         return 0;
3233 }
3234
3235 #if defined(CONFIG_OF)
3236 /* 1518 rounded up */
3237 #define AT91ETHER_MAX_RBUFF_SZ  0x600
3238 /* max number of receive buffers */
3239 #define AT91ETHER_MAX_RX_DESCR  9
3240
3241 /* Initialize and start the Receiver and Transmit subsystems */
3242 static int at91ether_start(struct net_device *dev)
3243 {
3244         struct macb *lp = netdev_priv(dev);
3245         struct macb_dma_desc *desc;
3246         dma_addr_t addr;
3247         u32 ctl;
3248         int i;
3249
3250         lp->rx_ring = dma_alloc_coherent(&lp->pdev->dev,
3251                                          (AT91ETHER_MAX_RX_DESCR *
3252                                           macb_dma_desc_get_size(lp)),
3253                                          &lp->rx_ring_dma, GFP_KERNEL);
3254         if (!lp->rx_ring)
3255                 return -ENOMEM;
3256
3257         lp->rx_buffers = dma_alloc_coherent(&lp->pdev->dev,
3258                                             AT91ETHER_MAX_RX_DESCR *
3259                                             AT91ETHER_MAX_RBUFF_SZ,
3260                                             &lp->rx_buffers_dma, GFP_KERNEL);
3261         if (!lp->rx_buffers) {
3262                 dma_free_coherent(&lp->pdev->dev,
3263                                   AT91ETHER_MAX_RX_DESCR *
3264                                   macb_dma_desc_get_size(lp),
3265                                   lp->rx_ring, lp->rx_ring_dma);
3266                 lp->rx_ring = NULL;
3267                 return -ENOMEM;
3268         }
3269
3270         addr = lp->rx_buffers_dma;
3271         for (i = 0; i < AT91ETHER_MAX_RX_DESCR; i++) {
3272                 desc = macb_rx_desc(lp, i);
3273                 macb_set_addr(lp, desc, addr);
3274                 desc->ctrl = 0;
3275                 addr += AT91ETHER_MAX_RBUFF_SZ;
3276         }
3277
3278         /* Set the Wrap bit on the last descriptor */
3279         desc->addr |= MACB_BIT(RX_WRAP);
3280
3281         /* Reset buffer index */
3282         lp->rx_tail = 0;
3283
3284         /* Program address of descriptor list in Rx Buffer Queue register */
3285         macb_writel(lp, RBQP, lp->rx_ring_dma);
3286
3287         /* Enable Receive and Transmit */
3288         ctl = macb_readl(lp, NCR);
3289         macb_writel(lp, NCR, ctl | MACB_BIT(RE) | MACB_BIT(TE));
3290
3291         return 0;
3292 }
3293
3294 /* Open the ethernet interface */
3295 static int at91ether_open(struct net_device *dev)
3296 {
3297         struct macb *lp = netdev_priv(dev);
3298         u32 ctl;
3299         int ret;
3300
3301         /* Clear internal statistics */
3302         ctl = macb_readl(lp, NCR);
3303         macb_writel(lp, NCR, ctl | MACB_BIT(CLRSTAT));
3304
3305         macb_set_hwaddr(lp);
3306
3307         ret = at91ether_start(dev);
3308         if (ret)
3309                 return ret;
3310
3311         /* Enable MAC interrupts */
3312         macb_writel(lp, IER, MACB_BIT(RCOMP)    |
3313                              MACB_BIT(RXUBR)    |
3314                              MACB_BIT(ISR_TUND) |
3315                              MACB_BIT(ISR_RLE)  |
3316                              MACB_BIT(TCOMP)    |
3317                              MACB_BIT(ISR_ROVR) |
3318                              MACB_BIT(HRESP));
3319
3320         /* schedule a link state check */
3321         phy_start(lp->phy_dev);
3322
3323         netif_start_queue(dev);
3324
3325         return 0;
3326 }
3327
3328 /* Close the interface */
3329 static int at91ether_close(struct net_device *dev)
3330 {
3331         struct macb *lp = netdev_priv(dev);
3332         u32 ctl;
3333
3334         /* Disable Receiver and Transmitter */
3335         ctl = macb_readl(lp, NCR);
3336         macb_writel(lp, NCR, ctl & ~(MACB_BIT(TE) | MACB_BIT(RE)));
3337
3338         /* Disable MAC interrupts */
3339         macb_writel(lp, IDR, MACB_BIT(RCOMP)    |
3340                              MACB_BIT(RXUBR)    |
3341                              MACB_BIT(ISR_TUND) |
3342                              MACB_BIT(ISR_RLE)  |
3343                              MACB_BIT(TCOMP)    |
3344                              MACB_BIT(ISR_ROVR) |
3345                              MACB_BIT(HRESP));
3346
3347         netif_stop_queue(dev);
3348
3349         dma_free_coherent(&lp->pdev->dev,
3350                           AT91ETHER_MAX_RX_DESCR *
3351                           macb_dma_desc_get_size(lp),
3352                           lp->rx_ring, lp->rx_ring_dma);
3353         lp->rx_ring = NULL;
3354
3355         dma_free_coherent(&lp->pdev->dev,
3356                           AT91ETHER_MAX_RX_DESCR * AT91ETHER_MAX_RBUFF_SZ,
3357                           lp->rx_buffers, lp->rx_buffers_dma);
3358         lp->rx_buffers = NULL;
3359
3360         return 0;
3361 }
3362
3363 /* Transmit packet */
3364 static int at91ether_start_xmit(struct sk_buff *skb, struct net_device *dev)
3365 {
3366         struct macb *lp = netdev_priv(dev);
3367
3368         if (macb_readl(lp, TSR) & MACB_BIT(RM9200_BNQ)) {
3369                 netif_stop_queue(dev);
3370
3371                 /* Store packet information (to free when Tx completed) */
3372                 lp->skb = skb;
3373                 lp->skb_length = skb->len;
3374                 lp->skb_physaddr = dma_map_single(NULL, skb->data, skb->len,
3375                                                         DMA_TO_DEVICE);
3376                 if (dma_mapping_error(NULL, lp->skb_physaddr)) {
3377                         dev_kfree_skb_any(skb);
3378                         dev->stats.tx_dropped++;
3379                         netdev_err(dev, "%s: DMA mapping error\n", __func__);
3380                         return NETDEV_TX_OK;
3381                 }
3382
3383                 /* Set address of the data in the Transmit Address register */
3384                 macb_writel(lp, TAR, lp->skb_physaddr);
3385                 /* Set length of the packet in the Transmit Control register */
3386                 macb_writel(lp, TCR, skb->len);
3387
3388         } else {
3389                 netdev_err(dev, "%s called, but device is busy!\n", __func__);
3390                 return NETDEV_TX_BUSY;
3391         }
3392
3393         return NETDEV_TX_OK;
3394 }
3395
3396 /* Extract received frame from buffer descriptors and sent to upper layers.
3397  * (Called from interrupt context)
3398  */
3399 static void at91ether_rx(struct net_device *dev)
3400 {
3401         struct macb *lp = netdev_priv(dev);
3402         struct macb_dma_desc *desc;
3403         unsigned char *p_recv;
3404         struct sk_buff *skb;
3405         unsigned int pktlen;
3406
3407         desc = macb_rx_desc(lp, lp->rx_tail);
3408         while (desc->addr & MACB_BIT(RX_USED)) {
3409                 p_recv = lp->rx_buffers + lp->rx_tail * AT91ETHER_MAX_RBUFF_SZ;
3410                 pktlen = MACB_BF(RX_FRMLEN, desc->ctrl);
3411                 skb = netdev_alloc_skb(dev, pktlen + 2);
3412                 if (skb) {
3413                         skb_reserve(skb, 2);
3414                         memcpy(skb_put(skb, pktlen), p_recv, pktlen);
3415
3416                         skb->protocol = eth_type_trans(skb, dev);
3417                         dev->stats.rx_packets++;
3418                         dev->stats.rx_bytes += pktlen;
3419                         netif_rx(skb);
3420                 } else {
3421                         dev->stats.rx_dropped++;
3422                 }
3423
3424                 if (desc->ctrl & MACB_BIT(RX_MHASH_MATCH))
3425                         dev->stats.multicast++;
3426
3427                 /* reset ownership bit */
3428                 desc->addr &= ~MACB_BIT(RX_USED);
3429
3430                 /* wrap after last buffer */
3431                 if (lp->rx_tail == AT91ETHER_MAX_RX_DESCR - 1)
3432                         lp->rx_tail = 0;
3433                 else
3434                         lp->rx_tail++;
3435
3436                 desc = macb_rx_desc(lp, lp->rx_tail);
3437         }
3438 }
3439
3440 /* MAC interrupt handler */
3441 static irqreturn_t at91ether_interrupt(int irq, void *dev_id)
3442 {
3443         struct net_device *dev = dev_id;
3444         struct macb *lp = netdev_priv(dev);
3445         u32 intstatus, ctl;
3446
3447         /* MAC Interrupt Status register indicates what interrupts are pending.
3448          * It is automatically cleared once read.
3449          */
3450         intstatus = macb_readl(lp, ISR);
3451
3452         /* Receive complete */
3453         if (intstatus & MACB_BIT(RCOMP))
3454                 at91ether_rx(dev);
3455
3456         /* Transmit complete */
3457         if (intstatus & MACB_BIT(TCOMP)) {
3458                 /* The TCOM bit is set even if the transmission failed */
3459                 if (intstatus & (MACB_BIT(ISR_TUND) | MACB_BIT(ISR_RLE)))
3460                         dev->stats.tx_errors++;
3461
3462                 if (lp->skb) {
3463                         dev_kfree_skb_irq(lp->skb);
3464                         lp->skb = NULL;
3465                         dma_unmap_single(NULL, lp->skb_physaddr,
3466                                          lp->skb_length, DMA_TO_DEVICE);
3467                         dev->stats.tx_packets++;
3468                         dev->stats.tx_bytes += lp->skb_length;
3469                 }
3470                 netif_wake_queue(dev);
3471         }
3472
3473         /* Work-around for EMAC Errata section 41.3.1 */
3474         if (intstatus & MACB_BIT(RXUBR)) {
3475                 ctl = macb_readl(lp, NCR);
3476                 macb_writel(lp, NCR, ctl & ~MACB_BIT(RE));
3477                 wmb();
3478                 macb_writel(lp, NCR, ctl | MACB_BIT(RE));
3479         }
3480
3481         if (intstatus & MACB_BIT(ISR_ROVR))
3482                 netdev_err(dev, "ROVR error\n");
3483
3484         return IRQ_HANDLED;
3485 }
3486
3487 #ifdef CONFIG_NET_POLL_CONTROLLER
3488 static void at91ether_poll_controller(struct net_device *dev)
3489 {
3490         unsigned long flags;
3491
3492         local_irq_save(flags);
3493         at91ether_interrupt(dev->irq, dev);
3494         local_irq_restore(flags);
3495 }
3496 #endif
3497
3498 static const struct net_device_ops at91ether_netdev_ops = {
3499         .ndo_open               = at91ether_open,
3500         .ndo_stop               = at91ether_close,
3501         .ndo_start_xmit         = at91ether_start_xmit,
3502         .ndo_get_stats          = macb_get_stats,
3503         .ndo_set_rx_mode        = macb_set_rx_mode,
3504         .ndo_set_mac_address    = eth_mac_addr,
3505         .ndo_do_ioctl           = macb_ioctl,
3506         .ndo_validate_addr      = eth_validate_addr,
3507         .ndo_change_mtu         = eth_change_mtu,
3508 #ifdef CONFIG_NET_POLL_CONTROLLER
3509         .ndo_poll_controller    = at91ether_poll_controller,
3510 #endif
3511 };
3512
3513 static int at91ether_clk_init(struct platform_device *pdev, struct clk **pclk,
3514                               struct clk **hclk, struct clk **tx_clk,
3515                               struct clk **rx_clk, struct clk **tsu_clk)
3516 {
3517         int err;
3518
3519         *hclk = NULL;
3520         *tx_clk = NULL;
3521         *rx_clk = NULL;
3522         *tsu_clk = NULL;
3523
3524         *pclk = devm_clk_get(&pdev->dev, "ether_clk");
3525         if (IS_ERR(*pclk))
3526                 return PTR_ERR(*pclk);
3527
3528         err = clk_prepare_enable(*pclk);
3529         if (err) {
3530                 dev_err(&pdev->dev, "failed to enable pclk (%u)\n", err);
3531                 return err;
3532         }
3533
3534         return 0;
3535 }
3536
3537 static int at91ether_init(struct platform_device *pdev)
3538 {
3539         struct net_device *dev = platform_get_drvdata(pdev);
3540         struct macb *bp = netdev_priv(dev);
3541         int err;
3542         u32 reg;
3543
3544         dev->netdev_ops = &at91ether_netdev_ops;
3545         dev->ethtool_ops = &macb_ethtool_ops;
3546
3547         err = devm_request_irq(&pdev->dev, dev->irq, at91ether_interrupt,
3548                                0, dev->name, dev);
3549         if (err)
3550                 return err;
3551
3552         macb_writel(bp, NCR, 0);
3553
3554         reg = MACB_BF(CLK, MACB_CLK_DIV32) | MACB_BIT(BIG);
3555         if (bp->phy_interface == PHY_INTERFACE_MODE_RMII)
3556                 reg |= MACB_BIT(RM9200_RMII);
3557
3558         macb_writel(bp, NCFGR, reg);
3559
3560         return 0;
3561 }
3562
3563 static const struct macb_config at91sam9260_config = {
3564         .caps = MACB_CAPS_USRIO_HAS_CLKEN | MACB_CAPS_USRIO_DEFAULT_IS_MII_GMII,
3565         .clk_init = macb_clk_init,
3566         .init = macb_init,
3567 };
3568
3569 static const struct macb_config pc302gem_config = {
3570         .caps = MACB_CAPS_SG_DISABLED | MACB_CAPS_GIGABIT_MODE_AVAILABLE,
3571         .dma_burst_length = 16,
3572         .clk_init = macb_clk_init,
3573         .init = macb_init,
3574 };
3575
3576 static const struct macb_config sama5d2_config = {
3577         .caps = MACB_CAPS_USRIO_DEFAULT_IS_MII_GMII,
3578         .dma_burst_length = 16,
3579         .clk_init = macb_clk_init,
3580         .init = macb_init,
3581 };
3582
3583 static const struct macb_config sama5d3_config = {
3584         .caps = MACB_CAPS_SG_DISABLED | MACB_CAPS_GIGABIT_MODE_AVAILABLE
3585               | MACB_CAPS_USRIO_DEFAULT_IS_MII_GMII,
3586         .dma_burst_length = 16,
3587         .clk_init = macb_clk_init,
3588         .init = macb_init,
3589 };
3590
3591 static const struct macb_config sama5d4_config = {
3592         .caps = MACB_CAPS_USRIO_DEFAULT_IS_MII_GMII,
3593         .dma_burst_length = 4,
3594         .clk_init = macb_clk_init,
3595         .init = macb_init,
3596 };
3597
3598 static const struct macb_config emac_config = {
3599         .clk_init = at91ether_clk_init,
3600         .init = at91ether_init,
3601 };
3602
3603 static const struct macb_config np4_config = {
3604         .caps = MACB_CAPS_USRIO_DISABLED,
3605         .clk_init = macb_clk_init,
3606         .init = macb_init,
3607 };
3608
3609 static const struct macb_config zynqmp_config = {
3610         .caps = MACB_CAPS_GIGABIT_MODE_AVAILABLE | MACB_CAPS_JUMBO |
3611                 MACB_CAPS_GEM_HAS_PTP | MACB_CAPS_PCS |
3612                 MACB_CAPS_PARTIAL_STORE_FORWARD | MACB_CAPS_WOL,
3613         .dma_burst_length = 16,
3614         .clk_init = macb_clk_init,
3615         .init = macb_init,
3616         .jumbo_max_len = 10240,
3617 };
3618
3619 static const struct macb_config zynq_config = {
3620         .caps = MACB_CAPS_GIGABIT_MODE_AVAILABLE | MACB_CAPS_NO_GIGABIT_HALF,
3621         .dma_burst_length = 16,
3622         .clk_init = macb_clk_init,
3623         .init = macb_init,
3624 };
3625
3626 static const struct of_device_id macb_dt_ids[] = {
3627         { .compatible = "cdns,at32ap7000-macb" },
3628         { .compatible = "cdns,at91sam9260-macb", .data = &at91sam9260_config },
3629         { .compatible = "cdns,macb" },
3630         { .compatible = "cdns,np4-macb", .data = &np4_config },
3631         { .compatible = "cdns,pc302-gem", .data = &pc302gem_config },
3632         { .compatible = "cdns,gem", .data = &pc302gem_config },
3633         { .compatible = "atmel,sama5d2-gem", .data = &sama5d2_config },
3634         { .compatible = "atmel,sama5d3-gem", .data = &sama5d3_config },
3635         { .compatible = "atmel,sama5d4-gem", .data = &sama5d4_config },
3636         { .compatible = "cdns,at91rm9200-emac", .data = &emac_config },
3637         { .compatible = "cdns,emac", .data = &emac_config },
3638         { .compatible = "cdns,zynqmp-gem", .data = &zynqmp_config},
3639         { .compatible = "cdns,zynq-gem", .data = &zynq_config },
3640         { /* sentinel */ }
3641 };
3642 MODULE_DEVICE_TABLE(of, macb_dt_ids);
3643 #endif /* CONFIG_OF */
3644
3645 static int macb_probe(struct platform_device *pdev)
3646 {
3647         int (*clk_init)(struct platform_device *, struct clk **,
3648                         struct clk **, struct clk **,  struct clk **,
3649                         struct clk **) = macb_clk_init;
3650         int (*init)(struct platform_device *) = macb_init;
3651         struct device_node *np = pdev->dev.of_node;
3652         struct device_node *phy_node;
3653         const struct macb_config *macb_config = NULL;
3654         struct clk *pclk, *hclk = NULL, *tx_clk = NULL, *rx_clk = NULL;
3655         struct clk *tsu_clk = NULL;
3656         unsigned int queue_mask, num_queues;
3657         struct macb_platform_data *pdata;
3658         bool native_io;
3659         struct phy_device *phydev;
3660         struct net_device *dev;
3661         struct resource *regs;
3662         void __iomem *mem;
3663         const char *mac;
3664         struct macb *bp;
3665         int err;
3666
3667         regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
3668         mem = devm_ioremap_resource(&pdev->dev, regs);
3669         if (IS_ERR(mem))
3670                 return PTR_ERR(mem);
3671
3672         if (np) {
3673                 const struct of_device_id *match;
3674
3675                 match = of_match_node(macb_dt_ids, np);
3676                 if (match && match->data) {
3677                         macb_config = match->data;
3678                         clk_init = macb_config->clk_init;
3679                         init = macb_config->init;
3680                 }
3681         }
3682
3683         err = clk_init(pdev, &pclk, &hclk, &tx_clk, &rx_clk, &tsu_clk);
3684         if (err)
3685                 return err;
3686
3687         pm_runtime_set_autosuspend_delay(&pdev->dev, MACB_PM_TIMEOUT);
3688         pm_runtime_use_autosuspend(&pdev->dev);
3689         pm_runtime_get_noresume(&pdev->dev);
3690         pm_runtime_set_active(&pdev->dev);
3691         pm_runtime_enable(&pdev->dev);
3692         native_io = hw_is_native_io(mem);
3693
3694         macb_probe_queues(mem, native_io, &queue_mask, &num_queues);
3695         dev = alloc_etherdev_mq(sizeof(*bp), num_queues);
3696         if (!dev) {
3697                 err = -ENOMEM;
3698                 goto err_disable_clocks;
3699         }
3700
3701         dev->base_addr = regs->start;
3702
3703         SET_NETDEV_DEV(dev, &pdev->dev);
3704
3705         bp = netdev_priv(dev);
3706         bp->pdev = pdev;
3707         bp->dev = dev;
3708         bp->regs = mem;
3709         bp->native_io = native_io;
3710         if (native_io) {
3711                 bp->macb_reg_readl = hw_readl_native;
3712                 bp->macb_reg_writel = hw_writel_native;
3713         } else {
3714                 bp->macb_reg_readl = hw_readl;
3715                 bp->macb_reg_writel = hw_writel;
3716         }
3717         bp->num_queues = num_queues;
3718         bp->queue_mask = queue_mask;
3719         if (macb_config)
3720                 bp->dma_burst_length = macb_config->dma_burst_length;
3721         bp->pclk = pclk;
3722         bp->hclk = hclk;
3723         bp->tx_clk = tx_clk;
3724         bp->rx_clk = rx_clk;
3725         bp->tsu_clk = tsu_clk;
3726         if (tsu_clk)
3727                 bp->tsu_rate = clk_get_rate(tsu_clk);
3728
3729         if (macb_config)
3730                 bp->jumbo_max_len = macb_config->jumbo_max_len;
3731
3732         spin_lock_init(&bp->lock);
3733
3734         /* setup capabilities */
3735         macb_configure_caps(bp, macb_config);
3736
3737 #ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
3738         if (GEM_BFEXT(DAW64, gem_readl(bp, DCFG6))) {
3739                 dma_set_mask(&pdev->dev, DMA_BIT_MASK(44));
3740                 bp->hw_dma_cap |= HW_DMA_CAP_64B;
3741         }
3742 #endif
3743         platform_set_drvdata(pdev, dev);
3744
3745         dev->irq = platform_get_irq(pdev, 0);
3746         if (dev->irq < 0) {
3747                 err = dev->irq;
3748                 goto err_out_free_netdev;
3749         }
3750
3751         /* MTU range: 68 - 1500 or 10240 */
3752         dev->min_mtu = GEM_MTU_MIN_SIZE;
3753         if (bp->caps & MACB_CAPS_JUMBO)
3754                 dev->max_mtu = gem_readl(bp, JML) - ETH_HLEN - ETH_FCS_LEN;
3755         else
3756                 dev->max_mtu = ETH_DATA_LEN;
3757
3758         mac = of_get_mac_address(np);
3759         if (mac)
3760                 ether_addr_copy(bp->dev->dev_addr, mac);
3761         else
3762                 macb_get_hwaddr(bp);
3763
3764         /* Power up the PHY if there is a GPIO reset */
3765         phy_node = of_parse_phandle(np, "phy-handle", 0);
3766         if (!phy_node && of_phy_is_fixed_link(np)) {
3767                 err = of_phy_register_fixed_link(np);
3768                 if (err < 0) {
3769                         dev_err(&pdev->dev, "broken fixed-link specification");
3770                         goto failed_phy;
3771                 }
3772                 phy_node = of_node_get(np);
3773                 bp->phy_node = phy_node;
3774         } else {
3775                 int gpio = of_get_named_gpio(phy_node, "reset-gpios", 0);
3776                 if (gpio_is_valid(gpio)) {
3777                         bp->reset_gpio = gpio_to_desc(gpio);
3778                         gpiod_direction_output(bp->reset_gpio, 1);
3779                 }
3780         }
3781
3782         err = of_get_phy_mode(np);
3783         if (err < 0) {
3784                 pdata = dev_get_platdata(&pdev->dev);
3785                 if (pdata && pdata->is_rmii)
3786                         bp->phy_interface = PHY_INTERFACE_MODE_RMII;
3787                 else
3788                         bp->phy_interface = PHY_INTERFACE_MODE_MII;
3789         } else {
3790                 bp->phy_interface = err;
3791         }
3792
3793         macb_reset_phy(pdev);
3794
3795         /* IP specific init */
3796         err = init(pdev);
3797         if (err)
3798                 goto err_out_free_netdev;
3799
3800         err = register_netdev(dev);
3801         if (err) {
3802                 dev_err(&pdev->dev, "Cannot register net device, aborting.\n");
3803                 goto err_out_unregister_netdev;
3804         }
3805
3806         err = macb_mii_init(bp);
3807         if (err)
3808                 goto err_out_unregister_netdev;
3809
3810         netif_carrier_off(dev);
3811
3812         tasklet_init(&bp->hresp_err_tasklet, macb_hresp_error_task,
3813                      (unsigned long)bp);
3814
3815         if (bp->caps & MACB_CAPS_WOL)
3816                 device_set_wakeup_capable(&bp->dev->dev, 1);
3817
3818         netdev_info(dev, "Cadence %s rev 0x%08x at 0x%08lx irq %d (%pM)\n",
3819                     macb_is_gem(bp) ? "GEM" : "MACB", macb_readl(bp, MID),
3820                     dev->base_addr, dev->irq, dev->dev_addr);
3821
3822         phydev = bp->phy_dev;
3823         phy_attached_info(phydev);
3824         pm_runtime_mark_last_busy(&bp->pdev->dev);
3825         pm_runtime_put_autosuspend(&bp->pdev->dev);
3826
3827         return 0;
3828
3829 err_out_unregister_netdev:
3830         unregister_netdev(dev);
3831
3832 err_out_free_netdev:
3833         free_netdev(dev);
3834
3835 failed_phy:
3836         of_node_put(phy_node);
3837
3838 err_disable_clocks:
3839         clk_disable_unprepare(tx_clk);
3840         clk_disable_unprepare(hclk);
3841         clk_disable_unprepare(pclk);
3842         clk_disable_unprepare(rx_clk);
3843         clk_disable_unprepare(tsu_clk);
3844         pm_runtime_disable(&pdev->dev);
3845         pm_runtime_set_suspended(&pdev->dev);
3846         pm_runtime_dont_use_autosuspend(&pdev->dev);
3847
3848         return err;
3849 }
3850
3851 static int macb_remove(struct platform_device *pdev)
3852 {
3853         struct net_device *dev;
3854         struct macb *bp;
3855
3856         dev = platform_get_drvdata(pdev);
3857
3858         if (dev) {
3859                 bp = netdev_priv(dev);
3860                 if (bp->phy_dev)
3861                         phy_disconnect(bp->phy_dev);
3862                 mdiobus_unregister(bp->mii_bus);
3863                 dev->phydev = NULL;
3864                 mdiobus_free(bp->mii_bus);
3865
3866                 /* Shutdown the PHY if there is a GPIO reset */
3867                 if (bp->reset_gpio)
3868                         gpiod_set_value(bp->reset_gpio, 0);
3869
3870                 unregister_netdev(dev);
3871                 pm_runtime_disable(&pdev->dev);
3872                 pm_runtime_dont_use_autosuspend(&pdev->dev);
3873                 if (!pm_runtime_suspended(&pdev->dev)) {
3874                         clk_disable_unprepare(bp->tx_clk);
3875                         clk_disable_unprepare(bp->hclk);
3876                         clk_disable_unprepare(bp->pclk);
3877                         clk_disable_unprepare(bp->rx_clk);
3878                         clk_disable_unprepare(bp->tsu_clk);
3879                         pm_runtime_set_suspended(&pdev->dev);
3880                 }
3881                 of_node_put(bp->phy_node);
3882                 free_netdev(dev);
3883         }
3884
3885         return 0;
3886 }
3887
3888 static int __maybe_unused macb_suspend(struct device *dev)
3889 {
3890         struct platform_device *pdev = to_platform_device(dev);
3891         struct net_device *netdev = platform_get_drvdata(pdev);
3892         struct macb *bp = netdev_priv(netdev);
3893         struct macb_queue *queue = bp->queues;
3894         unsigned long flags;
3895         unsigned int q;
3896         u32 ctrl, arpipmask;
3897
3898         if (!netif_running(netdev))
3899                 return 0;
3900
3901         if (device_may_wakeup(&bp->dev->dev)) {
3902                 spin_lock_irqsave(&bp->lock, flags);
3903                 ctrl = macb_readl(bp, NCR);
3904                 ctrl &= ~(MACB_BIT(TE) | MACB_BIT(RE));
3905                 macb_writel(bp, NCR, ctrl);
3906                 /* Tie off RXQ0 as well */
3907                 macb_writel(bp, RBQP, lower_32_bits(bp->rx_ring_tieoff_dma));
3908                 ctrl = macb_readl(bp, NCR);
3909                 ctrl |= MACB_BIT(RE);
3910                 macb_writel(bp, NCR, ctrl);
3911                 gem_writel(bp, NCFGR, gem_readl(bp, NCFGR) & ~MACB_BIT(NBC));
3912                 macb_writel(bp, TSR, -1);
3913                 macb_writel(bp, RSR, -1);
3914                 macb_readl(bp, ISR);
3915                 if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
3916                         macb_writel(bp, ISR, -1);
3917
3918                 /* Enable WOL (Q0 only) and disable all other interrupts */
3919                 macb_writel(bp, IER, MACB_BIT(WOL));
3920                 for (q = 1, queue = bp->queues; q < bp->num_queues;
3921                      ++q, ++queue) {
3922                         queue_writel(queue, IDR, MACB_RX_INT_FLAGS |
3923                                                  MACB_TX_INT_FLAGS |
3924                                                  MACB_BIT(HRESP));
3925                 }
3926
3927                 arpipmask = cpu_to_be32p(&bp->dev->ip_ptr->ifa_list->ifa_local)
3928                                          & 0xFFFF;
3929                 gem_writel(bp, WOL, MACB_BIT(ARP) | arpipmask);
3930                 spin_unlock_irqrestore(&bp->lock, flags);
3931                 enable_irq_wake(bp->queues[0].irq);
3932                 netif_device_detach(netdev);
3933                 napi_disable(&bp->napi);
3934         } else {
3935                 netif_device_detach(netdev);
3936                 napi_disable(&bp->napi);
3937                 phy_stop(bp->phy_dev);
3938                 phy_suspend(bp->phy_dev);
3939                 spin_lock_irqsave(&bp->lock, flags);
3940                 macb_reset_hw(bp);
3941                 spin_unlock_irqrestore(&bp->lock, flags);
3942         }
3943
3944         netif_carrier_off(netdev);
3945         if (bp->ptp_info)
3946                 bp->ptp_info->ptp_remove(netdev);
3947         pm_runtime_force_suspend(dev);
3948
3949         return 0;
3950 }
3951
3952 static int __maybe_unused macb_resume(struct device *dev)
3953 {
3954         struct platform_device *pdev = to_platform_device(dev);
3955         struct net_device *netdev = platform_get_drvdata(pdev);
3956         struct macb *bp = netdev_priv(netdev);
3957         unsigned long flags;
3958
3959         if (!netif_running(netdev))
3960                 return 0;
3961
3962         pm_runtime_force_resume(dev);
3963
3964         if (device_may_wakeup(&bp->dev->dev)) {
3965                 spin_lock_irqsave(&bp->lock, flags);
3966                 macb_writel(bp, IDR, MACB_BIT(WOL));
3967                 gem_writel(bp, WOL, 0);
3968                 /* Clear Q0 ISR as WOL was enabled on Q0 */
3969                 if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
3970                         macb_writel(bp, ISR, -1);
3971                 disable_irq_wake(bp->queues[0].irq);
3972                 spin_unlock_irqrestore(&bp->lock, flags);
3973                 macb_writel(bp, NCR, MACB_BIT(MPE));
3974                 napi_enable(&bp->napi);
3975                 netif_carrier_on(netdev);
3976         } else {
3977                 macb_writel(bp, NCR, MACB_BIT(MPE));
3978                 napi_enable(&bp->napi);
3979                 netif_carrier_on(netdev);
3980                 phy_resume(bp->phy_dev);
3981                 phy_start(bp->phy_dev);
3982         }
3983
3984         bp->macbgem_ops.mog_init_rings(bp);
3985         macb_init_hw(bp);
3986         macb_set_rx_mode(netdev);
3987         netif_device_attach(netdev);
3988         if (bp->ptp_info)
3989                 bp->ptp_info->ptp_init(netdev);
3990
3991         return 0;
3992 }
3993
3994 static int __maybe_unused macb_runtime_suspend(struct device *dev)
3995 {
3996         struct platform_device *pdev = to_platform_device(dev);
3997         struct net_device *netdev = platform_get_drvdata(pdev);
3998         struct macb *bp = netdev_priv(netdev);
3999
4000         if (!(device_may_wakeup(&bp->dev->dev))) {
4001                 clk_disable_unprepare(bp->tx_clk);
4002                 clk_disable_unprepare(bp->hclk);
4003                 clk_disable_unprepare(bp->pclk);
4004                 clk_disable_unprepare(bp->rx_clk);
4005         }
4006         clk_disable_unprepare(bp->tsu_clk);
4007
4008         return 0;
4009 }
4010
4011 static int __maybe_unused macb_runtime_resume(struct device *dev)
4012 {
4013         struct platform_device *pdev = to_platform_device(dev);
4014         struct net_device *netdev = platform_get_drvdata(pdev);
4015         struct macb *bp = netdev_priv(netdev);
4016
4017         if (!(device_may_wakeup(&bp->dev->dev))) {
4018                 clk_prepare_enable(bp->pclk);
4019                 clk_prepare_enable(bp->hclk);
4020                 clk_prepare_enable(bp->tx_clk);
4021                 clk_prepare_enable(bp->rx_clk);
4022         }
4023         clk_prepare_enable(bp->tsu_clk);
4024
4025         return 0;
4026 }
4027
4028 static const struct dev_pm_ops macb_pm_ops = {
4029         SET_SYSTEM_SLEEP_PM_OPS(macb_suspend, macb_resume)
4030         SET_RUNTIME_PM_OPS(macb_runtime_suspend, macb_runtime_resume, NULL)
4031 };
4032
4033 static struct platform_driver macb_driver = {
4034         .probe          = macb_probe,
4035         .remove         = macb_remove,
4036         .driver         = {
4037                 .name           = "macb",
4038                 .of_match_table = of_match_ptr(macb_dt_ids),
4039                 .pm     = &macb_pm_ops,
4040         },
4041 };
4042
4043 module_platform_driver(macb_driver);
4044
4045 MODULE_LICENSE("GPL");
4046 MODULE_DESCRIPTION("Cadence MACB/GEM Ethernet driver");
4047 MODULE_AUTHOR("Haavard Skinnemoen (Atmel)");
4048 MODULE_ALIAS("platform:macb");