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