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