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