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