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