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