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