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