net: ethernet: cadence-macb: Add disabled usrio caps
[cascardo/linux.git] / drivers / net / ethernet / cadence / macb.c
1 /*
2  * Cadence MACB/GEM Ethernet Controller driver
3  *
4  * Copyright (C) 2004-2006 Atmel Corporation
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  */
10
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 #include <linux/clk.h>
13 #include <linux/module.h>
14 #include <linux/moduleparam.h>
15 #include <linux/kernel.h>
16 #include <linux/types.h>
17 #include <linux/circ_buf.h>
18 #include <linux/slab.h>
19 #include <linux/init.h>
20 #include <linux/io.h>
21 #include <linux/gpio.h>
22 #include <linux/gpio/consumer.h>
23 #include <linux/interrupt.h>
24 #include <linux/netdevice.h>
25 #include <linux/etherdevice.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/platform_data/macb.h>
28 #include <linux/platform_device.h>
29 #include <linux/phy.h>
30 #include <linux/of.h>
31 #include <linux/of_device.h>
32 #include <linux/of_gpio.h>
33 #include <linux/of_mdio.h>
34 #include <linux/of_net.h>
35
36 #include "macb.h"
37
38 #define MACB_RX_BUFFER_SIZE     128
39 #define RX_BUFFER_MULTIPLE      64  /* bytes */
40 #define RX_RING_SIZE            512 /* must be power of 2 */
41 #define RX_RING_BYTES           (sizeof(struct macb_dma_desc) * RX_RING_SIZE)
42
43 #define TX_RING_SIZE            128 /* must be power of 2 */
44 #define TX_RING_BYTES           (sizeof(struct macb_dma_desc) * TX_RING_SIZE)
45
46 /* level of occupied TX descriptors under which we wake up TX process */
47 #define MACB_TX_WAKEUP_THRESH   (3 * TX_RING_SIZE / 4)
48
49 #define MACB_RX_INT_FLAGS       (MACB_BIT(RCOMP) | MACB_BIT(RXUBR)      \
50                                  | MACB_BIT(ISR_ROVR))
51 #define MACB_TX_ERR_FLAGS       (MACB_BIT(ISR_TUND)                     \
52                                         | MACB_BIT(ISR_RLE)             \
53                                         | MACB_BIT(TXERR))
54 #define MACB_TX_INT_FLAGS       (MACB_TX_ERR_FLAGS | MACB_BIT(TCOMP))
55
56 #define MACB_MAX_TX_LEN         ((unsigned int)((1 << MACB_TX_FRMLEN_SIZE) - 1))
57 #define GEM_MAX_TX_LEN          ((unsigned int)((1 << GEM_TX_FRMLEN_SIZE) - 1))
58
59 #define GEM_MTU_MIN_SIZE        68
60
61 /*
62  * Graceful stop timeouts in us. We should allow up to
63  * 1 frame time (10 Mbits/s, full-duplex, ignoring collisions)
64  */
65 #define MACB_HALT_TIMEOUT       1230
66
67 /* Ring buffer accessors */
68 static unsigned int macb_tx_ring_wrap(unsigned int index)
69 {
70         return index & (TX_RING_SIZE - 1);
71 }
72
73 static struct macb_dma_desc *macb_tx_desc(struct macb_queue *queue,
74                                           unsigned int index)
75 {
76         return &queue->tx_ring[macb_tx_ring_wrap(index)];
77 }
78
79 static struct macb_tx_skb *macb_tx_skb(struct macb_queue *queue,
80                                        unsigned int index)
81 {
82         return &queue->tx_skb[macb_tx_ring_wrap(index)];
83 }
84
85 static dma_addr_t macb_tx_dma(struct macb_queue *queue, unsigned int index)
86 {
87         dma_addr_t offset;
88
89         offset = macb_tx_ring_wrap(index) * sizeof(struct macb_dma_desc);
90
91         return queue->tx_ring_dma + offset;
92 }
93
94 static unsigned int macb_rx_ring_wrap(unsigned int index)
95 {
96         return index & (RX_RING_SIZE - 1);
97 }
98
99 static struct macb_dma_desc *macb_rx_desc(struct macb *bp, unsigned int index)
100 {
101         return &bp->rx_ring[macb_rx_ring_wrap(index)];
102 }
103
104 static void *macb_rx_buffer(struct macb *bp, unsigned int index)
105 {
106         return bp->rx_buffers + bp->rx_buffer_size * macb_rx_ring_wrap(index);
107 }
108
109 /* I/O accessors */
110 static u32 hw_readl_native(struct macb *bp, int offset)
111 {
112         return __raw_readl(bp->regs + offset);
113 }
114
115 static void hw_writel_native(struct macb *bp, int offset, u32 value)
116 {
117         __raw_writel(value, bp->regs + offset);
118 }
119
120 static u32 hw_readl(struct macb *bp, int offset)
121 {
122         return readl_relaxed(bp->regs + offset);
123 }
124
125 static void hw_writel(struct macb *bp, int offset, u32 value)
126 {
127         writel_relaxed(value, bp->regs + offset);
128 }
129
130 /*
131  * Find the CPU endianness by using the loopback bit of NCR register. When the
132  * CPU is in big endian we need to program swaped mode for management
133  * descriptor access.
134  */
135 static bool hw_is_native_io(void __iomem *addr)
136 {
137         u32 value = MACB_BIT(LLB);
138
139         __raw_writel(value, addr + MACB_NCR);
140         value = __raw_readl(addr + MACB_NCR);
141
142         /* Write 0 back to disable everything */
143         __raw_writel(0, addr + MACB_NCR);
144
145         return value == MACB_BIT(LLB);
146 }
147
148 static bool hw_is_gem(void __iomem *addr, bool native_io)
149 {
150         u32 id;
151
152         if (native_io)
153                 id = __raw_readl(addr + MACB_MID);
154         else
155                 id = readl_relaxed(addr + MACB_MID);
156
157         return MACB_BFEXT(IDNUM, id) >= 0x2;
158 }
159
160 static void macb_set_hwaddr(struct macb *bp)
161 {
162         u32 bottom;
163         u16 top;
164
165         bottom = cpu_to_le32(*((u32 *)bp->dev->dev_addr));
166         macb_or_gem_writel(bp, SA1B, bottom);
167         top = cpu_to_le16(*((u16 *)(bp->dev->dev_addr + 4)));
168         macb_or_gem_writel(bp, SA1T, top);
169
170         /* Clear unused address register sets */
171         macb_or_gem_writel(bp, SA2B, 0);
172         macb_or_gem_writel(bp, SA2T, 0);
173         macb_or_gem_writel(bp, SA3B, 0);
174         macb_or_gem_writel(bp, SA3T, 0);
175         macb_or_gem_writel(bp, SA4B, 0);
176         macb_or_gem_writel(bp, SA4T, 0);
177 }
178
179 static void macb_get_hwaddr(struct macb *bp)
180 {
181         struct macb_platform_data *pdata;
182         u32 bottom;
183         u16 top;
184         u8 addr[6];
185         int i;
186
187         pdata = dev_get_platdata(&bp->pdev->dev);
188
189         /* Check all 4 address register for vaild address */
190         for (i = 0; i < 4; i++) {
191                 bottom = macb_or_gem_readl(bp, SA1B + i * 8);
192                 top = macb_or_gem_readl(bp, SA1T + i * 8);
193
194                 if (pdata && pdata->rev_eth_addr) {
195                         addr[5] = bottom & 0xff;
196                         addr[4] = (bottom >> 8) & 0xff;
197                         addr[3] = (bottom >> 16) & 0xff;
198                         addr[2] = (bottom >> 24) & 0xff;
199                         addr[1] = top & 0xff;
200                         addr[0] = (top & 0xff00) >> 8;
201                 } else {
202                         addr[0] = bottom & 0xff;
203                         addr[1] = (bottom >> 8) & 0xff;
204                         addr[2] = (bottom >> 16) & 0xff;
205                         addr[3] = (bottom >> 24) & 0xff;
206                         addr[4] = top & 0xff;
207                         addr[5] = (top >> 8) & 0xff;
208                 }
209
210                 if (is_valid_ether_addr(addr)) {
211                         memcpy(bp->dev->dev_addr, addr, sizeof(addr));
212                         return;
213                 }
214         }
215
216         dev_info(&bp->pdev->dev, "invalid hw address, using random\n");
217         eth_hw_addr_random(bp->dev);
218 }
219
220 static int macb_mdio_read(struct mii_bus *bus, int mii_id, int regnum)
221 {
222         struct macb *bp = bus->priv;
223         int value;
224
225         macb_writel(bp, MAN, (MACB_BF(SOF, MACB_MAN_SOF)
226                               | MACB_BF(RW, MACB_MAN_READ)
227                               | MACB_BF(PHYA, mii_id)
228                               | MACB_BF(REGA, regnum)
229                               | MACB_BF(CODE, MACB_MAN_CODE)));
230
231         /* wait for end of transfer */
232         while (!MACB_BFEXT(IDLE, macb_readl(bp, NSR)))
233                 cpu_relax();
234
235         value = MACB_BFEXT(DATA, macb_readl(bp, MAN));
236
237         return value;
238 }
239
240 static int macb_mdio_write(struct mii_bus *bus, int mii_id, int regnum,
241                            u16 value)
242 {
243         struct macb *bp = bus->priv;
244
245         macb_writel(bp, MAN, (MACB_BF(SOF, MACB_MAN_SOF)
246                               | MACB_BF(RW, MACB_MAN_WRITE)
247                               | MACB_BF(PHYA, mii_id)
248                               | MACB_BF(REGA, regnum)
249                               | MACB_BF(CODE, MACB_MAN_CODE)
250                               | MACB_BF(DATA, value)));
251
252         /* wait for end of transfer */
253         while (!MACB_BFEXT(IDLE, macb_readl(bp, NSR)))
254                 cpu_relax();
255
256         return 0;
257 }
258
259 /**
260  * macb_set_tx_clk() - Set a clock to a new frequency
261  * @clk         Pointer to the clock to change
262  * @rate        New frequency in Hz
263  * @dev         Pointer to the struct net_device
264  */
265 static void macb_set_tx_clk(struct clk *clk, int speed, struct net_device *dev)
266 {
267         long ferr, rate, rate_rounded;
268
269         if (!clk)
270                 return;
271
272         switch (speed) {
273         case SPEED_10:
274                 rate = 2500000;
275                 break;
276         case SPEED_100:
277                 rate = 25000000;
278                 break;
279         case SPEED_1000:
280                 rate = 125000000;
281                 break;
282         default:
283                 return;
284         }
285
286         rate_rounded = clk_round_rate(clk, rate);
287         if (rate_rounded < 0)
288                 return;
289
290         /* RGMII allows 50 ppm frequency error. Test and warn if this limit
291          * is not satisfied.
292          */
293         ferr = abs(rate_rounded - rate);
294         ferr = DIV_ROUND_UP(ferr, rate / 100000);
295         if (ferr > 5)
296                 netdev_warn(dev, "unable to generate target frequency: %ld Hz\n",
297                                 rate);
298
299         if (clk_set_rate(clk, rate_rounded))
300                 netdev_err(dev, "adjusting tx_clk failed.\n");
301 }
302
303 static void macb_handle_link_change(struct net_device *dev)
304 {
305         struct macb *bp = netdev_priv(dev);
306         struct phy_device *phydev = bp->phy_dev;
307         unsigned long flags;
308         int status_change = 0;
309
310         spin_lock_irqsave(&bp->lock, flags);
311
312         if (phydev->link) {
313                 if ((bp->speed != phydev->speed) ||
314                     (bp->duplex != phydev->duplex)) {
315                         u32 reg;
316
317                         reg = macb_readl(bp, NCFGR);
318                         reg &= ~(MACB_BIT(SPD) | MACB_BIT(FD));
319                         if (macb_is_gem(bp))
320                                 reg &= ~GEM_BIT(GBE);
321
322                         if (phydev->duplex)
323                                 reg |= MACB_BIT(FD);
324                         if (phydev->speed == SPEED_100)
325                                 reg |= MACB_BIT(SPD);
326                         if (phydev->speed == SPEED_1000 &&
327                             bp->caps & MACB_CAPS_GIGABIT_MODE_AVAILABLE)
328                                 reg |= GEM_BIT(GBE);
329
330                         macb_or_gem_writel(bp, NCFGR, reg);
331
332                         bp->speed = phydev->speed;
333                         bp->duplex = phydev->duplex;
334                         status_change = 1;
335                 }
336         }
337
338         if (phydev->link != bp->link) {
339                 if (!phydev->link) {
340                         bp->speed = 0;
341                         bp->duplex = -1;
342                 }
343                 bp->link = phydev->link;
344
345                 status_change = 1;
346         }
347
348         spin_unlock_irqrestore(&bp->lock, flags);
349
350         if (status_change) {
351                 if (phydev->link) {
352                         /* Update the TX clock rate if and only if the link is
353                          * up and there has been a link change.
354                          */
355                         macb_set_tx_clk(bp->tx_clk, phydev->speed, dev);
356
357                         netif_carrier_on(dev);
358                         netdev_info(dev, "link up (%d/%s)\n",
359                                     phydev->speed,
360                                     phydev->duplex == DUPLEX_FULL ?
361                                     "Full" : "Half");
362                 } else {
363                         netif_carrier_off(dev);
364                         netdev_info(dev, "link down\n");
365                 }
366         }
367 }
368
369 /* based on au1000_eth. c*/
370 static int macb_mii_probe(struct net_device *dev)
371 {
372         struct macb *bp = netdev_priv(dev);
373         struct macb_platform_data *pdata;
374         struct phy_device *phydev;
375         int phy_irq;
376         int ret;
377
378         phydev = phy_find_first(bp->mii_bus);
379         if (!phydev) {
380                 netdev_err(dev, "no PHY found\n");
381                 return -ENXIO;
382         }
383
384         pdata = dev_get_platdata(&bp->pdev->dev);
385         if (pdata && gpio_is_valid(pdata->phy_irq_pin)) {
386                 ret = devm_gpio_request(&bp->pdev->dev, pdata->phy_irq_pin, "phy int");
387                 if (!ret) {
388                         phy_irq = gpio_to_irq(pdata->phy_irq_pin);
389                         phydev->irq = (phy_irq < 0) ? PHY_POLL : phy_irq;
390                 }
391         }
392
393         /* attach the mac to the phy */
394         ret = phy_connect_direct(dev, phydev, &macb_handle_link_change,
395                                  bp->phy_interface);
396         if (ret) {
397                 netdev_err(dev, "Could not attach to PHY\n");
398                 return ret;
399         }
400
401         /* mask with MAC supported features */
402         if (macb_is_gem(bp) && bp->caps & MACB_CAPS_GIGABIT_MODE_AVAILABLE)
403                 phydev->supported &= PHY_GBIT_FEATURES;
404         else
405                 phydev->supported &= PHY_BASIC_FEATURES;
406
407         if (bp->caps & MACB_CAPS_NO_GIGABIT_HALF)
408                 phydev->supported &= ~SUPPORTED_1000baseT_Half;
409
410         phydev->advertising = phydev->supported;
411
412         bp->link = 0;
413         bp->speed = 0;
414         bp->duplex = -1;
415         bp->phy_dev = phydev;
416
417         return 0;
418 }
419
420 static int macb_mii_init(struct macb *bp)
421 {
422         struct macb_platform_data *pdata;
423         struct device_node *np;
424         int err = -ENXIO, i;
425
426         /* Enable management port */
427         macb_writel(bp, NCR, MACB_BIT(MPE));
428
429         bp->mii_bus = mdiobus_alloc();
430         if (bp->mii_bus == NULL) {
431                 err = -ENOMEM;
432                 goto err_out;
433         }
434
435         bp->mii_bus->name = "MACB_mii_bus";
436         bp->mii_bus->read = &macb_mdio_read;
437         bp->mii_bus->write = &macb_mdio_write;
438         snprintf(bp->mii_bus->id, MII_BUS_ID_SIZE, "%s-%x",
439                 bp->pdev->name, bp->pdev->id);
440         bp->mii_bus->priv = bp;
441         bp->mii_bus->parent = &bp->dev->dev;
442         pdata = dev_get_platdata(&bp->pdev->dev);
443
444         dev_set_drvdata(&bp->dev->dev, bp->mii_bus);
445
446         np = bp->pdev->dev.of_node;
447         if (np) {
448                 /* try dt phy registration */
449                 err = of_mdiobus_register(bp->mii_bus, np);
450
451                 /* fallback to standard phy registration if no phy were
452                    found during dt phy registration */
453                 if (!err && !phy_find_first(bp->mii_bus)) {
454                         for (i = 0; i < PHY_MAX_ADDR; i++) {
455                                 struct phy_device *phydev;
456
457                                 phydev = mdiobus_scan(bp->mii_bus, i);
458                                 if (IS_ERR(phydev)) {
459                                         err = PTR_ERR(phydev);
460                                         break;
461                                 }
462                         }
463
464                         if (err)
465                                 goto err_out_unregister_bus;
466                 }
467         } else {
468                 if (pdata)
469                         bp->mii_bus->phy_mask = pdata->phy_mask;
470
471                 err = mdiobus_register(bp->mii_bus);
472         }
473
474         if (err)
475                 goto err_out_free_mdiobus;
476
477         err = macb_mii_probe(bp->dev);
478         if (err)
479                 goto err_out_unregister_bus;
480
481         return 0;
482
483 err_out_unregister_bus:
484         mdiobus_unregister(bp->mii_bus);
485 err_out_free_mdiobus:
486         mdiobus_free(bp->mii_bus);
487 err_out:
488         return err;
489 }
490
491 static void macb_update_stats(struct macb *bp)
492 {
493         u32 *p = &bp->hw_stats.macb.rx_pause_frames;
494         u32 *end = &bp->hw_stats.macb.tx_pause_frames + 1;
495         int offset = MACB_PFR;
496
497         WARN_ON((unsigned long)(end - p - 1) != (MACB_TPF - MACB_PFR) / 4);
498
499         for(; p < end; p++, offset += 4)
500                 *p += bp->macb_reg_readl(bp, offset);
501 }
502
503 static int macb_halt_tx(struct macb *bp)
504 {
505         unsigned long   halt_time, timeout;
506         u32             status;
507
508         macb_writel(bp, NCR, macb_readl(bp, NCR) | MACB_BIT(THALT));
509
510         timeout = jiffies + usecs_to_jiffies(MACB_HALT_TIMEOUT);
511         do {
512                 halt_time = jiffies;
513                 status = macb_readl(bp, TSR);
514                 if (!(status & MACB_BIT(TGO)))
515                         return 0;
516
517                 usleep_range(10, 250);
518         } while (time_before(halt_time, timeout));
519
520         return -ETIMEDOUT;
521 }
522
523 static void macb_tx_unmap(struct macb *bp, struct macb_tx_skb *tx_skb)
524 {
525         if (tx_skb->mapping) {
526                 if (tx_skb->mapped_as_page)
527                         dma_unmap_page(&bp->pdev->dev, tx_skb->mapping,
528                                        tx_skb->size, DMA_TO_DEVICE);
529                 else
530                         dma_unmap_single(&bp->pdev->dev, tx_skb->mapping,
531                                          tx_skb->size, DMA_TO_DEVICE);
532                 tx_skb->mapping = 0;
533         }
534
535         if (tx_skb->skb) {
536                 dev_kfree_skb_any(tx_skb->skb);
537                 tx_skb->skb = NULL;
538         }
539 }
540
541 static void macb_tx_error_task(struct work_struct *work)
542 {
543         struct macb_queue       *queue = container_of(work, struct macb_queue,
544                                                       tx_error_task);
545         struct macb             *bp = queue->bp;
546         struct macb_tx_skb      *tx_skb;
547         struct macb_dma_desc    *desc;
548         struct sk_buff          *skb;
549         unsigned int            tail;
550         unsigned long           flags;
551
552         netdev_vdbg(bp->dev, "macb_tx_error_task: q = %u, t = %u, h = %u\n",
553                     (unsigned int)(queue - bp->queues),
554                     queue->tx_tail, queue->tx_head);
555
556         /* Prevent the queue IRQ handlers from running: each of them may call
557          * macb_tx_interrupt(), which in turn may call netif_wake_subqueue().
558          * As explained below, we have to halt the transmission before updating
559          * TBQP registers so we call netif_tx_stop_all_queues() to notify the
560          * network engine about the macb/gem being halted.
561          */
562         spin_lock_irqsave(&bp->lock, flags);
563
564         /* Make sure nobody is trying to queue up new packets */
565         netif_tx_stop_all_queues(bp->dev);
566
567         /*
568          * Stop transmission now
569          * (in case we have just queued new packets)
570          * macb/gem must be halted to write TBQP register
571          */
572         if (macb_halt_tx(bp))
573                 /* Just complain for now, reinitializing TX path can be good */
574                 netdev_err(bp->dev, "BUG: halt tx timed out\n");
575
576         /*
577          * Treat frames in TX queue including the ones that caused the error.
578          * Free transmit buffers in upper layer.
579          */
580         for (tail = queue->tx_tail; tail != queue->tx_head; tail++) {
581                 u32     ctrl;
582
583                 desc = macb_tx_desc(queue, tail);
584                 ctrl = desc->ctrl;
585                 tx_skb = macb_tx_skb(queue, tail);
586                 skb = tx_skb->skb;
587
588                 if (ctrl & MACB_BIT(TX_USED)) {
589                         /* skb is set for the last buffer of the frame */
590                         while (!skb) {
591                                 macb_tx_unmap(bp, tx_skb);
592                                 tail++;
593                                 tx_skb = macb_tx_skb(queue, tail);
594                                 skb = tx_skb->skb;
595                         }
596
597                         /* ctrl still refers to the first buffer descriptor
598                          * since it's the only one written back by the hardware
599                          */
600                         if (!(ctrl & MACB_BIT(TX_BUF_EXHAUSTED))) {
601                                 netdev_vdbg(bp->dev, "txerr skb %u (data %p) TX complete\n",
602                                             macb_tx_ring_wrap(tail), skb->data);
603                                 bp->stats.tx_packets++;
604                                 bp->stats.tx_bytes += skb->len;
605                         }
606                 } else {
607                         /*
608                          * "Buffers exhausted mid-frame" errors may only happen
609                          * if the driver is buggy, so complain loudly about those.
610                          * Statistics are updated by hardware.
611                          */
612                         if (ctrl & MACB_BIT(TX_BUF_EXHAUSTED))
613                                 netdev_err(bp->dev,
614                                            "BUG: TX buffers exhausted mid-frame\n");
615
616                         desc->ctrl = ctrl | MACB_BIT(TX_USED);
617                 }
618
619                 macb_tx_unmap(bp, tx_skb);
620         }
621
622         /* Set end of TX queue */
623         desc = macb_tx_desc(queue, 0);
624         desc->addr = 0;
625         desc->ctrl = MACB_BIT(TX_USED);
626
627         /* Make descriptor updates visible to hardware */
628         wmb();
629
630         /* Reinitialize the TX desc queue */
631         queue_writel(queue, TBQP, queue->tx_ring_dma);
632         /* Make TX ring reflect state of hardware */
633         queue->tx_head = 0;
634         queue->tx_tail = 0;
635
636         /* Housework before enabling TX IRQ */
637         macb_writel(bp, TSR, macb_readl(bp, TSR));
638         queue_writel(queue, IER, MACB_TX_INT_FLAGS);
639
640         /* Now we are ready to start transmission again */
641         netif_tx_start_all_queues(bp->dev);
642         macb_writel(bp, NCR, macb_readl(bp, NCR) | MACB_BIT(TSTART));
643
644         spin_unlock_irqrestore(&bp->lock, flags);
645 }
646
647 static void macb_tx_interrupt(struct macb_queue *queue)
648 {
649         unsigned int tail;
650         unsigned int head;
651         u32 status;
652         struct macb *bp = queue->bp;
653         u16 queue_index = queue - bp->queues;
654
655         status = macb_readl(bp, TSR);
656         macb_writel(bp, TSR, status);
657
658         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
659                 queue_writel(queue, ISR, MACB_BIT(TCOMP));
660
661         netdev_vdbg(bp->dev, "macb_tx_interrupt status = 0x%03lx\n",
662                 (unsigned long)status);
663
664         head = queue->tx_head;
665         for (tail = queue->tx_tail; tail != head; tail++) {
666                 struct macb_tx_skb      *tx_skb;
667                 struct sk_buff          *skb;
668                 struct macb_dma_desc    *desc;
669                 u32                     ctrl;
670
671                 desc = macb_tx_desc(queue, tail);
672
673                 /* Make hw descriptor updates visible to CPU */
674                 rmb();
675
676                 ctrl = desc->ctrl;
677
678                 /* TX_USED bit is only set by hardware on the very first buffer
679                  * descriptor of the transmitted frame.
680                  */
681                 if (!(ctrl & MACB_BIT(TX_USED)))
682                         break;
683
684                 /* Process all buffers of the current transmitted frame */
685                 for (;; tail++) {
686                         tx_skb = macb_tx_skb(queue, tail);
687                         skb = tx_skb->skb;
688
689                         /* First, update TX stats if needed */
690                         if (skb) {
691                                 netdev_vdbg(bp->dev, "skb %u (data %p) TX complete\n",
692                                             macb_tx_ring_wrap(tail), skb->data);
693                                 bp->stats.tx_packets++;
694                                 bp->stats.tx_bytes += skb->len;
695                         }
696
697                         /* Now we can safely release resources */
698                         macb_tx_unmap(bp, tx_skb);
699
700                         /* skb is set only for the last buffer of the frame.
701                          * WARNING: at this point skb has been freed by
702                          * macb_tx_unmap().
703                          */
704                         if (skb)
705                                 break;
706                 }
707         }
708
709         queue->tx_tail = tail;
710         if (__netif_subqueue_stopped(bp->dev, queue_index) &&
711             CIRC_CNT(queue->tx_head, queue->tx_tail,
712                      TX_RING_SIZE) <= MACB_TX_WAKEUP_THRESH)
713                 netif_wake_subqueue(bp->dev, queue_index);
714 }
715
716 static void gem_rx_refill(struct macb *bp)
717 {
718         unsigned int            entry;
719         struct sk_buff          *skb;
720         dma_addr_t              paddr;
721
722         while (CIRC_SPACE(bp->rx_prepared_head, bp->rx_tail, RX_RING_SIZE) > 0) {
723                 entry = macb_rx_ring_wrap(bp->rx_prepared_head);
724
725                 /* Make hw descriptor updates visible to CPU */
726                 rmb();
727
728                 bp->rx_prepared_head++;
729
730                 if (bp->rx_skbuff[entry] == NULL) {
731                         /* allocate sk_buff for this free entry in ring */
732                         skb = netdev_alloc_skb(bp->dev, bp->rx_buffer_size);
733                         if (unlikely(skb == NULL)) {
734                                 netdev_err(bp->dev,
735                                            "Unable to allocate sk_buff\n");
736                                 break;
737                         }
738
739                         /* now fill corresponding descriptor entry */
740                         paddr = dma_map_single(&bp->pdev->dev, skb->data,
741                                                bp->rx_buffer_size, DMA_FROM_DEVICE);
742                         if (dma_mapping_error(&bp->pdev->dev, paddr)) {
743                                 dev_kfree_skb(skb);
744                                 break;
745                         }
746
747                         bp->rx_skbuff[entry] = skb;
748
749                         if (entry == RX_RING_SIZE - 1)
750                                 paddr |= MACB_BIT(RX_WRAP);
751                         bp->rx_ring[entry].addr = paddr;
752                         bp->rx_ring[entry].ctrl = 0;
753
754                         /* properly align Ethernet header */
755                         skb_reserve(skb, NET_IP_ALIGN);
756                 } else {
757                         bp->rx_ring[entry].addr &= ~MACB_BIT(RX_USED);
758                         bp->rx_ring[entry].ctrl = 0;
759                 }
760         }
761
762         /* Make descriptor updates visible to hardware */
763         wmb();
764
765         netdev_vdbg(bp->dev, "rx ring: prepared head %d, tail %d\n",
766                    bp->rx_prepared_head, bp->rx_tail);
767 }
768
769 /* Mark DMA descriptors from begin up to and not including end as unused */
770 static void discard_partial_frame(struct macb *bp, unsigned int begin,
771                                   unsigned int end)
772 {
773         unsigned int frag;
774
775         for (frag = begin; frag != end; frag++) {
776                 struct macb_dma_desc *desc = macb_rx_desc(bp, frag);
777                 desc->addr &= ~MACB_BIT(RX_USED);
778         }
779
780         /* Make descriptor updates visible to hardware */
781         wmb();
782
783         /*
784          * When this happens, the hardware stats registers for
785          * whatever caused this is updated, so we don't have to record
786          * anything.
787          */
788 }
789
790 static int gem_rx(struct macb *bp, int budget)
791 {
792         unsigned int            len;
793         unsigned int            entry;
794         struct sk_buff          *skb;
795         struct macb_dma_desc    *desc;
796         int                     count = 0;
797
798         while (count < budget) {
799                 u32 addr, ctrl;
800
801                 entry = macb_rx_ring_wrap(bp->rx_tail);
802                 desc = &bp->rx_ring[entry];
803
804                 /* Make hw descriptor updates visible to CPU */
805                 rmb();
806
807                 addr = desc->addr;
808                 ctrl = desc->ctrl;
809
810                 if (!(addr & MACB_BIT(RX_USED)))
811                         break;
812
813                 bp->rx_tail++;
814                 count++;
815
816                 if (!(ctrl & MACB_BIT(RX_SOF) && ctrl & MACB_BIT(RX_EOF))) {
817                         netdev_err(bp->dev,
818                                    "not whole frame pointed by descriptor\n");
819                         bp->stats.rx_dropped++;
820                         break;
821                 }
822                 skb = bp->rx_skbuff[entry];
823                 if (unlikely(!skb)) {
824                         netdev_err(bp->dev,
825                                    "inconsistent Rx descriptor chain\n");
826                         bp->stats.rx_dropped++;
827                         break;
828                 }
829                 /* now everything is ready for receiving packet */
830                 bp->rx_skbuff[entry] = NULL;
831                 len = ctrl & bp->rx_frm_len_mask;
832
833                 netdev_vdbg(bp->dev, "gem_rx %u (len %u)\n", entry, len);
834
835                 skb_put(skb, len);
836                 addr = MACB_BF(RX_WADDR, MACB_BFEXT(RX_WADDR, addr));
837                 dma_unmap_single(&bp->pdev->dev, addr,
838                                  bp->rx_buffer_size, DMA_FROM_DEVICE);
839
840                 skb->protocol = eth_type_trans(skb, bp->dev);
841                 skb_checksum_none_assert(skb);
842                 if (bp->dev->features & NETIF_F_RXCSUM &&
843                     !(bp->dev->flags & IFF_PROMISC) &&
844                     GEM_BFEXT(RX_CSUM, ctrl) & GEM_RX_CSUM_CHECKED_MASK)
845                         skb->ip_summed = CHECKSUM_UNNECESSARY;
846
847                 bp->stats.rx_packets++;
848                 bp->stats.rx_bytes += skb->len;
849
850 #if defined(DEBUG) && defined(VERBOSE_DEBUG)
851                 netdev_vdbg(bp->dev, "received skb of length %u, csum: %08x\n",
852                             skb->len, skb->csum);
853                 print_hex_dump(KERN_DEBUG, " mac: ", DUMP_PREFIX_ADDRESS, 16, 1,
854                                skb_mac_header(skb), 16, true);
855                 print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_ADDRESS, 16, 1,
856                                skb->data, 32, true);
857 #endif
858
859                 netif_receive_skb(skb);
860         }
861
862         gem_rx_refill(bp);
863
864         return count;
865 }
866
867 static int macb_rx_frame(struct macb *bp, unsigned int first_frag,
868                          unsigned int last_frag)
869 {
870         unsigned int len;
871         unsigned int frag;
872         unsigned int offset;
873         struct sk_buff *skb;
874         struct macb_dma_desc *desc;
875
876         desc = macb_rx_desc(bp, last_frag);
877         len = desc->ctrl & bp->rx_frm_len_mask;
878
879         netdev_vdbg(bp->dev, "macb_rx_frame frags %u - %u (len %u)\n",
880                 macb_rx_ring_wrap(first_frag),
881                 macb_rx_ring_wrap(last_frag), len);
882
883         /*
884          * The ethernet header starts NET_IP_ALIGN bytes into the
885          * first buffer. Since the header is 14 bytes, this makes the
886          * payload word-aligned.
887          *
888          * Instead of calling skb_reserve(NET_IP_ALIGN), we just copy
889          * the two padding bytes into the skb so that we avoid hitting
890          * the slowpath in memcpy(), and pull them off afterwards.
891          */
892         skb = netdev_alloc_skb(bp->dev, len + NET_IP_ALIGN);
893         if (!skb) {
894                 bp->stats.rx_dropped++;
895                 for (frag = first_frag; ; frag++) {
896                         desc = macb_rx_desc(bp, frag);
897                         desc->addr &= ~MACB_BIT(RX_USED);
898                         if (frag == last_frag)
899                                 break;
900                 }
901
902                 /* Make descriptor updates visible to hardware */
903                 wmb();
904
905                 return 1;
906         }
907
908         offset = 0;
909         len += NET_IP_ALIGN;
910         skb_checksum_none_assert(skb);
911         skb_put(skb, len);
912
913         for (frag = first_frag; ; frag++) {
914                 unsigned int frag_len = bp->rx_buffer_size;
915
916                 if (offset + frag_len > len) {
917                         BUG_ON(frag != last_frag);
918                         frag_len = len - offset;
919                 }
920                 skb_copy_to_linear_data_offset(skb, offset,
921                                 macb_rx_buffer(bp, frag), frag_len);
922                 offset += bp->rx_buffer_size;
923                 desc = macb_rx_desc(bp, frag);
924                 desc->addr &= ~MACB_BIT(RX_USED);
925
926                 if (frag == last_frag)
927                         break;
928         }
929
930         /* Make descriptor updates visible to hardware */
931         wmb();
932
933         __skb_pull(skb, NET_IP_ALIGN);
934         skb->protocol = eth_type_trans(skb, bp->dev);
935
936         bp->stats.rx_packets++;
937         bp->stats.rx_bytes += skb->len;
938         netdev_vdbg(bp->dev, "received skb of length %u, csum: %08x\n",
939                    skb->len, skb->csum);
940         netif_receive_skb(skb);
941
942         return 0;
943 }
944
945 static int macb_rx(struct macb *bp, int budget)
946 {
947         int received = 0;
948         unsigned int tail;
949         int first_frag = -1;
950
951         for (tail = bp->rx_tail; budget > 0; tail++) {
952                 struct macb_dma_desc *desc = macb_rx_desc(bp, tail);
953                 u32 addr, ctrl;
954
955                 /* Make hw descriptor updates visible to CPU */
956                 rmb();
957
958                 addr = desc->addr;
959                 ctrl = desc->ctrl;
960
961                 if (!(addr & MACB_BIT(RX_USED)))
962                         break;
963
964                 if (ctrl & MACB_BIT(RX_SOF)) {
965                         if (first_frag != -1)
966                                 discard_partial_frame(bp, first_frag, tail);
967                         first_frag = tail;
968                 }
969
970                 if (ctrl & MACB_BIT(RX_EOF)) {
971                         int dropped;
972                         BUG_ON(first_frag == -1);
973
974                         dropped = macb_rx_frame(bp, first_frag, tail);
975                         first_frag = -1;
976                         if (!dropped) {
977                                 received++;
978                                 budget--;
979                         }
980                 }
981         }
982
983         if (first_frag != -1)
984                 bp->rx_tail = first_frag;
985         else
986                 bp->rx_tail = tail;
987
988         return received;
989 }
990
991 static int macb_poll(struct napi_struct *napi, int budget)
992 {
993         struct macb *bp = container_of(napi, struct macb, napi);
994         int work_done;
995         u32 status;
996
997         status = macb_readl(bp, RSR);
998         macb_writel(bp, RSR, status);
999
1000         work_done = 0;
1001
1002         netdev_vdbg(bp->dev, "poll: status = %08lx, budget = %d\n",
1003                    (unsigned long)status, budget);
1004
1005         work_done = bp->macbgem_ops.mog_rx(bp, budget);
1006         if (work_done < budget) {
1007                 napi_complete(napi);
1008
1009                 /* Packets received while interrupts were disabled */
1010                 status = macb_readl(bp, RSR);
1011                 if (status) {
1012                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1013                                 macb_writel(bp, ISR, MACB_BIT(RCOMP));
1014                         napi_reschedule(napi);
1015                 } else {
1016                         macb_writel(bp, IER, MACB_RX_INT_FLAGS);
1017                 }
1018         }
1019
1020         /* TODO: Handle errors */
1021
1022         return work_done;
1023 }
1024
1025 static irqreturn_t macb_interrupt(int irq, void *dev_id)
1026 {
1027         struct macb_queue *queue = dev_id;
1028         struct macb *bp = queue->bp;
1029         struct net_device *dev = bp->dev;
1030         u32 status, ctrl;
1031
1032         status = queue_readl(queue, ISR);
1033
1034         if (unlikely(!status))
1035                 return IRQ_NONE;
1036
1037         spin_lock(&bp->lock);
1038
1039         while (status) {
1040                 /* close possible race with dev_close */
1041                 if (unlikely(!netif_running(dev))) {
1042                         queue_writel(queue, IDR, -1);
1043                         break;
1044                 }
1045
1046                 netdev_vdbg(bp->dev, "queue = %u, isr = 0x%08lx\n",
1047                             (unsigned int)(queue - bp->queues),
1048                             (unsigned long)status);
1049
1050                 if (status & MACB_RX_INT_FLAGS) {
1051                         /*
1052                          * There's no point taking any more interrupts
1053                          * until we have processed the buffers. The
1054                          * scheduling call may fail if the poll routine
1055                          * is already scheduled, so disable interrupts
1056                          * now.
1057                          */
1058                         queue_writel(queue, IDR, MACB_RX_INT_FLAGS);
1059                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1060                                 queue_writel(queue, ISR, MACB_BIT(RCOMP));
1061
1062                         if (napi_schedule_prep(&bp->napi)) {
1063                                 netdev_vdbg(bp->dev, "scheduling RX softirq\n");
1064                                 __napi_schedule(&bp->napi);
1065                         }
1066                 }
1067
1068                 if (unlikely(status & (MACB_TX_ERR_FLAGS))) {
1069                         queue_writel(queue, IDR, MACB_TX_INT_FLAGS);
1070                         schedule_work(&queue->tx_error_task);
1071
1072                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1073                                 queue_writel(queue, ISR, MACB_TX_ERR_FLAGS);
1074
1075                         break;
1076                 }
1077
1078                 if (status & MACB_BIT(TCOMP))
1079                         macb_tx_interrupt(queue);
1080
1081                 /*
1082                  * Link change detection isn't possible with RMII, so we'll
1083                  * add that if/when we get our hands on a full-blown MII PHY.
1084                  */
1085
1086                 /* There is a hardware issue under heavy load where DMA can
1087                  * stop, this causes endless "used buffer descriptor read"
1088                  * interrupts but it can be cleared by re-enabling RX. See
1089                  * the at91 manual, section 41.3.1 or the Zynq manual
1090                  * section 16.7.4 for details.
1091                  */
1092                 if (status & MACB_BIT(RXUBR)) {
1093                         ctrl = macb_readl(bp, NCR);
1094                         macb_writel(bp, NCR, ctrl & ~MACB_BIT(RE));
1095                         macb_writel(bp, NCR, ctrl | MACB_BIT(RE));
1096
1097                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1098                                 macb_writel(bp, ISR, MACB_BIT(RXUBR));
1099                 }
1100
1101                 if (status & MACB_BIT(ISR_ROVR)) {
1102                         /* We missed at least one packet */
1103                         if (macb_is_gem(bp))
1104                                 bp->hw_stats.gem.rx_overruns++;
1105                         else
1106                                 bp->hw_stats.macb.rx_overruns++;
1107
1108                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1109                                 queue_writel(queue, ISR, MACB_BIT(ISR_ROVR));
1110                 }
1111
1112                 if (status & MACB_BIT(HRESP)) {
1113                         /*
1114                          * TODO: Reset the hardware, and maybe move the
1115                          * netdev_err to a lower-priority context as well
1116                          * (work queue?)
1117                          */
1118                         netdev_err(dev, "DMA bus error: HRESP not OK\n");
1119
1120                         if (bp->caps & MACB_CAPS_ISR_CLEAR_ON_WRITE)
1121                                 queue_writel(queue, ISR, MACB_BIT(HRESP));
1122                 }
1123
1124                 status = queue_readl(queue, ISR);
1125         }
1126
1127         spin_unlock(&bp->lock);
1128
1129         return IRQ_HANDLED;
1130 }
1131
1132 #ifdef CONFIG_NET_POLL_CONTROLLER
1133 /*
1134  * Polling receive - used by netconsole and other diagnostic tools
1135  * to allow network i/o with interrupts disabled.
1136  */
1137 static void macb_poll_controller(struct net_device *dev)
1138 {
1139         struct macb *bp = netdev_priv(dev);
1140         struct macb_queue *queue;
1141         unsigned long flags;
1142         unsigned int q;
1143
1144         local_irq_save(flags);
1145         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue)
1146                 macb_interrupt(dev->irq, queue);
1147         local_irq_restore(flags);
1148 }
1149 #endif
1150
1151 static unsigned int macb_tx_map(struct macb *bp,
1152                                 struct macb_queue *queue,
1153                                 struct sk_buff *skb)
1154 {
1155         dma_addr_t mapping;
1156         unsigned int len, entry, i, tx_head = queue->tx_head;
1157         struct macb_tx_skb *tx_skb = NULL;
1158         struct macb_dma_desc *desc;
1159         unsigned int offset, size, count = 0;
1160         unsigned int f, nr_frags = skb_shinfo(skb)->nr_frags;
1161         unsigned int eof = 1;
1162         u32 ctrl;
1163
1164         /* First, map non-paged data */
1165         len = skb_headlen(skb);
1166         offset = 0;
1167         while (len) {
1168                 size = min(len, bp->max_tx_length);
1169                 entry = macb_tx_ring_wrap(tx_head);
1170                 tx_skb = &queue->tx_skb[entry];
1171
1172                 mapping = dma_map_single(&bp->pdev->dev,
1173                                          skb->data + offset,
1174                                          size, DMA_TO_DEVICE);
1175                 if (dma_mapping_error(&bp->pdev->dev, mapping))
1176                         goto dma_error;
1177
1178                 /* Save info to properly release resources */
1179                 tx_skb->skb = NULL;
1180                 tx_skb->mapping = mapping;
1181                 tx_skb->size = size;
1182                 tx_skb->mapped_as_page = false;
1183
1184                 len -= size;
1185                 offset += size;
1186                 count++;
1187                 tx_head++;
1188         }
1189
1190         /* Then, map paged data from fragments */
1191         for (f = 0; f < nr_frags; f++) {
1192                 const skb_frag_t *frag = &skb_shinfo(skb)->frags[f];
1193
1194                 len = skb_frag_size(frag);
1195                 offset = 0;
1196                 while (len) {
1197                         size = min(len, bp->max_tx_length);
1198                         entry = macb_tx_ring_wrap(tx_head);
1199                         tx_skb = &queue->tx_skb[entry];
1200
1201                         mapping = skb_frag_dma_map(&bp->pdev->dev, frag,
1202                                                    offset, size, DMA_TO_DEVICE);
1203                         if (dma_mapping_error(&bp->pdev->dev, mapping))
1204                                 goto dma_error;
1205
1206                         /* Save info to properly release resources */
1207                         tx_skb->skb = NULL;
1208                         tx_skb->mapping = mapping;
1209                         tx_skb->size = size;
1210                         tx_skb->mapped_as_page = true;
1211
1212                         len -= size;
1213                         offset += size;
1214                         count++;
1215                         tx_head++;
1216                 }
1217         }
1218
1219         /* Should never happen */
1220         if (unlikely(tx_skb == NULL)) {
1221                 netdev_err(bp->dev, "BUG! empty skb!\n");
1222                 return 0;
1223         }
1224
1225         /* This is the last buffer of the frame: save socket buffer */
1226         tx_skb->skb = skb;
1227
1228         /* Update TX ring: update buffer descriptors in reverse order
1229          * to avoid race condition
1230          */
1231
1232         /* Set 'TX_USED' bit in buffer descriptor at tx_head position
1233          * to set the end of TX queue
1234          */
1235         i = tx_head;
1236         entry = macb_tx_ring_wrap(i);
1237         ctrl = MACB_BIT(TX_USED);
1238         desc = &queue->tx_ring[entry];
1239         desc->ctrl = ctrl;
1240
1241         do {
1242                 i--;
1243                 entry = macb_tx_ring_wrap(i);
1244                 tx_skb = &queue->tx_skb[entry];
1245                 desc = &queue->tx_ring[entry];
1246
1247                 ctrl = (u32)tx_skb->size;
1248                 if (eof) {
1249                         ctrl |= MACB_BIT(TX_LAST);
1250                         eof = 0;
1251                 }
1252                 if (unlikely(entry == (TX_RING_SIZE - 1)))
1253                         ctrl |= MACB_BIT(TX_WRAP);
1254
1255                 /* Set TX buffer descriptor */
1256                 desc->addr = tx_skb->mapping;
1257                 /* desc->addr must be visible to hardware before clearing
1258                  * 'TX_USED' bit in desc->ctrl.
1259                  */
1260                 wmb();
1261                 desc->ctrl = ctrl;
1262         } while (i != queue->tx_head);
1263
1264         queue->tx_head = tx_head;
1265
1266         return count;
1267
1268 dma_error:
1269         netdev_err(bp->dev, "TX DMA map failed\n");
1270
1271         for (i = queue->tx_head; i != tx_head; i++) {
1272                 tx_skb = macb_tx_skb(queue, i);
1273
1274                 macb_tx_unmap(bp, tx_skb);
1275         }
1276
1277         return 0;
1278 }
1279
1280 static int macb_start_xmit(struct sk_buff *skb, struct net_device *dev)
1281 {
1282         u16 queue_index = skb_get_queue_mapping(skb);
1283         struct macb *bp = netdev_priv(dev);
1284         struct macb_queue *queue = &bp->queues[queue_index];
1285         unsigned long flags;
1286         unsigned int count, nr_frags, frag_size, f;
1287
1288 #if defined(DEBUG) && defined(VERBOSE_DEBUG)
1289         netdev_vdbg(bp->dev,
1290                    "start_xmit: queue %hu len %u head %p data %p tail %p end %p\n",
1291                    queue_index, skb->len, skb->head, skb->data,
1292                    skb_tail_pointer(skb), skb_end_pointer(skb));
1293         print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_OFFSET, 16, 1,
1294                        skb->data, 16, true);
1295 #endif
1296
1297         /* Count how many TX buffer descriptors are needed to send this
1298          * socket buffer: skb fragments of jumbo frames may need to be
1299          * splitted into many buffer descriptors.
1300          */
1301         count = DIV_ROUND_UP(skb_headlen(skb), bp->max_tx_length);
1302         nr_frags = skb_shinfo(skb)->nr_frags;
1303         for (f = 0; f < nr_frags; f++) {
1304                 frag_size = skb_frag_size(&skb_shinfo(skb)->frags[f]);
1305                 count += DIV_ROUND_UP(frag_size, bp->max_tx_length);
1306         }
1307
1308         spin_lock_irqsave(&bp->lock, flags);
1309
1310         /* This is a hard error, log it. */
1311         if (CIRC_SPACE(queue->tx_head, queue->tx_tail, TX_RING_SIZE) < count) {
1312                 netif_stop_subqueue(dev, queue_index);
1313                 spin_unlock_irqrestore(&bp->lock, flags);
1314                 netdev_dbg(bp->dev, "tx_head = %u, tx_tail = %u\n",
1315                            queue->tx_head, queue->tx_tail);
1316                 return NETDEV_TX_BUSY;
1317         }
1318
1319         /* Map socket buffer for DMA transfer */
1320         if (!macb_tx_map(bp, queue, skb)) {
1321                 dev_kfree_skb_any(skb);
1322                 goto unlock;
1323         }
1324
1325         /* Make newly initialized descriptor visible to hardware */
1326         wmb();
1327
1328         skb_tx_timestamp(skb);
1329
1330         macb_writel(bp, NCR, macb_readl(bp, NCR) | MACB_BIT(TSTART));
1331
1332         if (CIRC_SPACE(queue->tx_head, queue->tx_tail, TX_RING_SIZE) < 1)
1333                 netif_stop_subqueue(dev, queue_index);
1334
1335 unlock:
1336         spin_unlock_irqrestore(&bp->lock, flags);
1337
1338         return NETDEV_TX_OK;
1339 }
1340
1341 static void macb_init_rx_buffer_size(struct macb *bp, size_t size)
1342 {
1343         if (!macb_is_gem(bp)) {
1344                 bp->rx_buffer_size = MACB_RX_BUFFER_SIZE;
1345         } else {
1346                 bp->rx_buffer_size = size;
1347
1348                 if (bp->rx_buffer_size % RX_BUFFER_MULTIPLE) {
1349                         netdev_dbg(bp->dev,
1350                                     "RX buffer must be multiple of %d bytes, expanding\n",
1351                                     RX_BUFFER_MULTIPLE);
1352                         bp->rx_buffer_size =
1353                                 roundup(bp->rx_buffer_size, RX_BUFFER_MULTIPLE);
1354                 }
1355         }
1356
1357         netdev_dbg(bp->dev, "mtu [%u] rx_buffer_size [%Zu]\n",
1358                    bp->dev->mtu, bp->rx_buffer_size);
1359 }
1360
1361 static void gem_free_rx_buffers(struct macb *bp)
1362 {
1363         struct sk_buff          *skb;
1364         struct macb_dma_desc    *desc;
1365         dma_addr_t              addr;
1366         int i;
1367
1368         if (!bp->rx_skbuff)
1369                 return;
1370
1371         for (i = 0; i < RX_RING_SIZE; i++) {
1372                 skb = bp->rx_skbuff[i];
1373
1374                 if (skb == NULL)
1375                         continue;
1376
1377                 desc = &bp->rx_ring[i];
1378                 addr = MACB_BF(RX_WADDR, MACB_BFEXT(RX_WADDR, desc->addr));
1379                 dma_unmap_single(&bp->pdev->dev, addr, bp->rx_buffer_size,
1380                                  DMA_FROM_DEVICE);
1381                 dev_kfree_skb_any(skb);
1382                 skb = NULL;
1383         }
1384
1385         kfree(bp->rx_skbuff);
1386         bp->rx_skbuff = NULL;
1387 }
1388
1389 static void macb_free_rx_buffers(struct macb *bp)
1390 {
1391         if (bp->rx_buffers) {
1392                 dma_free_coherent(&bp->pdev->dev,
1393                                   RX_RING_SIZE * bp->rx_buffer_size,
1394                                   bp->rx_buffers, bp->rx_buffers_dma);
1395                 bp->rx_buffers = NULL;
1396         }
1397 }
1398
1399 static void macb_free_consistent(struct macb *bp)
1400 {
1401         struct macb_queue *queue;
1402         unsigned int q;
1403
1404         bp->macbgem_ops.mog_free_rx_buffers(bp);
1405         if (bp->rx_ring) {
1406                 dma_free_coherent(&bp->pdev->dev, RX_RING_BYTES,
1407                                   bp->rx_ring, bp->rx_ring_dma);
1408                 bp->rx_ring = NULL;
1409         }
1410
1411         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) {
1412                 kfree(queue->tx_skb);
1413                 queue->tx_skb = NULL;
1414                 if (queue->tx_ring) {
1415                         dma_free_coherent(&bp->pdev->dev, TX_RING_BYTES,
1416                                           queue->tx_ring, queue->tx_ring_dma);
1417                         queue->tx_ring = NULL;
1418                 }
1419         }
1420 }
1421
1422 static int gem_alloc_rx_buffers(struct macb *bp)
1423 {
1424         int size;
1425
1426         size = RX_RING_SIZE * sizeof(struct sk_buff *);
1427         bp->rx_skbuff = kzalloc(size, GFP_KERNEL);
1428         if (!bp->rx_skbuff)
1429                 return -ENOMEM;
1430         else
1431                 netdev_dbg(bp->dev,
1432                            "Allocated %d RX struct sk_buff entries at %p\n",
1433                            RX_RING_SIZE, bp->rx_skbuff);
1434         return 0;
1435 }
1436
1437 static int macb_alloc_rx_buffers(struct macb *bp)
1438 {
1439         int size;
1440
1441         size = RX_RING_SIZE * bp->rx_buffer_size;
1442         bp->rx_buffers = dma_alloc_coherent(&bp->pdev->dev, size,
1443                                             &bp->rx_buffers_dma, GFP_KERNEL);
1444         if (!bp->rx_buffers)
1445                 return -ENOMEM;
1446         else
1447                 netdev_dbg(bp->dev,
1448                            "Allocated RX buffers of %d bytes at %08lx (mapped %p)\n",
1449                            size, (unsigned long)bp->rx_buffers_dma, bp->rx_buffers);
1450         return 0;
1451 }
1452
1453 static int macb_alloc_consistent(struct macb *bp)
1454 {
1455         struct macb_queue *queue;
1456         unsigned int q;
1457         int size;
1458
1459         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) {
1460                 size = TX_RING_BYTES;
1461                 queue->tx_ring = dma_alloc_coherent(&bp->pdev->dev, size,
1462                                                     &queue->tx_ring_dma,
1463                                                     GFP_KERNEL);
1464                 if (!queue->tx_ring)
1465                         goto out_err;
1466                 netdev_dbg(bp->dev,
1467                            "Allocated TX ring for queue %u of %d bytes at %08lx (mapped %p)\n",
1468                            q, size, (unsigned long)queue->tx_ring_dma,
1469                            queue->tx_ring);
1470
1471                 size = TX_RING_SIZE * sizeof(struct macb_tx_skb);
1472                 queue->tx_skb = kmalloc(size, GFP_KERNEL);
1473                 if (!queue->tx_skb)
1474                         goto out_err;
1475         }
1476
1477         size = RX_RING_BYTES;
1478         bp->rx_ring = dma_alloc_coherent(&bp->pdev->dev, size,
1479                                          &bp->rx_ring_dma, GFP_KERNEL);
1480         if (!bp->rx_ring)
1481                 goto out_err;
1482         netdev_dbg(bp->dev,
1483                    "Allocated RX ring of %d bytes at %08lx (mapped %p)\n",
1484                    size, (unsigned long)bp->rx_ring_dma, bp->rx_ring);
1485
1486         if (bp->macbgem_ops.mog_alloc_rx_buffers(bp))
1487                 goto out_err;
1488
1489         return 0;
1490
1491 out_err:
1492         macb_free_consistent(bp);
1493         return -ENOMEM;
1494 }
1495
1496 static void gem_init_rings(struct macb *bp)
1497 {
1498         struct macb_queue *queue;
1499         unsigned int q;
1500         int i;
1501
1502         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) {
1503                 for (i = 0; i < TX_RING_SIZE; i++) {
1504                         queue->tx_ring[i].addr = 0;
1505                         queue->tx_ring[i].ctrl = MACB_BIT(TX_USED);
1506                 }
1507                 queue->tx_ring[TX_RING_SIZE - 1].ctrl |= MACB_BIT(TX_WRAP);
1508                 queue->tx_head = 0;
1509                 queue->tx_tail = 0;
1510         }
1511
1512         bp->rx_tail = 0;
1513         bp->rx_prepared_head = 0;
1514
1515         gem_rx_refill(bp);
1516 }
1517
1518 static void macb_init_rings(struct macb *bp)
1519 {
1520         int i;
1521         dma_addr_t addr;
1522
1523         addr = bp->rx_buffers_dma;
1524         for (i = 0; i < RX_RING_SIZE; i++) {
1525                 bp->rx_ring[i].addr = addr;
1526                 bp->rx_ring[i].ctrl = 0;
1527                 addr += bp->rx_buffer_size;
1528         }
1529         bp->rx_ring[RX_RING_SIZE - 1].addr |= MACB_BIT(RX_WRAP);
1530
1531         for (i = 0; i < TX_RING_SIZE; i++) {
1532                 bp->queues[0].tx_ring[i].addr = 0;
1533                 bp->queues[0].tx_ring[i].ctrl = MACB_BIT(TX_USED);
1534         }
1535         bp->queues[0].tx_head = 0;
1536         bp->queues[0].tx_tail = 0;
1537         bp->queues[0].tx_ring[TX_RING_SIZE - 1].ctrl |= MACB_BIT(TX_WRAP);
1538
1539         bp->rx_tail = 0;
1540 }
1541
1542 static void macb_reset_hw(struct macb *bp)
1543 {
1544         struct macb_queue *queue;
1545         unsigned int q;
1546
1547         /*
1548          * Disable RX and TX (XXX: Should we halt the transmission
1549          * more gracefully?)
1550          */
1551         macb_writel(bp, NCR, 0);
1552
1553         /* Clear the stats registers (XXX: Update stats first?) */
1554         macb_writel(bp, NCR, MACB_BIT(CLRSTAT));
1555
1556         /* Clear all status flags */
1557         macb_writel(bp, TSR, -1);
1558         macb_writel(bp, RSR, -1);
1559
1560         /* Disable all interrupts */
1561         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) {
1562                 queue_writel(queue, IDR, -1);
1563                 queue_readl(queue, ISR);
1564         }
1565 }
1566
1567 static u32 gem_mdc_clk_div(struct macb *bp)
1568 {
1569         u32 config;
1570         unsigned long pclk_hz = clk_get_rate(bp->pclk);
1571
1572         if (pclk_hz <= 20000000)
1573                 config = GEM_BF(CLK, GEM_CLK_DIV8);
1574         else if (pclk_hz <= 40000000)
1575                 config = GEM_BF(CLK, GEM_CLK_DIV16);
1576         else if (pclk_hz <= 80000000)
1577                 config = GEM_BF(CLK, GEM_CLK_DIV32);
1578         else if (pclk_hz <= 120000000)
1579                 config = GEM_BF(CLK, GEM_CLK_DIV48);
1580         else if (pclk_hz <= 160000000)
1581                 config = GEM_BF(CLK, GEM_CLK_DIV64);
1582         else
1583                 config = GEM_BF(CLK, GEM_CLK_DIV96);
1584
1585         return config;
1586 }
1587
1588 static u32 macb_mdc_clk_div(struct macb *bp)
1589 {
1590         u32 config;
1591         unsigned long pclk_hz;
1592
1593         if (macb_is_gem(bp))
1594                 return gem_mdc_clk_div(bp);
1595
1596         pclk_hz = clk_get_rate(bp->pclk);
1597         if (pclk_hz <= 20000000)
1598                 config = MACB_BF(CLK, MACB_CLK_DIV8);
1599         else if (pclk_hz <= 40000000)
1600                 config = MACB_BF(CLK, MACB_CLK_DIV16);
1601         else if (pclk_hz <= 80000000)
1602                 config = MACB_BF(CLK, MACB_CLK_DIV32);
1603         else
1604                 config = MACB_BF(CLK, MACB_CLK_DIV64);
1605
1606         return config;
1607 }
1608
1609 /*
1610  * Get the DMA bus width field of the network configuration register that we
1611  * should program.  We find the width from decoding the design configuration
1612  * register to find the maximum supported data bus width.
1613  */
1614 static u32 macb_dbw(struct macb *bp)
1615 {
1616         if (!macb_is_gem(bp))
1617                 return 0;
1618
1619         switch (GEM_BFEXT(DBWDEF, gem_readl(bp, DCFG1))) {
1620         case 4:
1621                 return GEM_BF(DBW, GEM_DBW128);
1622         case 2:
1623                 return GEM_BF(DBW, GEM_DBW64);
1624         case 1:
1625         default:
1626                 return GEM_BF(DBW, GEM_DBW32);
1627         }
1628 }
1629
1630 /*
1631  * Configure the receive DMA engine
1632  * - use the correct receive buffer size
1633  * - set best burst length for DMA operations
1634  *   (if not supported by FIFO, it will fallback to default)
1635  * - set both rx/tx packet buffers to full memory size
1636  * These are configurable parameters for GEM.
1637  */
1638 static void macb_configure_dma(struct macb *bp)
1639 {
1640         u32 dmacfg;
1641
1642         if (macb_is_gem(bp)) {
1643                 dmacfg = gem_readl(bp, DMACFG) & ~GEM_BF(RXBS, -1L);
1644                 dmacfg |= GEM_BF(RXBS, bp->rx_buffer_size / RX_BUFFER_MULTIPLE);
1645                 if (bp->dma_burst_length)
1646                         dmacfg = GEM_BFINS(FBLDO, bp->dma_burst_length, dmacfg);
1647                 dmacfg |= GEM_BIT(TXPBMS) | GEM_BF(RXBMS, -1L);
1648                 dmacfg &= ~GEM_BIT(ENDIA_PKT);
1649
1650                 if (bp->native_io)
1651                         dmacfg &= ~GEM_BIT(ENDIA_DESC);
1652                 else
1653                         dmacfg |= GEM_BIT(ENDIA_DESC); /* CPU in big endian */
1654
1655                 if (bp->dev->features & NETIF_F_HW_CSUM)
1656                         dmacfg |= GEM_BIT(TXCOEN);
1657                 else
1658                         dmacfg &= ~GEM_BIT(TXCOEN);
1659                 netdev_dbg(bp->dev, "Cadence configure DMA with 0x%08x\n",
1660                            dmacfg);
1661                 gem_writel(bp, DMACFG, dmacfg);
1662         }
1663 }
1664
1665 static void macb_init_hw(struct macb *bp)
1666 {
1667         struct macb_queue *queue;
1668         unsigned int q;
1669
1670         u32 config;
1671
1672         macb_reset_hw(bp);
1673         macb_set_hwaddr(bp);
1674
1675         config = macb_mdc_clk_div(bp);
1676         if (bp->phy_interface == PHY_INTERFACE_MODE_SGMII)
1677                 config |= GEM_BIT(SGMIIEN) | GEM_BIT(PCSSEL);
1678         config |= MACB_BF(RBOF, NET_IP_ALIGN);  /* Make eth data aligned */
1679         config |= MACB_BIT(PAE);                /* PAuse Enable */
1680         config |= MACB_BIT(DRFCS);              /* Discard Rx FCS */
1681         if (bp->caps & MACB_CAPS_JUMBO)
1682                 config |= MACB_BIT(JFRAME);     /* Enable jumbo frames */
1683         else
1684                 config |= MACB_BIT(BIG);        /* Receive oversized frames */
1685         if (bp->dev->flags & IFF_PROMISC)
1686                 config |= MACB_BIT(CAF);        /* Copy All Frames */
1687         else if (macb_is_gem(bp) && bp->dev->features & NETIF_F_RXCSUM)
1688                 config |= GEM_BIT(RXCOEN);
1689         if (!(bp->dev->flags & IFF_BROADCAST))
1690                 config |= MACB_BIT(NBC);        /* No BroadCast */
1691         config |= macb_dbw(bp);
1692         macb_writel(bp, NCFGR, config);
1693         if ((bp->caps & MACB_CAPS_JUMBO) && bp->jumbo_max_len)
1694                 gem_writel(bp, JML, bp->jumbo_max_len);
1695         bp->speed = SPEED_10;
1696         bp->duplex = DUPLEX_HALF;
1697         bp->rx_frm_len_mask = MACB_RX_FRMLEN_MASK;
1698         if (bp->caps & MACB_CAPS_JUMBO)
1699                 bp->rx_frm_len_mask = MACB_RX_JFRMLEN_MASK;
1700
1701         macb_configure_dma(bp);
1702
1703         /* Initialize TX and RX buffers */
1704         macb_writel(bp, RBQP, bp->rx_ring_dma);
1705         for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) {
1706                 queue_writel(queue, TBQP, queue->tx_ring_dma);
1707
1708                 /* Enable interrupts */
1709                 queue_writel(queue, IER,
1710                              MACB_RX_INT_FLAGS |
1711                              MACB_TX_INT_FLAGS |
1712                              MACB_BIT(HRESP));
1713         }
1714
1715         /* Enable TX and RX */
1716         macb_writel(bp, NCR, MACB_BIT(RE) | MACB_BIT(TE) | MACB_BIT(MPE));
1717 }
1718
1719 /*
1720  * The hash address register is 64 bits long and takes up two
1721  * locations in the memory map.  The least significant bits are stored
1722  * in EMAC_HSL and the most significant bits in EMAC_HSH.
1723  *
1724  * The unicast hash enable and the multicast hash enable bits in the
1725  * network configuration register enable the reception of hash matched
1726  * frames. The destination address is reduced to a 6 bit index into
1727  * the 64 bit hash register using the following hash function.  The
1728  * hash function is an exclusive or of every sixth bit of the
1729  * destination address.
1730  *
1731  * hi[5] = da[5] ^ da[11] ^ da[17] ^ da[23] ^ da[29] ^ da[35] ^ da[41] ^ da[47]
1732  * hi[4] = da[4] ^ da[10] ^ da[16] ^ da[22] ^ da[28] ^ da[34] ^ da[40] ^ da[46]
1733  * hi[3] = da[3] ^ da[09] ^ da[15] ^ da[21] ^ da[27] ^ da[33] ^ da[39] ^ da[45]
1734  * hi[2] = da[2] ^ da[08] ^ da[14] ^ da[20] ^ da[26] ^ da[32] ^ da[38] ^ da[44]
1735  * hi[1] = da[1] ^ da[07] ^ da[13] ^ da[19] ^ da[25] ^ da[31] ^ da[37] ^ da[43]
1736  * hi[0] = da[0] ^ da[06] ^ da[12] ^ da[18] ^ da[24] ^ da[30] ^ da[36] ^ da[42]
1737  *
1738  * da[0] represents the least significant bit of the first byte
1739  * received, that is, the multicast/unicast indicator, and da[47]
1740  * represents the most significant bit of the last byte received.  If
1741  * the hash index, hi[n], points to a bit that is set in the hash
1742  * register then the frame will be matched according to whether the
1743  * frame is multicast or unicast.  A multicast match will be signalled
1744  * if the multicast hash enable bit is set, da[0] is 1 and the hash
1745  * index points to a bit set in the hash register.  A unicast match
1746  * will be signalled if the unicast hash enable bit is set, da[0] is 0
1747  * and the hash index points to a bit set in the hash register.  To
1748  * receive all multicast frames, the hash register should be set with
1749  * all ones and the multicast hash enable bit should be set in the
1750  * network configuration register.
1751  */
1752
1753 static inline int hash_bit_value(int bitnr, __u8 *addr)
1754 {
1755         if (addr[bitnr / 8] & (1 << (bitnr % 8)))
1756                 return 1;
1757         return 0;
1758 }
1759
1760 /*
1761  * Return the hash index value for the specified address.
1762  */
1763 static int hash_get_index(__u8 *addr)
1764 {
1765         int i, j, bitval;
1766         int hash_index = 0;
1767
1768         for (j = 0; j < 6; j++) {
1769                 for (i = 0, bitval = 0; i < 8; i++)
1770                         bitval ^= hash_bit_value(i * 6 + j, addr);
1771
1772                 hash_index |= (bitval << j);
1773         }
1774
1775         return hash_index;
1776 }
1777
1778 /*
1779  * Add multicast addresses to the internal multicast-hash table.
1780  */
1781 static void macb_sethashtable(struct net_device *dev)
1782 {
1783         struct netdev_hw_addr *ha;
1784         unsigned long mc_filter[2];
1785         unsigned int bitnr;
1786         struct macb *bp = netdev_priv(dev);
1787
1788         mc_filter[0] = mc_filter[1] = 0;
1789
1790         netdev_for_each_mc_addr(ha, dev) {
1791                 bitnr = hash_get_index(ha->addr);
1792                 mc_filter[bitnr >> 5] |= 1 << (bitnr & 31);
1793         }
1794
1795         macb_or_gem_writel(bp, HRB, mc_filter[0]);
1796         macb_or_gem_writel(bp, HRT, mc_filter[1]);
1797 }
1798
1799 /*
1800  * Enable/Disable promiscuous and multicast modes.
1801  */
1802 static void macb_set_rx_mode(struct net_device *dev)
1803 {
1804         unsigned long cfg;
1805         struct macb *bp = netdev_priv(dev);
1806
1807         cfg = macb_readl(bp, NCFGR);
1808
1809         if (dev->flags & IFF_PROMISC) {
1810                 /* Enable promiscuous mode */
1811                 cfg |= MACB_BIT(CAF);
1812
1813                 /* Disable RX checksum offload */
1814                 if (macb_is_gem(bp))
1815                         cfg &= ~GEM_BIT(RXCOEN);
1816         } else {
1817                 /* Disable promiscuous mode */
1818                 cfg &= ~MACB_BIT(CAF);
1819
1820                 /* Enable RX checksum offload only if requested */
1821                 if (macb_is_gem(bp) && dev->features & NETIF_F_RXCSUM)
1822                         cfg |= GEM_BIT(RXCOEN);
1823         }
1824
1825         if (dev->flags & IFF_ALLMULTI) {
1826                 /* Enable all multicast mode */
1827                 macb_or_gem_writel(bp, HRB, -1);
1828                 macb_or_gem_writel(bp, HRT, -1);
1829                 cfg |= MACB_BIT(NCFGR_MTI);
1830         } else if (!netdev_mc_empty(dev)) {
1831                 /* Enable specific multicasts */
1832                 macb_sethashtable(dev);
1833                 cfg |= MACB_BIT(NCFGR_MTI);
1834         } else if (dev->flags & (~IFF_ALLMULTI)) {
1835                 /* Disable all multicast mode */
1836                 macb_or_gem_writel(bp, HRB, 0);
1837                 macb_or_gem_writel(bp, HRT, 0);
1838                 cfg &= ~MACB_BIT(NCFGR_MTI);
1839         }
1840
1841         macb_writel(bp, NCFGR, cfg);
1842 }
1843
1844 static int macb_open(struct net_device *dev)
1845 {
1846         struct macb *bp = netdev_priv(dev);
1847         size_t bufsz = dev->mtu + ETH_HLEN + ETH_FCS_LEN + NET_IP_ALIGN;
1848         int err;
1849
1850         netdev_dbg(bp->dev, "open\n");
1851
1852         /* carrier starts down */
1853         netif_carrier_off(dev);
1854
1855         /* if the phy is not yet register, retry later*/
1856         if (!bp->phy_dev)
1857                 return -EAGAIN;
1858
1859         /* RX buffers initialization */
1860         macb_init_rx_buffer_size(bp, bufsz);
1861
1862         err = macb_alloc_consistent(bp);
1863         if (err) {
1864                 netdev_err(dev, "Unable to allocate DMA memory (error %d)\n",
1865                            err);
1866                 return err;
1867         }
1868
1869         napi_enable(&bp->napi);
1870
1871         bp->macbgem_ops.mog_init_rings(bp);
1872         macb_init_hw(bp);
1873
1874         /* schedule a link state check */
1875         phy_start(bp->phy_dev);
1876
1877         netif_tx_start_all_queues(dev);
1878
1879         return 0;
1880 }
1881
1882 static int macb_close(struct net_device *dev)
1883 {
1884         struct macb *bp = netdev_priv(dev);
1885         unsigned long flags;
1886
1887         netif_tx_stop_all_queues(dev);
1888         napi_disable(&bp->napi);
1889
1890         if (bp->phy_dev)
1891                 phy_stop(bp->phy_dev);
1892
1893         spin_lock_irqsave(&bp->lock, flags);
1894         macb_reset_hw(bp);
1895         netif_carrier_off(dev);
1896         spin_unlock_irqrestore(&bp->lock, flags);
1897
1898         macb_free_consistent(bp);
1899
1900         return 0;
1901 }
1902
1903 static int macb_change_mtu(struct net_device *dev, int new_mtu)
1904 {
1905         struct macb *bp = netdev_priv(dev);
1906         u32 max_mtu;
1907
1908         if (netif_running(dev))
1909                 return -EBUSY;
1910
1911         max_mtu = ETH_DATA_LEN;
1912         if (bp->caps & MACB_CAPS_JUMBO)
1913                 max_mtu = gem_readl(bp, JML) - ETH_HLEN - ETH_FCS_LEN;
1914
1915         if ((new_mtu > max_mtu) || (new_mtu < GEM_MTU_MIN_SIZE))
1916                 return -EINVAL;
1917
1918         dev->mtu = new_mtu;
1919
1920         return 0;
1921 }
1922
1923 static void gem_update_stats(struct macb *bp)
1924 {
1925         unsigned int i;
1926         u32 *p = &bp->hw_stats.gem.tx_octets_31_0;
1927
1928         for (i = 0; i < GEM_STATS_LEN; ++i, ++p) {
1929                 u32 offset = gem_statistics[i].offset;
1930                 u64 val = bp->macb_reg_readl(bp, offset);
1931
1932                 bp->ethtool_stats[i] += val;
1933                 *p += val;
1934
1935                 if (offset == GEM_OCTTXL || offset == GEM_OCTRXL) {
1936                         /* Add GEM_OCTTXH, GEM_OCTRXH */
1937                         val = bp->macb_reg_readl(bp, offset + 4);
1938                         bp->ethtool_stats[i] += ((u64)val) << 32;
1939                         *(++p) += val;
1940                 }
1941         }
1942 }
1943
1944 static struct net_device_stats *gem_get_stats(struct macb *bp)
1945 {
1946         struct gem_stats *hwstat = &bp->hw_stats.gem;
1947         struct net_device_stats *nstat = &bp->stats;
1948
1949         gem_update_stats(bp);
1950
1951         nstat->rx_errors = (hwstat->rx_frame_check_sequence_errors +
1952                             hwstat->rx_alignment_errors +
1953                             hwstat->rx_resource_errors +
1954                             hwstat->rx_overruns +
1955                             hwstat->rx_oversize_frames +
1956                             hwstat->rx_jabbers +
1957                             hwstat->rx_undersized_frames +
1958                             hwstat->rx_length_field_frame_errors);
1959         nstat->tx_errors = (hwstat->tx_late_collisions +
1960                             hwstat->tx_excessive_collisions +
1961                             hwstat->tx_underrun +
1962                             hwstat->tx_carrier_sense_errors);
1963         nstat->multicast = hwstat->rx_multicast_frames;
1964         nstat->collisions = (hwstat->tx_single_collision_frames +
1965                              hwstat->tx_multiple_collision_frames +
1966                              hwstat->tx_excessive_collisions);
1967         nstat->rx_length_errors = (hwstat->rx_oversize_frames +
1968                                    hwstat->rx_jabbers +
1969                                    hwstat->rx_undersized_frames +
1970                                    hwstat->rx_length_field_frame_errors);
1971         nstat->rx_over_errors = hwstat->rx_resource_errors;
1972         nstat->rx_crc_errors = hwstat->rx_frame_check_sequence_errors;
1973         nstat->rx_frame_errors = hwstat->rx_alignment_errors;
1974         nstat->rx_fifo_errors = hwstat->rx_overruns;
1975         nstat->tx_aborted_errors = hwstat->tx_excessive_collisions;
1976         nstat->tx_carrier_errors = hwstat->tx_carrier_sense_errors;
1977         nstat->tx_fifo_errors = hwstat->tx_underrun;
1978
1979         return nstat;
1980 }
1981
1982 static void gem_get_ethtool_stats(struct net_device *dev,
1983                                   struct ethtool_stats *stats, u64 *data)
1984 {
1985         struct macb *bp;
1986
1987         bp = netdev_priv(dev);
1988         gem_update_stats(bp);
1989         memcpy(data, &bp->ethtool_stats, sizeof(u64) * GEM_STATS_LEN);
1990 }
1991
1992 static int gem_get_sset_count(struct net_device *dev, int sset)
1993 {
1994         switch (sset) {
1995         case ETH_SS_STATS:
1996                 return GEM_STATS_LEN;
1997         default:
1998                 return -EOPNOTSUPP;
1999         }
2000 }
2001
2002 static void gem_get_ethtool_strings(struct net_device *dev, u32 sset, u8 *p)
2003 {
2004         unsigned int i;
2005
2006         switch (sset) {
2007         case ETH_SS_STATS:
2008                 for (i = 0; i < GEM_STATS_LEN; i++, p += ETH_GSTRING_LEN)
2009                         memcpy(p, gem_statistics[i].stat_string,
2010                                ETH_GSTRING_LEN);
2011                 break;
2012         }
2013 }
2014
2015 static struct net_device_stats *macb_get_stats(struct net_device *dev)
2016 {
2017         struct macb *bp = netdev_priv(dev);
2018         struct net_device_stats *nstat = &bp->stats;
2019         struct macb_stats *hwstat = &bp->hw_stats.macb;
2020
2021         if (macb_is_gem(bp))
2022                 return gem_get_stats(bp);
2023
2024         /* read stats from hardware */
2025         macb_update_stats(bp);
2026
2027         /* Convert HW stats into netdevice stats */
2028         nstat->rx_errors = (hwstat->rx_fcs_errors +
2029                             hwstat->rx_align_errors +
2030                             hwstat->rx_resource_errors +
2031                             hwstat->rx_overruns +
2032                             hwstat->rx_oversize_pkts +
2033                             hwstat->rx_jabbers +
2034                             hwstat->rx_undersize_pkts +
2035                             hwstat->rx_length_mismatch);
2036         nstat->tx_errors = (hwstat->tx_late_cols +
2037                             hwstat->tx_excessive_cols +
2038                             hwstat->tx_underruns +
2039                             hwstat->tx_carrier_errors +
2040                             hwstat->sqe_test_errors);
2041         nstat->collisions = (hwstat->tx_single_cols +
2042                              hwstat->tx_multiple_cols +
2043                              hwstat->tx_excessive_cols);
2044         nstat->rx_length_errors = (hwstat->rx_oversize_pkts +
2045                                    hwstat->rx_jabbers +
2046                                    hwstat->rx_undersize_pkts +
2047                                    hwstat->rx_length_mismatch);
2048         nstat->rx_over_errors = hwstat->rx_resource_errors +
2049                                    hwstat->rx_overruns;
2050         nstat->rx_crc_errors = hwstat->rx_fcs_errors;
2051         nstat->rx_frame_errors = hwstat->rx_align_errors;
2052         nstat->rx_fifo_errors = hwstat->rx_overruns;
2053         /* XXX: What does "missed" mean? */
2054         nstat->tx_aborted_errors = hwstat->tx_excessive_cols;
2055         nstat->tx_carrier_errors = hwstat->tx_carrier_errors;
2056         nstat->tx_fifo_errors = hwstat->tx_underruns;
2057         /* Don't know about heartbeat or window errors... */
2058
2059         return nstat;
2060 }
2061
2062 static int macb_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
2063 {
2064         struct macb *bp = netdev_priv(dev);
2065         struct phy_device *phydev = bp->phy_dev;
2066
2067         if (!phydev)
2068                 return -ENODEV;
2069
2070         return phy_ethtool_gset(phydev, cmd);
2071 }
2072
2073 static int macb_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
2074 {
2075         struct macb *bp = netdev_priv(dev);
2076         struct phy_device *phydev = bp->phy_dev;
2077
2078         if (!phydev)
2079                 return -ENODEV;
2080
2081         return phy_ethtool_sset(phydev, cmd);
2082 }
2083
2084 static int macb_get_regs_len(struct net_device *netdev)
2085 {
2086         return MACB_GREGS_NBR * sizeof(u32);
2087 }
2088
2089 static void macb_get_regs(struct net_device *dev, struct ethtool_regs *regs,
2090                           void *p)
2091 {
2092         struct macb *bp = netdev_priv(dev);
2093         unsigned int tail, head;
2094         u32 *regs_buff = p;
2095
2096         regs->version = (macb_readl(bp, MID) & ((1 << MACB_REV_SIZE) - 1))
2097                         | MACB_GREGS_VERSION;
2098
2099         tail = macb_tx_ring_wrap(bp->queues[0].tx_tail);
2100         head = macb_tx_ring_wrap(bp->queues[0].tx_head);
2101
2102         regs_buff[0]  = macb_readl(bp, NCR);
2103         regs_buff[1]  = macb_or_gem_readl(bp, NCFGR);
2104         regs_buff[2]  = macb_readl(bp, NSR);
2105         regs_buff[3]  = macb_readl(bp, TSR);
2106         regs_buff[4]  = macb_readl(bp, RBQP);
2107         regs_buff[5]  = macb_readl(bp, TBQP);
2108         regs_buff[6]  = macb_readl(bp, RSR);
2109         regs_buff[7]  = macb_readl(bp, IMR);
2110
2111         regs_buff[8]  = tail;
2112         regs_buff[9]  = head;
2113         regs_buff[10] = macb_tx_dma(&bp->queues[0], tail);
2114         regs_buff[11] = macb_tx_dma(&bp->queues[0], head);
2115
2116         if (!(bp->caps & MACB_CAPS_USRIO_DISABLED))
2117                 regs_buff[12] = macb_or_gem_readl(bp, USRIO);
2118         if (macb_is_gem(bp)) {
2119                 regs_buff[13] = gem_readl(bp, DMACFG);
2120         }
2121 }
2122
2123 static const struct ethtool_ops macb_ethtool_ops = {
2124         .get_settings           = macb_get_settings,
2125         .set_settings           = macb_set_settings,
2126         .get_regs_len           = macb_get_regs_len,
2127         .get_regs               = macb_get_regs,
2128         .get_link               = ethtool_op_get_link,
2129         .get_ts_info            = ethtool_op_get_ts_info,
2130 };
2131
2132 static const struct ethtool_ops gem_ethtool_ops = {
2133         .get_settings           = macb_get_settings,
2134         .set_settings           = macb_set_settings,
2135         .get_regs_len           = macb_get_regs_len,
2136         .get_regs               = macb_get_regs,
2137         .get_link               = ethtool_op_get_link,
2138         .get_ts_info            = ethtool_op_get_ts_info,
2139         .get_ethtool_stats      = gem_get_ethtool_stats,
2140         .get_strings            = gem_get_ethtool_strings,
2141         .get_sset_count         = gem_get_sset_count,
2142 };
2143
2144 static int macb_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
2145 {
2146         struct macb *bp = netdev_priv(dev);
2147         struct phy_device *phydev = bp->phy_dev;
2148
2149         if (!netif_running(dev))
2150                 return -EINVAL;
2151
2152         if (!phydev)
2153                 return -ENODEV;
2154
2155         return phy_mii_ioctl(phydev, rq, cmd);
2156 }
2157
2158 static int macb_set_features(struct net_device *netdev,
2159                              netdev_features_t features)
2160 {
2161         struct macb *bp = netdev_priv(netdev);
2162         netdev_features_t changed = features ^ netdev->features;
2163
2164         /* TX checksum offload */
2165         if ((changed & NETIF_F_HW_CSUM) && macb_is_gem(bp)) {
2166                 u32 dmacfg;
2167
2168                 dmacfg = gem_readl(bp, DMACFG);
2169                 if (features & NETIF_F_HW_CSUM)
2170                         dmacfg |= GEM_BIT(TXCOEN);
2171                 else
2172                         dmacfg &= ~GEM_BIT(TXCOEN);
2173                 gem_writel(bp, DMACFG, dmacfg);
2174         }
2175
2176         /* RX checksum offload */
2177         if ((changed & NETIF_F_RXCSUM) && macb_is_gem(bp)) {
2178                 u32 netcfg;
2179
2180                 netcfg = gem_readl(bp, NCFGR);
2181                 if (features & NETIF_F_RXCSUM &&
2182                     !(netdev->flags & IFF_PROMISC))
2183                         netcfg |= GEM_BIT(RXCOEN);
2184                 else
2185                         netcfg &= ~GEM_BIT(RXCOEN);
2186                 gem_writel(bp, NCFGR, netcfg);
2187         }
2188
2189         return 0;
2190 }
2191
2192 static const struct net_device_ops macb_netdev_ops = {
2193         .ndo_open               = macb_open,
2194         .ndo_stop               = macb_close,
2195         .ndo_start_xmit         = macb_start_xmit,
2196         .ndo_set_rx_mode        = macb_set_rx_mode,
2197         .ndo_get_stats          = macb_get_stats,
2198         .ndo_do_ioctl           = macb_ioctl,
2199         .ndo_validate_addr      = eth_validate_addr,
2200         .ndo_change_mtu         = macb_change_mtu,
2201         .ndo_set_mac_address    = eth_mac_addr,
2202 #ifdef CONFIG_NET_POLL_CONTROLLER
2203         .ndo_poll_controller    = macb_poll_controller,
2204 #endif
2205         .ndo_set_features       = macb_set_features,
2206 };
2207
2208 /*
2209  * Configure peripheral capabilities according to device tree
2210  * and integration options used
2211  */
2212 static void macb_configure_caps(struct macb *bp, const struct macb_config *dt_conf)
2213 {
2214         u32 dcfg;
2215
2216         if (dt_conf)
2217                 bp->caps = dt_conf->caps;
2218
2219         if (hw_is_gem(bp->regs, bp->native_io)) {
2220                 bp->caps |= MACB_CAPS_MACB_IS_GEM;
2221
2222                 dcfg = gem_readl(bp, DCFG1);
2223                 if (GEM_BFEXT(IRQCOR, dcfg) == 0)
2224                         bp->caps |= MACB_CAPS_ISR_CLEAR_ON_WRITE;
2225                 dcfg = gem_readl(bp, DCFG2);
2226                 if ((dcfg & (GEM_BIT(RX_PKT_BUFF) | GEM_BIT(TX_PKT_BUFF))) == 0)
2227                         bp->caps |= MACB_CAPS_FIFO_MODE;
2228         }
2229
2230         dev_dbg(&bp->pdev->dev, "Cadence caps 0x%08x\n", bp->caps);
2231 }
2232
2233 static void macb_probe_queues(void __iomem *mem,
2234                               bool native_io,
2235                               unsigned int *queue_mask,
2236                               unsigned int *num_queues)
2237 {
2238         unsigned int hw_q;
2239
2240         *queue_mask = 0x1;
2241         *num_queues = 1;
2242
2243         /* is it macb or gem ?
2244          *
2245          * We need to read directly from the hardware here because
2246          * we are early in the probe process and don't have the
2247          * MACB_CAPS_MACB_IS_GEM flag positioned
2248          */
2249         if (!hw_is_gem(mem, native_io))
2250                 return;
2251
2252         /* bit 0 is never set but queue 0 always exists */
2253         *queue_mask = readl_relaxed(mem + GEM_DCFG6) & 0xff;
2254
2255         *queue_mask |= 0x1;
2256
2257         for (hw_q = 1; hw_q < MACB_MAX_QUEUES; ++hw_q)
2258                 if (*queue_mask & (1 << hw_q))
2259                         (*num_queues)++;
2260 }
2261
2262 static int macb_clk_init(struct platform_device *pdev, struct clk **pclk,
2263                          struct clk **hclk, struct clk **tx_clk)
2264 {
2265         int err;
2266
2267         *pclk = devm_clk_get(&pdev->dev, "pclk");
2268         if (IS_ERR(*pclk)) {
2269                 err = PTR_ERR(*pclk);
2270                 dev_err(&pdev->dev, "failed to get macb_clk (%u)\n", err);
2271                 return err;
2272         }
2273
2274         *hclk = devm_clk_get(&pdev->dev, "hclk");
2275         if (IS_ERR(*hclk)) {
2276                 err = PTR_ERR(*hclk);
2277                 dev_err(&pdev->dev, "failed to get hclk (%u)\n", err);
2278                 return err;
2279         }
2280
2281         *tx_clk = devm_clk_get(&pdev->dev, "tx_clk");
2282         if (IS_ERR(*tx_clk))
2283                 *tx_clk = NULL;
2284
2285         err = clk_prepare_enable(*pclk);
2286         if (err) {
2287                 dev_err(&pdev->dev, "failed to enable pclk (%u)\n", err);
2288                 return err;
2289         }
2290
2291         err = clk_prepare_enable(*hclk);
2292         if (err) {
2293                 dev_err(&pdev->dev, "failed to enable hclk (%u)\n", err);
2294                 goto err_disable_pclk;
2295         }
2296
2297         err = clk_prepare_enable(*tx_clk);
2298         if (err) {
2299                 dev_err(&pdev->dev, "failed to enable tx_clk (%u)\n", err);
2300                 goto err_disable_hclk;
2301         }
2302
2303         return 0;
2304
2305 err_disable_hclk:
2306         clk_disable_unprepare(*hclk);
2307
2308 err_disable_pclk:
2309         clk_disable_unprepare(*pclk);
2310
2311         return err;
2312 }
2313
2314 static int macb_init(struct platform_device *pdev)
2315 {
2316         struct net_device *dev = platform_get_drvdata(pdev);
2317         unsigned int hw_q, q;
2318         struct macb *bp = netdev_priv(dev);
2319         struct macb_queue *queue;
2320         int err;
2321         u32 val;
2322
2323         /* set the queue register mapping once for all: queue0 has a special
2324          * register mapping but we don't want to test the queue index then
2325          * compute the corresponding register offset at run time.
2326          */
2327         for (hw_q = 0, q = 0; hw_q < MACB_MAX_QUEUES; ++hw_q) {
2328                 if (!(bp->queue_mask & (1 << hw_q)))
2329                         continue;
2330
2331                 queue = &bp->queues[q];
2332                 queue->bp = bp;
2333                 if (hw_q) {
2334                         queue->ISR  = GEM_ISR(hw_q - 1);
2335                         queue->IER  = GEM_IER(hw_q - 1);
2336                         queue->IDR  = GEM_IDR(hw_q - 1);
2337                         queue->IMR  = GEM_IMR(hw_q - 1);
2338                         queue->TBQP = GEM_TBQP(hw_q - 1);
2339                 } else {
2340                         /* queue0 uses legacy registers */
2341                         queue->ISR  = MACB_ISR;
2342                         queue->IER  = MACB_IER;
2343                         queue->IDR  = MACB_IDR;
2344                         queue->IMR  = MACB_IMR;
2345                         queue->TBQP = MACB_TBQP;
2346                 }
2347
2348                 /* get irq: here we use the linux queue index, not the hardware
2349                  * queue index. the queue irq definitions in the device tree
2350                  * must remove the optional gaps that could exist in the
2351                  * hardware queue mask.
2352                  */
2353                 queue->irq = platform_get_irq(pdev, q);
2354                 err = devm_request_irq(&pdev->dev, queue->irq, macb_interrupt,
2355                                        IRQF_SHARED, dev->name, queue);
2356                 if (err) {
2357                         dev_err(&pdev->dev,
2358                                 "Unable to request IRQ %d (error %d)\n",
2359                                 queue->irq, err);
2360                         return err;
2361                 }
2362
2363                 INIT_WORK(&queue->tx_error_task, macb_tx_error_task);
2364                 q++;
2365         }
2366
2367         dev->netdev_ops = &macb_netdev_ops;
2368         netif_napi_add(dev, &bp->napi, macb_poll, 64);
2369
2370         /* setup appropriated routines according to adapter type */
2371         if (macb_is_gem(bp)) {
2372                 bp->max_tx_length = GEM_MAX_TX_LEN;
2373                 bp->macbgem_ops.mog_alloc_rx_buffers = gem_alloc_rx_buffers;
2374                 bp->macbgem_ops.mog_free_rx_buffers = gem_free_rx_buffers;
2375                 bp->macbgem_ops.mog_init_rings = gem_init_rings;
2376                 bp->macbgem_ops.mog_rx = gem_rx;
2377                 dev->ethtool_ops = &gem_ethtool_ops;
2378         } else {
2379                 bp->max_tx_length = MACB_MAX_TX_LEN;
2380                 bp->macbgem_ops.mog_alloc_rx_buffers = macb_alloc_rx_buffers;
2381                 bp->macbgem_ops.mog_free_rx_buffers = macb_free_rx_buffers;
2382                 bp->macbgem_ops.mog_init_rings = macb_init_rings;
2383                 bp->macbgem_ops.mog_rx = macb_rx;
2384                 dev->ethtool_ops = &macb_ethtool_ops;
2385         }
2386
2387         /* Set features */
2388         dev->hw_features = NETIF_F_SG;
2389         /* Checksum offload is only available on gem with packet buffer */
2390         if (macb_is_gem(bp) && !(bp->caps & MACB_CAPS_FIFO_MODE))
2391                 dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_RXCSUM;
2392         if (bp->caps & MACB_CAPS_SG_DISABLED)
2393                 dev->hw_features &= ~NETIF_F_SG;
2394         dev->features = dev->hw_features;
2395
2396         if (!(bp->caps & MACB_CAPS_USRIO_DISABLED)) {
2397                 val = 0;
2398                 if (bp->phy_interface == PHY_INTERFACE_MODE_RGMII)
2399                         val = GEM_BIT(RGMII);
2400                 else if (bp->phy_interface == PHY_INTERFACE_MODE_RMII &&
2401                          (bp->caps & MACB_CAPS_USRIO_DEFAULT_IS_MII))
2402                         val = MACB_BIT(RMII);
2403                 else if (!(bp->caps & MACB_CAPS_USRIO_DEFAULT_IS_MII))
2404                         val = MACB_BIT(MII);
2405
2406                 if (bp->caps & MACB_CAPS_USRIO_HAS_CLKEN)
2407                         val |= MACB_BIT(CLKEN);
2408
2409                 macb_or_gem_writel(bp, USRIO, val);
2410         }
2411
2412         /* Set MII management clock divider */
2413         val = macb_mdc_clk_div(bp);
2414         val |= macb_dbw(bp);
2415         if (bp->phy_interface == PHY_INTERFACE_MODE_SGMII)
2416                 val |= GEM_BIT(SGMIIEN) | GEM_BIT(PCSSEL);
2417         macb_writel(bp, NCFGR, val);
2418
2419         return 0;
2420 }
2421
2422 #if defined(CONFIG_OF)
2423 /* 1518 rounded up */
2424 #define AT91ETHER_MAX_RBUFF_SZ  0x600
2425 /* max number of receive buffers */
2426 #define AT91ETHER_MAX_RX_DESCR  9
2427
2428 /* Initialize and start the Receiver and Transmit subsystems */
2429 static int at91ether_start(struct net_device *dev)
2430 {
2431         struct macb *lp = netdev_priv(dev);
2432         dma_addr_t addr;
2433         u32 ctl;
2434         int i;
2435
2436         lp->rx_ring = dma_alloc_coherent(&lp->pdev->dev,
2437                                          (AT91ETHER_MAX_RX_DESCR *
2438                                           sizeof(struct macb_dma_desc)),
2439                                          &lp->rx_ring_dma, GFP_KERNEL);
2440         if (!lp->rx_ring)
2441                 return -ENOMEM;
2442
2443         lp->rx_buffers = dma_alloc_coherent(&lp->pdev->dev,
2444                                             AT91ETHER_MAX_RX_DESCR *
2445                                             AT91ETHER_MAX_RBUFF_SZ,
2446                                             &lp->rx_buffers_dma, GFP_KERNEL);
2447         if (!lp->rx_buffers) {
2448                 dma_free_coherent(&lp->pdev->dev,
2449                                   AT91ETHER_MAX_RX_DESCR *
2450                                   sizeof(struct macb_dma_desc),
2451                                   lp->rx_ring, lp->rx_ring_dma);
2452                 lp->rx_ring = NULL;
2453                 return -ENOMEM;
2454         }
2455
2456         addr = lp->rx_buffers_dma;
2457         for (i = 0; i < AT91ETHER_MAX_RX_DESCR; i++) {
2458                 lp->rx_ring[i].addr = addr;
2459                 lp->rx_ring[i].ctrl = 0;
2460                 addr += AT91ETHER_MAX_RBUFF_SZ;
2461         }
2462
2463         /* Set the Wrap bit on the last descriptor */
2464         lp->rx_ring[AT91ETHER_MAX_RX_DESCR - 1].addr |= MACB_BIT(RX_WRAP);
2465
2466         /* Reset buffer index */
2467         lp->rx_tail = 0;
2468
2469         /* Program address of descriptor list in Rx Buffer Queue register */
2470         macb_writel(lp, RBQP, lp->rx_ring_dma);
2471
2472         /* Enable Receive and Transmit */
2473         ctl = macb_readl(lp, NCR);
2474         macb_writel(lp, NCR, ctl | MACB_BIT(RE) | MACB_BIT(TE));
2475
2476         return 0;
2477 }
2478
2479 /* Open the ethernet interface */
2480 static int at91ether_open(struct net_device *dev)
2481 {
2482         struct macb *lp = netdev_priv(dev);
2483         u32 ctl;
2484         int ret;
2485
2486         /* Clear internal statistics */
2487         ctl = macb_readl(lp, NCR);
2488         macb_writel(lp, NCR, ctl | MACB_BIT(CLRSTAT));
2489
2490         macb_set_hwaddr(lp);
2491
2492         ret = at91ether_start(dev);
2493         if (ret)
2494                 return ret;
2495
2496         /* Enable MAC interrupts */
2497         macb_writel(lp, IER, MACB_BIT(RCOMP)    |
2498                              MACB_BIT(RXUBR)    |
2499                              MACB_BIT(ISR_TUND) |
2500                              MACB_BIT(ISR_RLE)  |
2501                              MACB_BIT(TCOMP)    |
2502                              MACB_BIT(ISR_ROVR) |
2503                              MACB_BIT(HRESP));
2504
2505         /* schedule a link state check */
2506         phy_start(lp->phy_dev);
2507
2508         netif_start_queue(dev);
2509
2510         return 0;
2511 }
2512
2513 /* Close the interface */
2514 static int at91ether_close(struct net_device *dev)
2515 {
2516         struct macb *lp = netdev_priv(dev);
2517         u32 ctl;
2518
2519         /* Disable Receiver and Transmitter */
2520         ctl = macb_readl(lp, NCR);
2521         macb_writel(lp, NCR, ctl & ~(MACB_BIT(TE) | MACB_BIT(RE)));
2522
2523         /* Disable MAC interrupts */
2524         macb_writel(lp, IDR, MACB_BIT(RCOMP)    |
2525                              MACB_BIT(RXUBR)    |
2526                              MACB_BIT(ISR_TUND) |
2527                              MACB_BIT(ISR_RLE)  |
2528                              MACB_BIT(TCOMP)    |
2529                              MACB_BIT(ISR_ROVR) |
2530                              MACB_BIT(HRESP));
2531
2532         netif_stop_queue(dev);
2533
2534         dma_free_coherent(&lp->pdev->dev,
2535                           AT91ETHER_MAX_RX_DESCR *
2536                           sizeof(struct macb_dma_desc),
2537                           lp->rx_ring, lp->rx_ring_dma);
2538         lp->rx_ring = NULL;
2539
2540         dma_free_coherent(&lp->pdev->dev,
2541                           AT91ETHER_MAX_RX_DESCR * AT91ETHER_MAX_RBUFF_SZ,
2542                           lp->rx_buffers, lp->rx_buffers_dma);
2543         lp->rx_buffers = NULL;
2544
2545         return 0;
2546 }
2547
2548 /* Transmit packet */
2549 static int at91ether_start_xmit(struct sk_buff *skb, struct net_device *dev)
2550 {
2551         struct macb *lp = netdev_priv(dev);
2552
2553         if (macb_readl(lp, TSR) & MACB_BIT(RM9200_BNQ)) {
2554                 netif_stop_queue(dev);
2555
2556                 /* Store packet information (to free when Tx completed) */
2557                 lp->skb = skb;
2558                 lp->skb_length = skb->len;
2559                 lp->skb_physaddr = dma_map_single(NULL, skb->data, skb->len,
2560                                                         DMA_TO_DEVICE);
2561
2562                 /* Set address of the data in the Transmit Address register */
2563                 macb_writel(lp, TAR, lp->skb_physaddr);
2564                 /* Set length of the packet in the Transmit Control register */
2565                 macb_writel(lp, TCR, skb->len);
2566
2567         } else {
2568                 netdev_err(dev, "%s called, but device is busy!\n", __func__);
2569                 return NETDEV_TX_BUSY;
2570         }
2571
2572         return NETDEV_TX_OK;
2573 }
2574
2575 /* Extract received frame from buffer descriptors and sent to upper layers.
2576  * (Called from interrupt context)
2577  */
2578 static void at91ether_rx(struct net_device *dev)
2579 {
2580         struct macb *lp = netdev_priv(dev);
2581         unsigned char *p_recv;
2582         struct sk_buff *skb;
2583         unsigned int pktlen;
2584
2585         while (lp->rx_ring[lp->rx_tail].addr & MACB_BIT(RX_USED)) {
2586                 p_recv = lp->rx_buffers + lp->rx_tail * AT91ETHER_MAX_RBUFF_SZ;
2587                 pktlen = MACB_BF(RX_FRMLEN, lp->rx_ring[lp->rx_tail].ctrl);
2588                 skb = netdev_alloc_skb(dev, pktlen + 2);
2589                 if (skb) {
2590                         skb_reserve(skb, 2);
2591                         memcpy(skb_put(skb, pktlen), p_recv, pktlen);
2592
2593                         skb->protocol = eth_type_trans(skb, dev);
2594                         lp->stats.rx_packets++;
2595                         lp->stats.rx_bytes += pktlen;
2596                         netif_rx(skb);
2597                 } else {
2598                         lp->stats.rx_dropped++;
2599                 }
2600
2601                 if (lp->rx_ring[lp->rx_tail].ctrl & MACB_BIT(RX_MHASH_MATCH))
2602                         lp->stats.multicast++;
2603
2604                 /* reset ownership bit */
2605                 lp->rx_ring[lp->rx_tail].addr &= ~MACB_BIT(RX_USED);
2606
2607                 /* wrap after last buffer */
2608                 if (lp->rx_tail == AT91ETHER_MAX_RX_DESCR - 1)
2609                         lp->rx_tail = 0;
2610                 else
2611                         lp->rx_tail++;
2612         }
2613 }
2614
2615 /* MAC interrupt handler */
2616 static irqreturn_t at91ether_interrupt(int irq, void *dev_id)
2617 {
2618         struct net_device *dev = dev_id;
2619         struct macb *lp = netdev_priv(dev);
2620         u32 intstatus, ctl;
2621
2622         /* MAC Interrupt Status register indicates what interrupts are pending.
2623          * It is automatically cleared once read.
2624          */
2625         intstatus = macb_readl(lp, ISR);
2626
2627         /* Receive complete */
2628         if (intstatus & MACB_BIT(RCOMP))
2629                 at91ether_rx(dev);
2630
2631         /* Transmit complete */
2632         if (intstatus & MACB_BIT(TCOMP)) {
2633                 /* The TCOM bit is set even if the transmission failed */
2634                 if (intstatus & (MACB_BIT(ISR_TUND) | MACB_BIT(ISR_RLE)))
2635                         lp->stats.tx_errors++;
2636
2637                 if (lp->skb) {
2638                         dev_kfree_skb_irq(lp->skb);
2639                         lp->skb = NULL;
2640                         dma_unmap_single(NULL, lp->skb_physaddr,
2641                                          lp->skb_length, DMA_TO_DEVICE);
2642                         lp->stats.tx_packets++;
2643                         lp->stats.tx_bytes += lp->skb_length;
2644                 }
2645                 netif_wake_queue(dev);
2646         }
2647
2648         /* Work-around for EMAC Errata section 41.3.1 */
2649         if (intstatus & MACB_BIT(RXUBR)) {
2650                 ctl = macb_readl(lp, NCR);
2651                 macb_writel(lp, NCR, ctl & ~MACB_BIT(RE));
2652                 macb_writel(lp, NCR, ctl | MACB_BIT(RE));
2653         }
2654
2655         if (intstatus & MACB_BIT(ISR_ROVR))
2656                 netdev_err(dev, "ROVR error\n");
2657
2658         return IRQ_HANDLED;
2659 }
2660
2661 #ifdef CONFIG_NET_POLL_CONTROLLER
2662 static void at91ether_poll_controller(struct net_device *dev)
2663 {
2664         unsigned long flags;
2665
2666         local_irq_save(flags);
2667         at91ether_interrupt(dev->irq, dev);
2668         local_irq_restore(flags);
2669 }
2670 #endif
2671
2672 static const struct net_device_ops at91ether_netdev_ops = {
2673         .ndo_open               = at91ether_open,
2674         .ndo_stop               = at91ether_close,
2675         .ndo_start_xmit         = at91ether_start_xmit,
2676         .ndo_get_stats          = macb_get_stats,
2677         .ndo_set_rx_mode        = macb_set_rx_mode,
2678         .ndo_set_mac_address    = eth_mac_addr,
2679         .ndo_do_ioctl           = macb_ioctl,
2680         .ndo_validate_addr      = eth_validate_addr,
2681         .ndo_change_mtu         = eth_change_mtu,
2682 #ifdef CONFIG_NET_POLL_CONTROLLER
2683         .ndo_poll_controller    = at91ether_poll_controller,
2684 #endif
2685 };
2686
2687 static int at91ether_clk_init(struct platform_device *pdev, struct clk **pclk,
2688                               struct clk **hclk, struct clk **tx_clk)
2689 {
2690         int err;
2691
2692         *hclk = NULL;
2693         *tx_clk = NULL;
2694
2695         *pclk = devm_clk_get(&pdev->dev, "ether_clk");
2696         if (IS_ERR(*pclk))
2697                 return PTR_ERR(*pclk);
2698
2699         err = clk_prepare_enable(*pclk);
2700         if (err) {
2701                 dev_err(&pdev->dev, "failed to enable pclk (%u)\n", err);
2702                 return err;
2703         }
2704
2705         return 0;
2706 }
2707
2708 static int at91ether_init(struct platform_device *pdev)
2709 {
2710         struct net_device *dev = platform_get_drvdata(pdev);
2711         struct macb *bp = netdev_priv(dev);
2712         int err;
2713         u32 reg;
2714
2715         dev->netdev_ops = &at91ether_netdev_ops;
2716         dev->ethtool_ops = &macb_ethtool_ops;
2717
2718         err = devm_request_irq(&pdev->dev, dev->irq, at91ether_interrupt,
2719                                0, dev->name, dev);
2720         if (err)
2721                 return err;
2722
2723         macb_writel(bp, NCR, 0);
2724
2725         reg = MACB_BF(CLK, MACB_CLK_DIV32) | MACB_BIT(BIG);
2726         if (bp->phy_interface == PHY_INTERFACE_MODE_RMII)
2727                 reg |= MACB_BIT(RM9200_RMII);
2728
2729         macb_writel(bp, NCFGR, reg);
2730
2731         return 0;
2732 }
2733
2734 static const struct macb_config at91sam9260_config = {
2735         .caps = MACB_CAPS_USRIO_HAS_CLKEN | MACB_CAPS_USRIO_DEFAULT_IS_MII,
2736         .clk_init = macb_clk_init,
2737         .init = macb_init,
2738 };
2739
2740 static const struct macb_config pc302gem_config = {
2741         .caps = MACB_CAPS_SG_DISABLED | MACB_CAPS_GIGABIT_MODE_AVAILABLE,
2742         .dma_burst_length = 16,
2743         .clk_init = macb_clk_init,
2744         .init = macb_init,
2745 };
2746
2747 static const struct macb_config sama5d2_config = {
2748         .caps = 0,
2749         .dma_burst_length = 16,
2750         .clk_init = macb_clk_init,
2751         .init = macb_init,
2752 };
2753
2754 static const struct macb_config sama5d3_config = {
2755         .caps = MACB_CAPS_SG_DISABLED | MACB_CAPS_GIGABIT_MODE_AVAILABLE,
2756         .dma_burst_length = 16,
2757         .clk_init = macb_clk_init,
2758         .init = macb_init,
2759 };
2760
2761 static const struct macb_config sama5d4_config = {
2762         .caps = 0,
2763         .dma_burst_length = 4,
2764         .clk_init = macb_clk_init,
2765         .init = macb_init,
2766 };
2767
2768 static const struct macb_config emac_config = {
2769         .clk_init = at91ether_clk_init,
2770         .init = at91ether_init,
2771 };
2772
2773
2774 static const struct macb_config zynqmp_config = {
2775         .caps = MACB_CAPS_GIGABIT_MODE_AVAILABLE | MACB_CAPS_JUMBO,
2776         .dma_burst_length = 16,
2777         .clk_init = macb_clk_init,
2778         .init = macb_init,
2779         .jumbo_max_len = 10240,
2780 };
2781
2782 static const struct macb_config zynq_config = {
2783         .caps = MACB_CAPS_GIGABIT_MODE_AVAILABLE | MACB_CAPS_NO_GIGABIT_HALF,
2784         .dma_burst_length = 16,
2785         .clk_init = macb_clk_init,
2786         .init = macb_init,
2787 };
2788
2789 static const struct of_device_id macb_dt_ids[] = {
2790         { .compatible = "cdns,at32ap7000-macb" },
2791         { .compatible = "cdns,at91sam9260-macb", .data = &at91sam9260_config },
2792         { .compatible = "cdns,macb" },
2793         { .compatible = "cdns,pc302-gem", .data = &pc302gem_config },
2794         { .compatible = "cdns,gem", .data = &pc302gem_config },
2795         { .compatible = "atmel,sama5d2-gem", .data = &sama5d2_config },
2796         { .compatible = "atmel,sama5d3-gem", .data = &sama5d3_config },
2797         { .compatible = "atmel,sama5d4-gem", .data = &sama5d4_config },
2798         { .compatible = "cdns,at91rm9200-emac", .data = &emac_config },
2799         { .compatible = "cdns,emac", .data = &emac_config },
2800         { .compatible = "cdns,zynqmp-gem", .data = &zynqmp_config},
2801         { .compatible = "cdns,zynq-gem", .data = &zynq_config },
2802         { /* sentinel */ }
2803 };
2804 MODULE_DEVICE_TABLE(of, macb_dt_ids);
2805 #endif /* CONFIG_OF */
2806
2807 static int macb_probe(struct platform_device *pdev)
2808 {
2809         int (*clk_init)(struct platform_device *, struct clk **,
2810                         struct clk **, struct clk **)
2811                                               = macb_clk_init;
2812         int (*init)(struct platform_device *) = macb_init;
2813         struct device_node *np = pdev->dev.of_node;
2814         struct device_node *phy_node;
2815         const struct macb_config *macb_config = NULL;
2816         struct clk *pclk, *hclk, *tx_clk;
2817         unsigned int queue_mask, num_queues;
2818         struct macb_platform_data *pdata;
2819         bool native_io;
2820         struct phy_device *phydev;
2821         struct net_device *dev;
2822         struct resource *regs;
2823         void __iomem *mem;
2824         const char *mac;
2825         struct macb *bp;
2826         int err;
2827
2828         regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2829         mem = devm_ioremap_resource(&pdev->dev, regs);
2830         if (IS_ERR(mem))
2831                 return PTR_ERR(mem);
2832
2833         if (np) {
2834                 const struct of_device_id *match;
2835
2836                 match = of_match_node(macb_dt_ids, np);
2837                 if (match && match->data) {
2838                         macb_config = match->data;
2839                         clk_init = macb_config->clk_init;
2840                         init = macb_config->init;
2841                 }
2842         }
2843
2844         err = clk_init(pdev, &pclk, &hclk, &tx_clk);
2845         if (err)
2846                 return err;
2847
2848         native_io = hw_is_native_io(mem);
2849
2850         macb_probe_queues(mem, native_io, &queue_mask, &num_queues);
2851         dev = alloc_etherdev_mq(sizeof(*bp), num_queues);
2852         if (!dev) {
2853                 err = -ENOMEM;
2854                 goto err_disable_clocks;
2855         }
2856
2857         dev->base_addr = regs->start;
2858
2859         SET_NETDEV_DEV(dev, &pdev->dev);
2860
2861         bp = netdev_priv(dev);
2862         bp->pdev = pdev;
2863         bp->dev = dev;
2864         bp->regs = mem;
2865         bp->native_io = native_io;
2866         if (native_io) {
2867                 bp->macb_reg_readl = hw_readl_native;
2868                 bp->macb_reg_writel = hw_writel_native;
2869         } else {
2870                 bp->macb_reg_readl = hw_readl;
2871                 bp->macb_reg_writel = hw_writel;
2872         }
2873         bp->num_queues = num_queues;
2874         bp->queue_mask = queue_mask;
2875         if (macb_config)
2876                 bp->dma_burst_length = macb_config->dma_burst_length;
2877         bp->pclk = pclk;
2878         bp->hclk = hclk;
2879         bp->tx_clk = tx_clk;
2880         if (macb_config)
2881                 bp->jumbo_max_len = macb_config->jumbo_max_len;
2882
2883         spin_lock_init(&bp->lock);
2884
2885         /* setup capabilities */
2886         macb_configure_caps(bp, macb_config);
2887
2888         platform_set_drvdata(pdev, dev);
2889
2890         dev->irq = platform_get_irq(pdev, 0);
2891         if (dev->irq < 0) {
2892                 err = dev->irq;
2893                 goto err_disable_clocks;
2894         }
2895
2896         mac = of_get_mac_address(np);
2897         if (mac)
2898                 memcpy(bp->dev->dev_addr, mac, ETH_ALEN);
2899         else
2900                 macb_get_hwaddr(bp);
2901
2902         /* Power up the PHY if there is a GPIO reset */
2903         phy_node =  of_get_next_available_child(np, NULL);
2904         if (phy_node) {
2905                 int gpio = of_get_named_gpio(phy_node, "reset-gpios", 0);
2906                 if (gpio_is_valid(gpio))
2907                         bp->reset_gpio = gpio_to_desc(gpio);
2908                 gpiod_set_value(bp->reset_gpio, GPIOD_OUT_HIGH);
2909         }
2910         of_node_put(phy_node);
2911
2912         err = of_get_phy_mode(np);
2913         if (err < 0) {
2914                 pdata = dev_get_platdata(&pdev->dev);
2915                 if (pdata && pdata->is_rmii)
2916                         bp->phy_interface = PHY_INTERFACE_MODE_RMII;
2917                 else
2918                         bp->phy_interface = PHY_INTERFACE_MODE_MII;
2919         } else {
2920                 bp->phy_interface = err;
2921         }
2922
2923         /* IP specific init */
2924         err = init(pdev);
2925         if (err)
2926                 goto err_out_free_netdev;
2927
2928         err = register_netdev(dev);
2929         if (err) {
2930                 dev_err(&pdev->dev, "Cannot register net device, aborting.\n");
2931                 goto err_out_unregister_netdev;
2932         }
2933
2934         err = macb_mii_init(bp);
2935         if (err)
2936                 goto err_out_unregister_netdev;
2937
2938         netif_carrier_off(dev);
2939
2940         netdev_info(dev, "Cadence %s rev 0x%08x at 0x%08lx irq %d (%pM)\n",
2941                     macb_is_gem(bp) ? "GEM" : "MACB", macb_readl(bp, MID),
2942                     dev->base_addr, dev->irq, dev->dev_addr);
2943
2944         phydev = bp->phy_dev;
2945         phy_attached_info(phydev);
2946
2947         return 0;
2948
2949 err_out_unregister_netdev:
2950         unregister_netdev(dev);
2951
2952 err_out_free_netdev:
2953         free_netdev(dev);
2954
2955 err_disable_clocks:
2956         clk_disable_unprepare(tx_clk);
2957         clk_disable_unprepare(hclk);
2958         clk_disable_unprepare(pclk);
2959
2960         return err;
2961 }
2962
2963 static int macb_remove(struct platform_device *pdev)
2964 {
2965         struct net_device *dev;
2966         struct macb *bp;
2967
2968         dev = platform_get_drvdata(pdev);
2969
2970         if (dev) {
2971                 bp = netdev_priv(dev);
2972                 if (bp->phy_dev)
2973                         phy_disconnect(bp->phy_dev);
2974                 mdiobus_unregister(bp->mii_bus);
2975                 mdiobus_free(bp->mii_bus);
2976
2977                 /* Shutdown the PHY if there is a GPIO reset */
2978                 gpiod_set_value(bp->reset_gpio, GPIOD_OUT_LOW);
2979
2980                 unregister_netdev(dev);
2981                 clk_disable_unprepare(bp->tx_clk);
2982                 clk_disable_unprepare(bp->hclk);
2983                 clk_disable_unprepare(bp->pclk);
2984                 free_netdev(dev);
2985         }
2986
2987         return 0;
2988 }
2989
2990 static int __maybe_unused macb_suspend(struct device *dev)
2991 {
2992         struct platform_device *pdev = to_platform_device(dev);
2993         struct net_device *netdev = platform_get_drvdata(pdev);
2994         struct macb *bp = netdev_priv(netdev);
2995
2996         netif_carrier_off(netdev);
2997         netif_device_detach(netdev);
2998
2999         clk_disable_unprepare(bp->tx_clk);
3000         clk_disable_unprepare(bp->hclk);
3001         clk_disable_unprepare(bp->pclk);
3002
3003         return 0;
3004 }
3005
3006 static int __maybe_unused macb_resume(struct device *dev)
3007 {
3008         struct platform_device *pdev = to_platform_device(dev);
3009         struct net_device *netdev = platform_get_drvdata(pdev);
3010         struct macb *bp = netdev_priv(netdev);
3011
3012         clk_prepare_enable(bp->pclk);
3013         clk_prepare_enable(bp->hclk);
3014         clk_prepare_enable(bp->tx_clk);
3015
3016         netif_device_attach(netdev);
3017
3018         return 0;
3019 }
3020
3021 static SIMPLE_DEV_PM_OPS(macb_pm_ops, macb_suspend, macb_resume);
3022
3023 static struct platform_driver macb_driver = {
3024         .probe          = macb_probe,
3025         .remove         = macb_remove,
3026         .driver         = {
3027                 .name           = "macb",
3028                 .of_match_table = of_match_ptr(macb_dt_ids),
3029                 .pm     = &macb_pm_ops,
3030         },
3031 };
3032
3033 module_platform_driver(macb_driver);
3034
3035 MODULE_LICENSE("GPL");
3036 MODULE_DESCRIPTION("Cadence MACB/GEM Ethernet driver");
3037 MODULE_AUTHOR("Haavard Skinnemoen (Atmel)");
3038 MODULE_ALIAS("platform:macb");