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