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