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