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