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