1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2013 - 2019 Intel Corporation. */
3 
4 #include <linux/types.h>
5 #include <linux/module.h>
6 #include <net/ipv6.h>
7 #include <net/ip.h>
8 #include <net/tcp.h>
9 #include <linux/if_macvlan.h>
10 #include <linux/prefetch.h>
11 
12 #include "fm10k.h"
13 
14 #define DRV_SUMMARY	"Intel(R) Ethernet Switch Host Interface Driver"
15 char fm10k_driver_name[] = "fm10k";
16 static const char fm10k_driver_string[] = DRV_SUMMARY;
17 static const char fm10k_copyright[] =
18 	"Copyright(c) 2013 - 2019 Intel Corporation.";
19 
20 MODULE_AUTHOR("Intel Corporation, <linux.nics@intel.com>");
21 MODULE_DESCRIPTION(DRV_SUMMARY);
22 MODULE_LICENSE("GPL v2");
23 
24 /* single workqueue for entire fm10k driver */
25 struct workqueue_struct *fm10k_workqueue;
26 
27 /**
28  * fm10k_init_module - Driver Registration Routine
29  *
30  * fm10k_init_module is the first routine called when the driver is
31  * loaded.  All it does is register with the PCI subsystem.
32  **/
33 static int __init fm10k_init_module(void)
34 {
35 	pr_info("%s\n", fm10k_driver_string);
36 	pr_info("%s\n", fm10k_copyright);
37 
38 	/* create driver workqueue */
39 	fm10k_workqueue = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0,
40 					  fm10k_driver_name);
41 	if (!fm10k_workqueue)
42 		return -ENOMEM;
43 
44 	fm10k_dbg_init();
45 
46 	return fm10k_register_pci_driver();
47 }
48 module_init(fm10k_init_module);
49 
50 /**
51  * fm10k_exit_module - Driver Exit Cleanup Routine
52  *
53  * fm10k_exit_module is called just before the driver is removed
54  * from memory.
55  **/
56 static void __exit fm10k_exit_module(void)
57 {
58 	fm10k_unregister_pci_driver();
59 
60 	fm10k_dbg_exit();
61 
62 	/* destroy driver workqueue */
63 	destroy_workqueue(fm10k_workqueue);
64 }
65 module_exit(fm10k_exit_module);
66 
67 static bool fm10k_alloc_mapped_page(struct fm10k_ring *rx_ring,
68 				    struct fm10k_rx_buffer *bi)
69 {
70 	struct page *page = bi->page;
71 	dma_addr_t dma;
72 
73 	/* Only page will be NULL if buffer was consumed */
74 	if (likely(page))
75 		return true;
76 
77 	/* alloc new page for storage */
78 	page = dev_alloc_page();
79 	if (unlikely(!page)) {
80 		rx_ring->rx_stats.alloc_failed++;
81 		return false;
82 	}
83 
84 	/* map page for use */
85 	dma = dma_map_page(rx_ring->dev, page, 0, PAGE_SIZE, DMA_FROM_DEVICE);
86 
87 	/* if mapping failed free memory back to system since
88 	 * there isn't much point in holding memory we can't use
89 	 */
90 	if (dma_mapping_error(rx_ring->dev, dma)) {
91 		__free_page(page);
92 
93 		rx_ring->rx_stats.alloc_failed++;
94 		return false;
95 	}
96 
97 	bi->dma = dma;
98 	bi->page = page;
99 	bi->page_offset = 0;
100 
101 	return true;
102 }
103 
104 /**
105  * fm10k_alloc_rx_buffers - Replace used receive buffers
106  * @rx_ring: ring to place buffers on
107  * @cleaned_count: number of buffers to replace
108  **/
109 void fm10k_alloc_rx_buffers(struct fm10k_ring *rx_ring, u16 cleaned_count)
110 {
111 	union fm10k_rx_desc *rx_desc;
112 	struct fm10k_rx_buffer *bi;
113 	u16 i = rx_ring->next_to_use;
114 
115 	/* nothing to do */
116 	if (!cleaned_count)
117 		return;
118 
119 	rx_desc = FM10K_RX_DESC(rx_ring, i);
120 	bi = &rx_ring->rx_buffer[i];
121 	i -= rx_ring->count;
122 
123 	do {
124 		if (!fm10k_alloc_mapped_page(rx_ring, bi))
125 			break;
126 
127 		/* Refresh the desc even if buffer_addrs didn't change
128 		 * because each write-back erases this info.
129 		 */
130 		rx_desc->q.pkt_addr = cpu_to_le64(bi->dma + bi->page_offset);
131 
132 		rx_desc++;
133 		bi++;
134 		i++;
135 		if (unlikely(!i)) {
136 			rx_desc = FM10K_RX_DESC(rx_ring, 0);
137 			bi = rx_ring->rx_buffer;
138 			i -= rx_ring->count;
139 		}
140 
141 		/* clear the status bits for the next_to_use descriptor */
142 		rx_desc->d.staterr = 0;
143 
144 		cleaned_count--;
145 	} while (cleaned_count);
146 
147 	i += rx_ring->count;
148 
149 	if (rx_ring->next_to_use != i) {
150 		/* record the next descriptor to use */
151 		rx_ring->next_to_use = i;
152 
153 		/* update next to alloc since we have filled the ring */
154 		rx_ring->next_to_alloc = i;
155 
156 		/* Force memory writes to complete before letting h/w
157 		 * know there are new descriptors to fetch.  (Only
158 		 * applicable for weak-ordered memory model archs,
159 		 * such as IA-64).
160 		 */
161 		wmb();
162 
163 		/* notify hardware of new descriptors */
164 		writel(i, rx_ring->tail);
165 	}
166 }
167 
168 /**
169  * fm10k_reuse_rx_page - page flip buffer and store it back on the ring
170  * @rx_ring: rx descriptor ring to store buffers on
171  * @old_buff: donor buffer to have page reused
172  *
173  * Synchronizes page for reuse by the interface
174  **/
175 static void fm10k_reuse_rx_page(struct fm10k_ring *rx_ring,
176 				struct fm10k_rx_buffer *old_buff)
177 {
178 	struct fm10k_rx_buffer *new_buff;
179 	u16 nta = rx_ring->next_to_alloc;
180 
181 	new_buff = &rx_ring->rx_buffer[nta];
182 
183 	/* update, and store next to alloc */
184 	nta++;
185 	rx_ring->next_to_alloc = (nta < rx_ring->count) ? nta : 0;
186 
187 	/* transfer page from old buffer to new buffer */
188 	*new_buff = *old_buff;
189 
190 	/* sync the buffer for use by the device */
191 	dma_sync_single_range_for_device(rx_ring->dev, old_buff->dma,
192 					 old_buff->page_offset,
193 					 FM10K_RX_BUFSZ,
194 					 DMA_FROM_DEVICE);
195 }
196 
197 static inline bool fm10k_page_is_reserved(struct page *page)
198 {
199 	return (page_to_nid(page) != numa_mem_id()) || page_is_pfmemalloc(page);
200 }
201 
202 static bool fm10k_can_reuse_rx_page(struct fm10k_rx_buffer *rx_buffer,
203 				    struct page *page,
204 				    unsigned int __maybe_unused truesize)
205 {
206 	/* avoid re-using remote pages */
207 	if (unlikely(fm10k_page_is_reserved(page)))
208 		return false;
209 
210 #if (PAGE_SIZE < 8192)
211 	/* if we are only owner of page we can reuse it */
212 	if (unlikely(page_count(page) != 1))
213 		return false;
214 
215 	/* flip page offset to other buffer */
216 	rx_buffer->page_offset ^= FM10K_RX_BUFSZ;
217 #else
218 	/* move offset up to the next cache line */
219 	rx_buffer->page_offset += truesize;
220 
221 	if (rx_buffer->page_offset > (PAGE_SIZE - FM10K_RX_BUFSZ))
222 		return false;
223 #endif
224 
225 	/* Even if we own the page, we are not allowed to use atomic_set()
226 	 * This would break get_page_unless_zero() users.
227 	 */
228 	page_ref_inc(page);
229 
230 	return true;
231 }
232 
233 /**
234  * fm10k_add_rx_frag - Add contents of Rx buffer to sk_buff
235  * @rx_buffer: buffer containing page to add
236  * @size: packet size from rx_desc
237  * @rx_desc: descriptor containing length of buffer written by hardware
238  * @skb: sk_buff to place the data into
239  *
240  * This function will add the data contained in rx_buffer->page to the skb.
241  * This is done either through a direct copy if the data in the buffer is
242  * less than the skb header size, otherwise it will just attach the page as
243  * a frag to the skb.
244  *
245  * The function will then update the page offset if necessary and return
246  * true if the buffer can be reused by the interface.
247  **/
248 static bool fm10k_add_rx_frag(struct fm10k_rx_buffer *rx_buffer,
249 			      unsigned int size,
250 			      union fm10k_rx_desc *rx_desc,
251 			      struct sk_buff *skb)
252 {
253 	struct page *page = rx_buffer->page;
254 	unsigned char *va = page_address(page) + rx_buffer->page_offset;
255 #if (PAGE_SIZE < 8192)
256 	unsigned int truesize = FM10K_RX_BUFSZ;
257 #else
258 	unsigned int truesize = ALIGN(size, 512);
259 #endif
260 	unsigned int pull_len;
261 
262 	if (unlikely(skb_is_nonlinear(skb)))
263 		goto add_tail_frag;
264 
265 	if (likely(size <= FM10K_RX_HDR_LEN)) {
266 		memcpy(__skb_put(skb, size), va, ALIGN(size, sizeof(long)));
267 
268 		/* page is not reserved, we can reuse buffer as-is */
269 		if (likely(!fm10k_page_is_reserved(page)))
270 			return true;
271 
272 		/* this page cannot be reused so discard it */
273 		__free_page(page);
274 		return false;
275 	}
276 
277 	/* we need the header to contain the greater of either ETH_HLEN or
278 	 * 60 bytes if the skb->len is less than 60 for skb_pad.
279 	 */
280 	pull_len = eth_get_headlen(skb->dev, va, FM10K_RX_HDR_LEN);
281 
282 	/* align pull length to size of long to optimize memcpy performance */
283 	memcpy(__skb_put(skb, pull_len), va, ALIGN(pull_len, sizeof(long)));
284 
285 	/* update all of the pointers */
286 	va += pull_len;
287 	size -= pull_len;
288 
289 add_tail_frag:
290 	skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page,
291 			(unsigned long)va & ~PAGE_MASK, size, truesize);
292 
293 	return fm10k_can_reuse_rx_page(rx_buffer, page, truesize);
294 }
295 
296 static struct sk_buff *fm10k_fetch_rx_buffer(struct fm10k_ring *rx_ring,
297 					     union fm10k_rx_desc *rx_desc,
298 					     struct sk_buff *skb)
299 {
300 	unsigned int size = le16_to_cpu(rx_desc->w.length);
301 	struct fm10k_rx_buffer *rx_buffer;
302 	struct page *page;
303 
304 	rx_buffer = &rx_ring->rx_buffer[rx_ring->next_to_clean];
305 	page = rx_buffer->page;
306 	prefetchw(page);
307 
308 	if (likely(!skb)) {
309 		void *page_addr = page_address(page) +
310 				  rx_buffer->page_offset;
311 
312 		/* prefetch first cache line of first page */
313 		net_prefetch(page_addr);
314 
315 		/* allocate a skb to store the frags */
316 		skb = napi_alloc_skb(&rx_ring->q_vector->napi,
317 				     FM10K_RX_HDR_LEN);
318 		if (unlikely(!skb)) {
319 			rx_ring->rx_stats.alloc_failed++;
320 			return NULL;
321 		}
322 
323 		/* we will be copying header into skb->data in
324 		 * pskb_may_pull so it is in our interest to prefetch
325 		 * it now to avoid a possible cache miss
326 		 */
327 		prefetchw(skb->data);
328 	}
329 
330 	/* we are reusing so sync this buffer for CPU use */
331 	dma_sync_single_range_for_cpu(rx_ring->dev,
332 				      rx_buffer->dma,
333 				      rx_buffer->page_offset,
334 				      size,
335 				      DMA_FROM_DEVICE);
336 
337 	/* pull page into skb */
338 	if (fm10k_add_rx_frag(rx_buffer, size, rx_desc, skb)) {
339 		/* hand second half of page back to the ring */
340 		fm10k_reuse_rx_page(rx_ring, rx_buffer);
341 	} else {
342 		/* we are not reusing the buffer so unmap it */
343 		dma_unmap_page(rx_ring->dev, rx_buffer->dma,
344 			       PAGE_SIZE, DMA_FROM_DEVICE);
345 	}
346 
347 	/* clear contents of rx_buffer */
348 	rx_buffer->page = NULL;
349 
350 	return skb;
351 }
352 
353 static inline void fm10k_rx_checksum(struct fm10k_ring *ring,
354 				     union fm10k_rx_desc *rx_desc,
355 				     struct sk_buff *skb)
356 {
357 	skb_checksum_none_assert(skb);
358 
359 	/* Rx checksum disabled via ethtool */
360 	if (!(ring->netdev->features & NETIF_F_RXCSUM))
361 		return;
362 
363 	/* TCP/UDP checksum error bit is set */
364 	if (fm10k_test_staterr(rx_desc,
365 			       FM10K_RXD_STATUS_L4E |
366 			       FM10K_RXD_STATUS_L4E2 |
367 			       FM10K_RXD_STATUS_IPE |
368 			       FM10K_RXD_STATUS_IPE2)) {
369 		ring->rx_stats.csum_err++;
370 		return;
371 	}
372 
373 	/* It must be a TCP or UDP packet with a valid checksum */
374 	if (fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_L4CS2))
375 		skb->encapsulation = true;
376 	else if (!fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_L4CS))
377 		return;
378 
379 	skb->ip_summed = CHECKSUM_UNNECESSARY;
380 
381 	ring->rx_stats.csum_good++;
382 }
383 
384 #define FM10K_RSS_L4_TYPES_MASK \
385 	(BIT(FM10K_RSSTYPE_IPV4_TCP) | \
386 	 BIT(FM10K_RSSTYPE_IPV4_UDP) | \
387 	 BIT(FM10K_RSSTYPE_IPV6_TCP) | \
388 	 BIT(FM10K_RSSTYPE_IPV6_UDP))
389 
390 static inline void fm10k_rx_hash(struct fm10k_ring *ring,
391 				 union fm10k_rx_desc *rx_desc,
392 				 struct sk_buff *skb)
393 {
394 	u16 rss_type;
395 
396 	if (!(ring->netdev->features & NETIF_F_RXHASH))
397 		return;
398 
399 	rss_type = le16_to_cpu(rx_desc->w.pkt_info) & FM10K_RXD_RSSTYPE_MASK;
400 	if (!rss_type)
401 		return;
402 
403 	skb_set_hash(skb, le32_to_cpu(rx_desc->d.rss),
404 		     (BIT(rss_type) & FM10K_RSS_L4_TYPES_MASK) ?
405 		     PKT_HASH_TYPE_L4 : PKT_HASH_TYPE_L3);
406 }
407 
408 static void fm10k_type_trans(struct fm10k_ring *rx_ring,
409 			     union fm10k_rx_desc __maybe_unused *rx_desc,
410 			     struct sk_buff *skb)
411 {
412 	struct net_device *dev = rx_ring->netdev;
413 	struct fm10k_l2_accel *l2_accel = rcu_dereference_bh(rx_ring->l2_accel);
414 
415 	/* check to see if DGLORT belongs to a MACVLAN */
416 	if (l2_accel) {
417 		u16 idx = le16_to_cpu(FM10K_CB(skb)->fi.w.dglort) - 1;
418 
419 		idx -= l2_accel->dglort;
420 		if (idx < l2_accel->size && l2_accel->macvlan[idx])
421 			dev = l2_accel->macvlan[idx];
422 		else
423 			l2_accel = NULL;
424 	}
425 
426 	/* Record Rx queue, or update macvlan statistics */
427 	if (!l2_accel)
428 		skb_record_rx_queue(skb, rx_ring->queue_index);
429 	else
430 		macvlan_count_rx(netdev_priv(dev), skb->len + ETH_HLEN, true,
431 				 false);
432 
433 	skb->protocol = eth_type_trans(skb, dev);
434 }
435 
436 /**
437  * fm10k_process_skb_fields - Populate skb header fields from Rx descriptor
438  * @rx_ring: rx descriptor ring packet is being transacted on
439  * @rx_desc: pointer to the EOP Rx descriptor
440  * @skb: pointer to current skb being populated
441  *
442  * This function checks the ring, descriptor, and packet information in
443  * order to populate the hash, checksum, VLAN, timestamp, protocol, and
444  * other fields within the skb.
445  **/
446 static unsigned int fm10k_process_skb_fields(struct fm10k_ring *rx_ring,
447 					     union fm10k_rx_desc *rx_desc,
448 					     struct sk_buff *skb)
449 {
450 	unsigned int len = skb->len;
451 
452 	fm10k_rx_hash(rx_ring, rx_desc, skb);
453 
454 	fm10k_rx_checksum(rx_ring, rx_desc, skb);
455 
456 	FM10K_CB(skb)->tstamp = rx_desc->q.timestamp;
457 
458 	FM10K_CB(skb)->fi.w.vlan = rx_desc->w.vlan;
459 
460 	FM10K_CB(skb)->fi.d.glort = rx_desc->d.glort;
461 
462 	if (rx_desc->w.vlan) {
463 		u16 vid = le16_to_cpu(rx_desc->w.vlan);
464 
465 		if ((vid & VLAN_VID_MASK) != rx_ring->vid)
466 			__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid);
467 		else if (vid & VLAN_PRIO_MASK)
468 			__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q),
469 					       vid & VLAN_PRIO_MASK);
470 	}
471 
472 	fm10k_type_trans(rx_ring, rx_desc, skb);
473 
474 	return len;
475 }
476 
477 /**
478  * fm10k_is_non_eop - process handling of non-EOP buffers
479  * @rx_ring: Rx ring being processed
480  * @rx_desc: Rx descriptor for current buffer
481  *
482  * This function updates next to clean.  If the buffer is an EOP buffer
483  * this function exits returning false, otherwise it will place the
484  * sk_buff in the next buffer to be chained and return true indicating
485  * that this is in fact a non-EOP buffer.
486  **/
487 static bool fm10k_is_non_eop(struct fm10k_ring *rx_ring,
488 			     union fm10k_rx_desc *rx_desc)
489 {
490 	u32 ntc = rx_ring->next_to_clean + 1;
491 
492 	/* fetch, update, and store next to clean */
493 	ntc = (ntc < rx_ring->count) ? ntc : 0;
494 	rx_ring->next_to_clean = ntc;
495 
496 	prefetch(FM10K_RX_DESC(rx_ring, ntc));
497 
498 	if (likely(fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_EOP)))
499 		return false;
500 
501 	return true;
502 }
503 
504 /**
505  * fm10k_cleanup_headers - Correct corrupted or empty headers
506  * @rx_ring: rx descriptor ring packet is being transacted on
507  * @rx_desc: pointer to the EOP Rx descriptor
508  * @skb: pointer to current skb being fixed
509  *
510  * Address the case where we are pulling data in on pages only
511  * and as such no data is present in the skb header.
512  *
513  * In addition if skb is not at least 60 bytes we need to pad it so that
514  * it is large enough to qualify as a valid Ethernet frame.
515  *
516  * Returns true if an error was encountered and skb was freed.
517  **/
518 static bool fm10k_cleanup_headers(struct fm10k_ring *rx_ring,
519 				  union fm10k_rx_desc *rx_desc,
520 				  struct sk_buff *skb)
521 {
522 	if (unlikely((fm10k_test_staterr(rx_desc,
523 					 FM10K_RXD_STATUS_RXE)))) {
524 #define FM10K_TEST_RXD_BIT(rxd, bit) \
525 	((rxd)->w.csum_err & cpu_to_le16(bit))
526 		if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_SWITCH_ERROR))
527 			rx_ring->rx_stats.switch_errors++;
528 		if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_NO_DESCRIPTOR))
529 			rx_ring->rx_stats.drops++;
530 		if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_PP_ERROR))
531 			rx_ring->rx_stats.pp_errors++;
532 		if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_SWITCH_READY))
533 			rx_ring->rx_stats.link_errors++;
534 		if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_TOO_BIG))
535 			rx_ring->rx_stats.length_errors++;
536 		dev_kfree_skb_any(skb);
537 		rx_ring->rx_stats.errors++;
538 		return true;
539 	}
540 
541 	/* if eth_skb_pad returns an error the skb was freed */
542 	if (eth_skb_pad(skb))
543 		return true;
544 
545 	return false;
546 }
547 
548 /**
549  * fm10k_receive_skb - helper function to handle rx indications
550  * @q_vector: structure containing interrupt and ring information
551  * @skb: packet to send up
552  **/
553 static void fm10k_receive_skb(struct fm10k_q_vector *q_vector,
554 			      struct sk_buff *skb)
555 {
556 	napi_gro_receive(&q_vector->napi, skb);
557 }
558 
559 static int fm10k_clean_rx_irq(struct fm10k_q_vector *q_vector,
560 			      struct fm10k_ring *rx_ring,
561 			      int budget)
562 {
563 	struct sk_buff *skb = rx_ring->skb;
564 	unsigned int total_bytes = 0, total_packets = 0;
565 	u16 cleaned_count = fm10k_desc_unused(rx_ring);
566 
567 	while (likely(total_packets < budget)) {
568 		union fm10k_rx_desc *rx_desc;
569 
570 		/* return some buffers to hardware, one at a time is too slow */
571 		if (cleaned_count >= FM10K_RX_BUFFER_WRITE) {
572 			fm10k_alloc_rx_buffers(rx_ring, cleaned_count);
573 			cleaned_count = 0;
574 		}
575 
576 		rx_desc = FM10K_RX_DESC(rx_ring, rx_ring->next_to_clean);
577 
578 		if (!rx_desc->d.staterr)
579 			break;
580 
581 		/* This memory barrier is needed to keep us from reading
582 		 * any other fields out of the rx_desc until we know the
583 		 * descriptor has been written back
584 		 */
585 		dma_rmb();
586 
587 		/* retrieve a buffer from the ring */
588 		skb = fm10k_fetch_rx_buffer(rx_ring, rx_desc, skb);
589 
590 		/* exit if we failed to retrieve a buffer */
591 		if (!skb)
592 			break;
593 
594 		cleaned_count++;
595 
596 		/* fetch next buffer in frame if non-eop */
597 		if (fm10k_is_non_eop(rx_ring, rx_desc))
598 			continue;
599 
600 		/* verify the packet layout is correct */
601 		if (fm10k_cleanup_headers(rx_ring, rx_desc, skb)) {
602 			skb = NULL;
603 			continue;
604 		}
605 
606 		/* populate checksum, timestamp, VLAN, and protocol */
607 		total_bytes += fm10k_process_skb_fields(rx_ring, rx_desc, skb);
608 
609 		fm10k_receive_skb(q_vector, skb);
610 
611 		/* reset skb pointer */
612 		skb = NULL;
613 
614 		/* update budget accounting */
615 		total_packets++;
616 	}
617 
618 	/* place incomplete frames back on ring for completion */
619 	rx_ring->skb = skb;
620 
621 	u64_stats_update_begin(&rx_ring->syncp);
622 	rx_ring->stats.packets += total_packets;
623 	rx_ring->stats.bytes += total_bytes;
624 	u64_stats_update_end(&rx_ring->syncp);
625 	q_vector->rx.total_packets += total_packets;
626 	q_vector->rx.total_bytes += total_bytes;
627 
628 	return total_packets;
629 }
630 
631 #define VXLAN_HLEN (sizeof(struct udphdr) + 8)
632 static struct ethhdr *fm10k_port_is_vxlan(struct sk_buff *skb)
633 {
634 	struct fm10k_intfc *interface = netdev_priv(skb->dev);
635 
636 	if (interface->vxlan_port != udp_hdr(skb)->dest)
637 		return NULL;
638 
639 	/* return offset of udp_hdr plus 8 bytes for VXLAN header */
640 	return (struct ethhdr *)(skb_transport_header(skb) + VXLAN_HLEN);
641 }
642 
643 #define FM10K_NVGRE_RESERVED0_FLAGS htons(0x9FFF)
644 #define NVGRE_TNI htons(0x2000)
645 struct fm10k_nvgre_hdr {
646 	__be16 flags;
647 	__be16 proto;
648 	__be32 tni;
649 };
650 
651 static struct ethhdr *fm10k_gre_is_nvgre(struct sk_buff *skb)
652 {
653 	struct fm10k_nvgre_hdr *nvgre_hdr;
654 	int hlen = ip_hdrlen(skb);
655 
656 	/* currently only IPv4 is supported due to hlen above */
657 	if (vlan_get_protocol(skb) != htons(ETH_P_IP))
658 		return NULL;
659 
660 	/* our transport header should be NVGRE */
661 	nvgre_hdr = (struct fm10k_nvgre_hdr *)(skb_network_header(skb) + hlen);
662 
663 	/* verify all reserved flags are 0 */
664 	if (nvgre_hdr->flags & FM10K_NVGRE_RESERVED0_FLAGS)
665 		return NULL;
666 
667 	/* report start of ethernet header */
668 	if (nvgre_hdr->flags & NVGRE_TNI)
669 		return (struct ethhdr *)(nvgre_hdr + 1);
670 
671 	return (struct ethhdr *)(&nvgre_hdr->tni);
672 }
673 
674 __be16 fm10k_tx_encap_offload(struct sk_buff *skb)
675 {
676 	u8 l4_hdr = 0, inner_l4_hdr = 0, inner_l4_hlen;
677 	struct ethhdr *eth_hdr;
678 
679 	if (skb->inner_protocol_type != ENCAP_TYPE_ETHER ||
680 	    skb->inner_protocol != htons(ETH_P_TEB))
681 		return 0;
682 
683 	switch (vlan_get_protocol(skb)) {
684 	case htons(ETH_P_IP):
685 		l4_hdr = ip_hdr(skb)->protocol;
686 		break;
687 	case htons(ETH_P_IPV6):
688 		l4_hdr = ipv6_hdr(skb)->nexthdr;
689 		break;
690 	default:
691 		return 0;
692 	}
693 
694 	switch (l4_hdr) {
695 	case IPPROTO_UDP:
696 		eth_hdr = fm10k_port_is_vxlan(skb);
697 		break;
698 	case IPPROTO_GRE:
699 		eth_hdr = fm10k_gre_is_nvgre(skb);
700 		break;
701 	default:
702 		return 0;
703 	}
704 
705 	if (!eth_hdr)
706 		return 0;
707 
708 	switch (eth_hdr->h_proto) {
709 	case htons(ETH_P_IP):
710 		inner_l4_hdr = inner_ip_hdr(skb)->protocol;
711 		break;
712 	case htons(ETH_P_IPV6):
713 		inner_l4_hdr = inner_ipv6_hdr(skb)->nexthdr;
714 		break;
715 	default:
716 		return 0;
717 	}
718 
719 	switch (inner_l4_hdr) {
720 	case IPPROTO_TCP:
721 		inner_l4_hlen = inner_tcp_hdrlen(skb);
722 		break;
723 	case IPPROTO_UDP:
724 		inner_l4_hlen = 8;
725 		break;
726 	default:
727 		return 0;
728 	}
729 
730 	/* The hardware allows tunnel offloads only if the combined inner and
731 	 * outer header is 184 bytes or less
732 	 */
733 	if (skb_inner_transport_header(skb) + inner_l4_hlen -
734 	    skb_mac_header(skb) > FM10K_TUNNEL_HEADER_LENGTH)
735 		return 0;
736 
737 	return eth_hdr->h_proto;
738 }
739 
740 static int fm10k_tso(struct fm10k_ring *tx_ring,
741 		     struct fm10k_tx_buffer *first)
742 {
743 	struct sk_buff *skb = first->skb;
744 	struct fm10k_tx_desc *tx_desc;
745 	unsigned char *th;
746 	u8 hdrlen;
747 
748 	if (skb->ip_summed != CHECKSUM_PARTIAL)
749 		return 0;
750 
751 	if (!skb_is_gso(skb))
752 		return 0;
753 
754 	/* compute header lengths */
755 	if (skb->encapsulation) {
756 		if (!fm10k_tx_encap_offload(skb))
757 			goto err_vxlan;
758 		th = skb_inner_transport_header(skb);
759 	} else {
760 		th = skb_transport_header(skb);
761 	}
762 
763 	/* compute offset from SOF to transport header and add header len */
764 	hdrlen = (th - skb->data) + (((struct tcphdr *)th)->doff << 2);
765 
766 	first->tx_flags |= FM10K_TX_FLAGS_CSUM;
767 
768 	/* update gso size and bytecount with header size */
769 	first->gso_segs = skb_shinfo(skb)->gso_segs;
770 	first->bytecount += (first->gso_segs - 1) * hdrlen;
771 
772 	/* populate Tx descriptor header size and mss */
773 	tx_desc = FM10K_TX_DESC(tx_ring, tx_ring->next_to_use);
774 	tx_desc->hdrlen = hdrlen;
775 	tx_desc->mss = cpu_to_le16(skb_shinfo(skb)->gso_size);
776 
777 	return 1;
778 
779 err_vxlan:
780 	tx_ring->netdev->features &= ~NETIF_F_GSO_UDP_TUNNEL;
781 	if (net_ratelimit())
782 		netdev_err(tx_ring->netdev,
783 			   "TSO requested for unsupported tunnel, disabling offload\n");
784 	return -1;
785 }
786 
787 static void fm10k_tx_csum(struct fm10k_ring *tx_ring,
788 			  struct fm10k_tx_buffer *first)
789 {
790 	struct sk_buff *skb = first->skb;
791 	struct fm10k_tx_desc *tx_desc;
792 	union {
793 		struct iphdr *ipv4;
794 		struct ipv6hdr *ipv6;
795 		u8 *raw;
796 	} network_hdr;
797 	u8 *transport_hdr;
798 	__be16 frag_off;
799 	__be16 protocol;
800 	u8 l4_hdr = 0;
801 
802 	if (skb->ip_summed != CHECKSUM_PARTIAL)
803 		goto no_csum;
804 
805 	if (skb->encapsulation) {
806 		protocol = fm10k_tx_encap_offload(skb);
807 		if (!protocol) {
808 			if (skb_checksum_help(skb)) {
809 				dev_warn(tx_ring->dev,
810 					 "failed to offload encap csum!\n");
811 				tx_ring->tx_stats.csum_err++;
812 			}
813 			goto no_csum;
814 		}
815 		network_hdr.raw = skb_inner_network_header(skb);
816 		transport_hdr = skb_inner_transport_header(skb);
817 	} else {
818 		protocol = vlan_get_protocol(skb);
819 		network_hdr.raw = skb_network_header(skb);
820 		transport_hdr = skb_transport_header(skb);
821 	}
822 
823 	switch (protocol) {
824 	case htons(ETH_P_IP):
825 		l4_hdr = network_hdr.ipv4->protocol;
826 		break;
827 	case htons(ETH_P_IPV6):
828 		l4_hdr = network_hdr.ipv6->nexthdr;
829 		if (likely((transport_hdr - network_hdr.raw) ==
830 			   sizeof(struct ipv6hdr)))
831 			break;
832 		ipv6_skip_exthdr(skb, network_hdr.raw - skb->data +
833 				      sizeof(struct ipv6hdr),
834 				 &l4_hdr, &frag_off);
835 		if (unlikely(frag_off))
836 			l4_hdr = NEXTHDR_FRAGMENT;
837 		break;
838 	default:
839 		break;
840 	}
841 
842 	switch (l4_hdr) {
843 	case IPPROTO_TCP:
844 	case IPPROTO_UDP:
845 		break;
846 	case IPPROTO_GRE:
847 		if (skb->encapsulation)
848 			break;
849 		fallthrough;
850 	default:
851 		if (unlikely(net_ratelimit())) {
852 			dev_warn(tx_ring->dev,
853 				 "partial checksum, version=%d l4 proto=%x\n",
854 				 protocol, l4_hdr);
855 		}
856 		skb_checksum_help(skb);
857 		tx_ring->tx_stats.csum_err++;
858 		goto no_csum;
859 	}
860 
861 	/* update TX checksum flag */
862 	first->tx_flags |= FM10K_TX_FLAGS_CSUM;
863 	tx_ring->tx_stats.csum_good++;
864 
865 no_csum:
866 	/* populate Tx descriptor header size and mss */
867 	tx_desc = FM10K_TX_DESC(tx_ring, tx_ring->next_to_use);
868 	tx_desc->hdrlen = 0;
869 	tx_desc->mss = 0;
870 }
871 
872 #define FM10K_SET_FLAG(_input, _flag, _result) \
873 	((_flag <= _result) ? \
874 	 ((u32)(_input & _flag) * (_result / _flag)) : \
875 	 ((u32)(_input & _flag) / (_flag / _result)))
876 
877 static u8 fm10k_tx_desc_flags(struct sk_buff *skb, u32 tx_flags)
878 {
879 	/* set type for advanced descriptor with frame checksum insertion */
880 	u32 desc_flags = 0;
881 
882 	/* set checksum offload bits */
883 	desc_flags |= FM10K_SET_FLAG(tx_flags, FM10K_TX_FLAGS_CSUM,
884 				     FM10K_TXD_FLAG_CSUM);
885 
886 	return desc_flags;
887 }
888 
889 static bool fm10k_tx_desc_push(struct fm10k_ring *tx_ring,
890 			       struct fm10k_tx_desc *tx_desc, u16 i,
891 			       dma_addr_t dma, unsigned int size, u8 desc_flags)
892 {
893 	/* set RS and INT for last frame in a cache line */
894 	if ((++i & (FM10K_TXD_WB_FIFO_SIZE - 1)) == 0)
895 		desc_flags |= FM10K_TXD_FLAG_RS | FM10K_TXD_FLAG_INT;
896 
897 	/* record values to descriptor */
898 	tx_desc->buffer_addr = cpu_to_le64(dma);
899 	tx_desc->flags = desc_flags;
900 	tx_desc->buflen = cpu_to_le16(size);
901 
902 	/* return true if we just wrapped the ring */
903 	return i == tx_ring->count;
904 }
905 
906 static int __fm10k_maybe_stop_tx(struct fm10k_ring *tx_ring, u16 size)
907 {
908 	netif_stop_subqueue(tx_ring->netdev, tx_ring->queue_index);
909 
910 	/* Memory barrier before checking head and tail */
911 	smp_mb();
912 
913 	/* Check again in a case another CPU has just made room available */
914 	if (likely(fm10k_desc_unused(tx_ring) < size))
915 		return -EBUSY;
916 
917 	/* A reprieve! - use start_queue because it doesn't call schedule */
918 	netif_start_subqueue(tx_ring->netdev, tx_ring->queue_index);
919 	++tx_ring->tx_stats.restart_queue;
920 	return 0;
921 }
922 
923 static inline int fm10k_maybe_stop_tx(struct fm10k_ring *tx_ring, u16 size)
924 {
925 	if (likely(fm10k_desc_unused(tx_ring) >= size))
926 		return 0;
927 	return __fm10k_maybe_stop_tx(tx_ring, size);
928 }
929 
930 static void fm10k_tx_map(struct fm10k_ring *tx_ring,
931 			 struct fm10k_tx_buffer *first)
932 {
933 	struct sk_buff *skb = first->skb;
934 	struct fm10k_tx_buffer *tx_buffer;
935 	struct fm10k_tx_desc *tx_desc;
936 	skb_frag_t *frag;
937 	unsigned char *data;
938 	dma_addr_t dma;
939 	unsigned int data_len, size;
940 	u32 tx_flags = first->tx_flags;
941 	u16 i = tx_ring->next_to_use;
942 	u8 flags = fm10k_tx_desc_flags(skb, tx_flags);
943 
944 	tx_desc = FM10K_TX_DESC(tx_ring, i);
945 
946 	/* add HW VLAN tag */
947 	if (skb_vlan_tag_present(skb))
948 		tx_desc->vlan = cpu_to_le16(skb_vlan_tag_get(skb));
949 	else
950 		tx_desc->vlan = 0;
951 
952 	size = skb_headlen(skb);
953 	data = skb->data;
954 
955 	dma = dma_map_single(tx_ring->dev, data, size, DMA_TO_DEVICE);
956 
957 	data_len = skb->data_len;
958 	tx_buffer = first;
959 
960 	for (frag = &skb_shinfo(skb)->frags[0];; frag++) {
961 		if (dma_mapping_error(tx_ring->dev, dma))
962 			goto dma_error;
963 
964 		/* record length, and DMA address */
965 		dma_unmap_len_set(tx_buffer, len, size);
966 		dma_unmap_addr_set(tx_buffer, dma, dma);
967 
968 		while (unlikely(size > FM10K_MAX_DATA_PER_TXD)) {
969 			if (fm10k_tx_desc_push(tx_ring, tx_desc++, i++, dma,
970 					       FM10K_MAX_DATA_PER_TXD, flags)) {
971 				tx_desc = FM10K_TX_DESC(tx_ring, 0);
972 				i = 0;
973 			}
974 
975 			dma += FM10K_MAX_DATA_PER_TXD;
976 			size -= FM10K_MAX_DATA_PER_TXD;
977 		}
978 
979 		if (likely(!data_len))
980 			break;
981 
982 		if (fm10k_tx_desc_push(tx_ring, tx_desc++, i++,
983 				       dma, size, flags)) {
984 			tx_desc = FM10K_TX_DESC(tx_ring, 0);
985 			i = 0;
986 		}
987 
988 		size = skb_frag_size(frag);
989 		data_len -= size;
990 
991 		dma = skb_frag_dma_map(tx_ring->dev, frag, 0, size,
992 				       DMA_TO_DEVICE);
993 
994 		tx_buffer = &tx_ring->tx_buffer[i];
995 	}
996 
997 	/* write last descriptor with LAST bit set */
998 	flags |= FM10K_TXD_FLAG_LAST;
999 
1000 	if (fm10k_tx_desc_push(tx_ring, tx_desc, i++, dma, size, flags))
1001 		i = 0;
1002 
1003 	/* record bytecount for BQL */
1004 	netdev_tx_sent_queue(txring_txq(tx_ring), first->bytecount);
1005 
1006 	/* record SW timestamp if HW timestamp is not available */
1007 	skb_tx_timestamp(first->skb);
1008 
1009 	/* Force memory writes to complete before letting h/w know there
1010 	 * are new descriptors to fetch.  (Only applicable for weak-ordered
1011 	 * memory model archs, such as IA-64).
1012 	 *
1013 	 * We also need this memory barrier to make certain all of the
1014 	 * status bits have been updated before next_to_watch is written.
1015 	 */
1016 	wmb();
1017 
1018 	/* set next_to_watch value indicating a packet is present */
1019 	first->next_to_watch = tx_desc;
1020 
1021 	tx_ring->next_to_use = i;
1022 
1023 	/* Make sure there is space in the ring for the next send. */
1024 	fm10k_maybe_stop_tx(tx_ring, DESC_NEEDED);
1025 
1026 	/* notify HW of packet */
1027 	if (netif_xmit_stopped(txring_txq(tx_ring)) || !netdev_xmit_more()) {
1028 		writel(i, tx_ring->tail);
1029 	}
1030 
1031 	return;
1032 dma_error:
1033 	dev_err(tx_ring->dev, "TX DMA map failed\n");
1034 
1035 	/* clear dma mappings for failed tx_buffer map */
1036 	for (;;) {
1037 		tx_buffer = &tx_ring->tx_buffer[i];
1038 		fm10k_unmap_and_free_tx_resource(tx_ring, tx_buffer);
1039 		if (tx_buffer == first)
1040 			break;
1041 		if (i == 0)
1042 			i = tx_ring->count;
1043 		i--;
1044 	}
1045 
1046 	tx_ring->next_to_use = i;
1047 }
1048 
1049 netdev_tx_t fm10k_xmit_frame_ring(struct sk_buff *skb,
1050 				  struct fm10k_ring *tx_ring)
1051 {
1052 	u16 count = TXD_USE_COUNT(skb_headlen(skb));
1053 	struct fm10k_tx_buffer *first;
1054 	unsigned short f;
1055 	u32 tx_flags = 0;
1056 	int tso;
1057 
1058 	/* need: 1 descriptor per page * PAGE_SIZE/FM10K_MAX_DATA_PER_TXD,
1059 	 *       + 1 desc for skb_headlen/FM10K_MAX_DATA_PER_TXD,
1060 	 *       + 2 desc gap to keep tail from touching head
1061 	 * otherwise try next time
1062 	 */
1063 	for (f = 0; f < skb_shinfo(skb)->nr_frags; f++) {
1064 		skb_frag_t *frag = &skb_shinfo(skb)->frags[f];
1065 
1066 		count += TXD_USE_COUNT(skb_frag_size(frag));
1067 	}
1068 
1069 	if (fm10k_maybe_stop_tx(tx_ring, count + 3)) {
1070 		tx_ring->tx_stats.tx_busy++;
1071 		return NETDEV_TX_BUSY;
1072 	}
1073 
1074 	/* record the location of the first descriptor for this packet */
1075 	first = &tx_ring->tx_buffer[tx_ring->next_to_use];
1076 	first->skb = skb;
1077 	first->bytecount = max_t(unsigned int, skb->len, ETH_ZLEN);
1078 	first->gso_segs = 1;
1079 
1080 	/* record initial flags and protocol */
1081 	first->tx_flags = tx_flags;
1082 
1083 	tso = fm10k_tso(tx_ring, first);
1084 	if (tso < 0)
1085 		goto out_drop;
1086 	else if (!tso)
1087 		fm10k_tx_csum(tx_ring, first);
1088 
1089 	fm10k_tx_map(tx_ring, first);
1090 
1091 	return NETDEV_TX_OK;
1092 
1093 out_drop:
1094 	dev_kfree_skb_any(first->skb);
1095 	first->skb = NULL;
1096 
1097 	return NETDEV_TX_OK;
1098 }
1099 
1100 static u64 fm10k_get_tx_completed(struct fm10k_ring *ring)
1101 {
1102 	return ring->stats.packets;
1103 }
1104 
1105 /**
1106  * fm10k_get_tx_pending - how many Tx descriptors not processed
1107  * @ring: the ring structure
1108  * @in_sw: is tx_pending being checked in SW or in HW?
1109  */
1110 u64 fm10k_get_tx_pending(struct fm10k_ring *ring, bool in_sw)
1111 {
1112 	struct fm10k_intfc *interface = ring->q_vector->interface;
1113 	struct fm10k_hw *hw = &interface->hw;
1114 	u32 head, tail;
1115 
1116 	if (likely(in_sw)) {
1117 		head = ring->next_to_clean;
1118 		tail = ring->next_to_use;
1119 	} else {
1120 		head = fm10k_read_reg(hw, FM10K_TDH(ring->reg_idx));
1121 		tail = fm10k_read_reg(hw, FM10K_TDT(ring->reg_idx));
1122 	}
1123 
1124 	return ((head <= tail) ? tail : tail + ring->count) - head;
1125 }
1126 
1127 bool fm10k_check_tx_hang(struct fm10k_ring *tx_ring)
1128 {
1129 	u32 tx_done = fm10k_get_tx_completed(tx_ring);
1130 	u32 tx_done_old = tx_ring->tx_stats.tx_done_old;
1131 	u32 tx_pending = fm10k_get_tx_pending(tx_ring, true);
1132 
1133 	clear_check_for_tx_hang(tx_ring);
1134 
1135 	/* Check for a hung queue, but be thorough. This verifies
1136 	 * that a transmit has been completed since the previous
1137 	 * check AND there is at least one packet pending. By
1138 	 * requiring this to fail twice we avoid races with
1139 	 * clearing the ARMED bit and conditions where we
1140 	 * run the check_tx_hang logic with a transmit completion
1141 	 * pending but without time to complete it yet.
1142 	 */
1143 	if (!tx_pending || (tx_done_old != tx_done)) {
1144 		/* update completed stats and continue */
1145 		tx_ring->tx_stats.tx_done_old = tx_done;
1146 		/* reset the countdown */
1147 		clear_bit(__FM10K_HANG_CHECK_ARMED, tx_ring->state);
1148 
1149 		return false;
1150 	}
1151 
1152 	/* make sure it is true for two checks in a row */
1153 	return test_and_set_bit(__FM10K_HANG_CHECK_ARMED, tx_ring->state);
1154 }
1155 
1156 /**
1157  * fm10k_tx_timeout_reset - initiate reset due to Tx timeout
1158  * @interface: driver private struct
1159  **/
1160 void fm10k_tx_timeout_reset(struct fm10k_intfc *interface)
1161 {
1162 	/* Do the reset outside of interrupt context */
1163 	if (!test_bit(__FM10K_DOWN, interface->state)) {
1164 		interface->tx_timeout_count++;
1165 		set_bit(FM10K_FLAG_RESET_REQUESTED, interface->flags);
1166 		fm10k_service_event_schedule(interface);
1167 	}
1168 }
1169 
1170 /**
1171  * fm10k_clean_tx_irq - Reclaim resources after transmit completes
1172  * @q_vector: structure containing interrupt and ring information
1173  * @tx_ring: tx ring to clean
1174  * @napi_budget: Used to determine if we are in netpoll
1175  **/
1176 static bool fm10k_clean_tx_irq(struct fm10k_q_vector *q_vector,
1177 			       struct fm10k_ring *tx_ring, int napi_budget)
1178 {
1179 	struct fm10k_intfc *interface = q_vector->interface;
1180 	struct fm10k_tx_buffer *tx_buffer;
1181 	struct fm10k_tx_desc *tx_desc;
1182 	unsigned int total_bytes = 0, total_packets = 0;
1183 	unsigned int budget = q_vector->tx.work_limit;
1184 	unsigned int i = tx_ring->next_to_clean;
1185 
1186 	if (test_bit(__FM10K_DOWN, interface->state))
1187 		return true;
1188 
1189 	tx_buffer = &tx_ring->tx_buffer[i];
1190 	tx_desc = FM10K_TX_DESC(tx_ring, i);
1191 	i -= tx_ring->count;
1192 
1193 	do {
1194 		struct fm10k_tx_desc *eop_desc = tx_buffer->next_to_watch;
1195 
1196 		/* if next_to_watch is not set then there is no work pending */
1197 		if (!eop_desc)
1198 			break;
1199 
1200 		/* prevent any other reads prior to eop_desc */
1201 		smp_rmb();
1202 
1203 		/* if DD is not set pending work has not been completed */
1204 		if (!(eop_desc->flags & FM10K_TXD_FLAG_DONE))
1205 			break;
1206 
1207 		/* clear next_to_watch to prevent false hangs */
1208 		tx_buffer->next_to_watch = NULL;
1209 
1210 		/* update the statistics for this packet */
1211 		total_bytes += tx_buffer->bytecount;
1212 		total_packets += tx_buffer->gso_segs;
1213 
1214 		/* free the skb */
1215 		napi_consume_skb(tx_buffer->skb, napi_budget);
1216 
1217 		/* unmap skb header data */
1218 		dma_unmap_single(tx_ring->dev,
1219 				 dma_unmap_addr(tx_buffer, dma),
1220 				 dma_unmap_len(tx_buffer, len),
1221 				 DMA_TO_DEVICE);
1222 
1223 		/* clear tx_buffer data */
1224 		tx_buffer->skb = NULL;
1225 		dma_unmap_len_set(tx_buffer, len, 0);
1226 
1227 		/* unmap remaining buffers */
1228 		while (tx_desc != eop_desc) {
1229 			tx_buffer++;
1230 			tx_desc++;
1231 			i++;
1232 			if (unlikely(!i)) {
1233 				i -= tx_ring->count;
1234 				tx_buffer = tx_ring->tx_buffer;
1235 				tx_desc = FM10K_TX_DESC(tx_ring, 0);
1236 			}
1237 
1238 			/* unmap any remaining paged data */
1239 			if (dma_unmap_len(tx_buffer, len)) {
1240 				dma_unmap_page(tx_ring->dev,
1241 					       dma_unmap_addr(tx_buffer, dma),
1242 					       dma_unmap_len(tx_buffer, len),
1243 					       DMA_TO_DEVICE);
1244 				dma_unmap_len_set(tx_buffer, len, 0);
1245 			}
1246 		}
1247 
1248 		/* move us one more past the eop_desc for start of next pkt */
1249 		tx_buffer++;
1250 		tx_desc++;
1251 		i++;
1252 		if (unlikely(!i)) {
1253 			i -= tx_ring->count;
1254 			tx_buffer = tx_ring->tx_buffer;
1255 			tx_desc = FM10K_TX_DESC(tx_ring, 0);
1256 		}
1257 
1258 		/* issue prefetch for next Tx descriptor */
1259 		prefetch(tx_desc);
1260 
1261 		/* update budget accounting */
1262 		budget--;
1263 	} while (likely(budget));
1264 
1265 	i += tx_ring->count;
1266 	tx_ring->next_to_clean = i;
1267 	u64_stats_update_begin(&tx_ring->syncp);
1268 	tx_ring->stats.bytes += total_bytes;
1269 	tx_ring->stats.packets += total_packets;
1270 	u64_stats_update_end(&tx_ring->syncp);
1271 	q_vector->tx.total_bytes += total_bytes;
1272 	q_vector->tx.total_packets += total_packets;
1273 
1274 	if (check_for_tx_hang(tx_ring) && fm10k_check_tx_hang(tx_ring)) {
1275 		/* schedule immediate reset if we believe we hung */
1276 		struct fm10k_hw *hw = &interface->hw;
1277 
1278 		netif_err(interface, drv, tx_ring->netdev,
1279 			  "Detected Tx Unit Hang\n"
1280 			  "  Tx Queue             <%d>\n"
1281 			  "  TDH, TDT             <%x>, <%x>\n"
1282 			  "  next_to_use          <%x>\n"
1283 			  "  next_to_clean        <%x>\n",
1284 			  tx_ring->queue_index,
1285 			  fm10k_read_reg(hw, FM10K_TDH(tx_ring->reg_idx)),
1286 			  fm10k_read_reg(hw, FM10K_TDT(tx_ring->reg_idx)),
1287 			  tx_ring->next_to_use, i);
1288 
1289 		netif_stop_subqueue(tx_ring->netdev,
1290 				    tx_ring->queue_index);
1291 
1292 		netif_info(interface, probe, tx_ring->netdev,
1293 			   "tx hang %d detected on queue %d, resetting interface\n",
1294 			   interface->tx_timeout_count + 1,
1295 			   tx_ring->queue_index);
1296 
1297 		fm10k_tx_timeout_reset(interface);
1298 
1299 		/* the netdev is about to reset, no point in enabling stuff */
1300 		return true;
1301 	}
1302 
1303 	/* notify netdev of completed buffers */
1304 	netdev_tx_completed_queue(txring_txq(tx_ring),
1305 				  total_packets, total_bytes);
1306 
1307 #define TX_WAKE_THRESHOLD min_t(u16, FM10K_MIN_TXD - 1, DESC_NEEDED * 2)
1308 	if (unlikely(total_packets && netif_carrier_ok(tx_ring->netdev) &&
1309 		     (fm10k_desc_unused(tx_ring) >= TX_WAKE_THRESHOLD))) {
1310 		/* Make sure that anybody stopping the queue after this
1311 		 * sees the new next_to_clean.
1312 		 */
1313 		smp_mb();
1314 		if (__netif_subqueue_stopped(tx_ring->netdev,
1315 					     tx_ring->queue_index) &&
1316 		    !test_bit(__FM10K_DOWN, interface->state)) {
1317 			netif_wake_subqueue(tx_ring->netdev,
1318 					    tx_ring->queue_index);
1319 			++tx_ring->tx_stats.restart_queue;
1320 		}
1321 	}
1322 
1323 	return !!budget;
1324 }
1325 
1326 /**
1327  * fm10k_update_itr - update the dynamic ITR value based on packet size
1328  *
1329  *      Stores a new ITR value based on strictly on packet size.  The
1330  *      divisors and thresholds used by this function were determined based
1331  *      on theoretical maximum wire speed and testing data, in order to
1332  *      minimize response time while increasing bulk throughput.
1333  *
1334  * @ring_container: Container for rings to have ITR updated
1335  **/
1336 static void fm10k_update_itr(struct fm10k_ring_container *ring_container)
1337 {
1338 	unsigned int avg_wire_size, packets, itr_round;
1339 
1340 	/* Only update ITR if we are using adaptive setting */
1341 	if (!ITR_IS_ADAPTIVE(ring_container->itr))
1342 		goto clear_counts;
1343 
1344 	packets = ring_container->total_packets;
1345 	if (!packets)
1346 		goto clear_counts;
1347 
1348 	avg_wire_size = ring_container->total_bytes / packets;
1349 
1350 	/* The following is a crude approximation of:
1351 	 *  wmem_default / (size + overhead) = desired_pkts_per_int
1352 	 *  rate / bits_per_byte / (size + ethernet overhead) = pkt_rate
1353 	 *  (desired_pkt_rate / pkt_rate) * usecs_per_sec = ITR value
1354 	 *
1355 	 * Assuming wmem_default is 212992 and overhead is 640 bytes per
1356 	 * packet, (256 skb, 64 headroom, 320 shared info), we can reduce the
1357 	 * formula down to
1358 	 *
1359 	 *  (34 * (size + 24)) / (size + 640) = ITR
1360 	 *
1361 	 * We first do some math on the packet size and then finally bitshift
1362 	 * by 8 after rounding up. We also have to account for PCIe link speed
1363 	 * difference as ITR scales based on this.
1364 	 */
1365 	if (avg_wire_size <= 360) {
1366 		/* Start at 250K ints/sec and gradually drop to 77K ints/sec */
1367 		avg_wire_size *= 8;
1368 		avg_wire_size += 376;
1369 	} else if (avg_wire_size <= 1152) {
1370 		/* 77K ints/sec to 45K ints/sec */
1371 		avg_wire_size *= 3;
1372 		avg_wire_size += 2176;
1373 	} else if (avg_wire_size <= 1920) {
1374 		/* 45K ints/sec to 38K ints/sec */
1375 		avg_wire_size += 4480;
1376 	} else {
1377 		/* plateau at a limit of 38K ints/sec */
1378 		avg_wire_size = 6656;
1379 	}
1380 
1381 	/* Perform final bitshift for division after rounding up to ensure
1382 	 * that the calculation will never get below a 1. The bit shift
1383 	 * accounts for changes in the ITR due to PCIe link speed.
1384 	 */
1385 	itr_round = READ_ONCE(ring_container->itr_scale) + 8;
1386 	avg_wire_size += BIT(itr_round) - 1;
1387 	avg_wire_size >>= itr_round;
1388 
1389 	/* write back value and retain adaptive flag */
1390 	ring_container->itr = avg_wire_size | FM10K_ITR_ADAPTIVE;
1391 
1392 clear_counts:
1393 	ring_container->total_bytes = 0;
1394 	ring_container->total_packets = 0;
1395 }
1396 
1397 static void fm10k_qv_enable(struct fm10k_q_vector *q_vector)
1398 {
1399 	/* Enable auto-mask and clear the current mask */
1400 	u32 itr = FM10K_ITR_ENABLE;
1401 
1402 	/* Update Tx ITR */
1403 	fm10k_update_itr(&q_vector->tx);
1404 
1405 	/* Update Rx ITR */
1406 	fm10k_update_itr(&q_vector->rx);
1407 
1408 	/* Store Tx itr in timer slot 0 */
1409 	itr |= (q_vector->tx.itr & FM10K_ITR_MAX);
1410 
1411 	/* Shift Rx itr to timer slot 1 */
1412 	itr |= (q_vector->rx.itr & FM10K_ITR_MAX) << FM10K_ITR_INTERVAL1_SHIFT;
1413 
1414 	/* Write the final value to the ITR register */
1415 	writel(itr, q_vector->itr);
1416 }
1417 
1418 static int fm10k_poll(struct napi_struct *napi, int budget)
1419 {
1420 	struct fm10k_q_vector *q_vector =
1421 			       container_of(napi, struct fm10k_q_vector, napi);
1422 	struct fm10k_ring *ring;
1423 	int per_ring_budget, work_done = 0;
1424 	bool clean_complete = true;
1425 
1426 	fm10k_for_each_ring(ring, q_vector->tx) {
1427 		if (!fm10k_clean_tx_irq(q_vector, ring, budget))
1428 			clean_complete = false;
1429 	}
1430 
1431 	/* Handle case where we are called by netpoll with a budget of 0 */
1432 	if (budget <= 0)
1433 		return budget;
1434 
1435 	/* attempt to distribute budget to each queue fairly, but don't
1436 	 * allow the budget to go below 1 because we'll exit polling
1437 	 */
1438 	if (q_vector->rx.count > 1)
1439 		per_ring_budget = max(budget / q_vector->rx.count, 1);
1440 	else
1441 		per_ring_budget = budget;
1442 
1443 	fm10k_for_each_ring(ring, q_vector->rx) {
1444 		int work = fm10k_clean_rx_irq(q_vector, ring, per_ring_budget);
1445 
1446 		work_done += work;
1447 		if (work >= per_ring_budget)
1448 			clean_complete = false;
1449 	}
1450 
1451 	/* If all work not completed, return budget and keep polling */
1452 	if (!clean_complete)
1453 		return budget;
1454 
1455 	/* Exit the polling mode, but don't re-enable interrupts if stack might
1456 	 * poll us due to busy-polling
1457 	 */
1458 	if (likely(napi_complete_done(napi, work_done)))
1459 		fm10k_qv_enable(q_vector);
1460 
1461 	return min(work_done, budget - 1);
1462 }
1463 
1464 /**
1465  * fm10k_set_qos_queues: Allocate queues for a QOS-enabled device
1466  * @interface: board private structure to initialize
1467  *
1468  * When QoS (Quality of Service) is enabled, allocate queues for
1469  * each traffic class.  If multiqueue isn't available,then abort QoS
1470  * initialization.
1471  *
1472  * This function handles all combinations of Qos and RSS.
1473  *
1474  **/
1475 static bool fm10k_set_qos_queues(struct fm10k_intfc *interface)
1476 {
1477 	struct net_device *dev = interface->netdev;
1478 	struct fm10k_ring_feature *f;
1479 	int rss_i, i;
1480 	int pcs;
1481 
1482 	/* Map queue offset and counts onto allocated tx queues */
1483 	pcs = netdev_get_num_tc(dev);
1484 
1485 	if (pcs <= 1)
1486 		return false;
1487 
1488 	/* set QoS mask and indices */
1489 	f = &interface->ring_feature[RING_F_QOS];
1490 	f->indices = pcs;
1491 	f->mask = BIT(fls(pcs - 1)) - 1;
1492 
1493 	/* determine the upper limit for our current DCB mode */
1494 	rss_i = interface->hw.mac.max_queues / pcs;
1495 	rss_i = BIT(fls(rss_i) - 1);
1496 
1497 	/* set RSS mask and indices */
1498 	f = &interface->ring_feature[RING_F_RSS];
1499 	rss_i = min_t(u16, rss_i, f->limit);
1500 	f->indices = rss_i;
1501 	f->mask = BIT(fls(rss_i - 1)) - 1;
1502 
1503 	/* configure pause class to queue mapping */
1504 	for (i = 0; i < pcs; i++)
1505 		netdev_set_tc_queue(dev, i, rss_i, rss_i * i);
1506 
1507 	interface->num_rx_queues = rss_i * pcs;
1508 	interface->num_tx_queues = rss_i * pcs;
1509 
1510 	return true;
1511 }
1512 
1513 /**
1514  * fm10k_set_rss_queues: Allocate queues for RSS
1515  * @interface: board private structure to initialize
1516  *
1517  * This is our "base" multiqueue mode.  RSS (Receive Side Scaling) will try
1518  * to allocate one Rx queue per CPU, and if available, one Tx queue per CPU.
1519  *
1520  **/
1521 static bool fm10k_set_rss_queues(struct fm10k_intfc *interface)
1522 {
1523 	struct fm10k_ring_feature *f;
1524 	u16 rss_i;
1525 
1526 	f = &interface->ring_feature[RING_F_RSS];
1527 	rss_i = min_t(u16, interface->hw.mac.max_queues, f->limit);
1528 
1529 	/* record indices and power of 2 mask for RSS */
1530 	f->indices = rss_i;
1531 	f->mask = BIT(fls(rss_i - 1)) - 1;
1532 
1533 	interface->num_rx_queues = rss_i;
1534 	interface->num_tx_queues = rss_i;
1535 
1536 	return true;
1537 }
1538 
1539 /**
1540  * fm10k_set_num_queues: Allocate queues for device, feature dependent
1541  * @interface: board private structure to initialize
1542  *
1543  * This is the top level queue allocation routine.  The order here is very
1544  * important, starting with the "most" number of features turned on at once,
1545  * and ending with the smallest set of features.  This way large combinations
1546  * can be allocated if they're turned on, and smaller combinations are the
1547  * fall through conditions.
1548  *
1549  **/
1550 static void fm10k_set_num_queues(struct fm10k_intfc *interface)
1551 {
1552 	/* Attempt to setup QoS and RSS first */
1553 	if (fm10k_set_qos_queues(interface))
1554 		return;
1555 
1556 	/* If we don't have QoS, just fallback to only RSS. */
1557 	fm10k_set_rss_queues(interface);
1558 }
1559 
1560 /**
1561  * fm10k_reset_num_queues - Reset the number of queues to zero
1562  * @interface: board private structure
1563  *
1564  * This function should be called whenever we need to reset the number of
1565  * queues after an error condition.
1566  */
1567 static void fm10k_reset_num_queues(struct fm10k_intfc *interface)
1568 {
1569 	interface->num_tx_queues = 0;
1570 	interface->num_rx_queues = 0;
1571 	interface->num_q_vectors = 0;
1572 }
1573 
1574 /**
1575  * fm10k_alloc_q_vector - Allocate memory for a single interrupt vector
1576  * @interface: board private structure to initialize
1577  * @v_count: q_vectors allocated on interface, used for ring interleaving
1578  * @v_idx: index of vector in interface struct
1579  * @txr_count: total number of Tx rings to allocate
1580  * @txr_idx: index of first Tx ring to allocate
1581  * @rxr_count: total number of Rx rings to allocate
1582  * @rxr_idx: index of first Rx ring to allocate
1583  *
1584  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
1585  **/
1586 static int fm10k_alloc_q_vector(struct fm10k_intfc *interface,
1587 				unsigned int v_count, unsigned int v_idx,
1588 				unsigned int txr_count, unsigned int txr_idx,
1589 				unsigned int rxr_count, unsigned int rxr_idx)
1590 {
1591 	struct fm10k_q_vector *q_vector;
1592 	struct fm10k_ring *ring;
1593 	int ring_count;
1594 
1595 	ring_count = txr_count + rxr_count;
1596 
1597 	/* allocate q_vector and rings */
1598 	q_vector = kzalloc(struct_size(q_vector, ring, ring_count), GFP_KERNEL);
1599 	if (!q_vector)
1600 		return -ENOMEM;
1601 
1602 	/* initialize NAPI */
1603 	netif_napi_add(interface->netdev, &q_vector->napi,
1604 		       fm10k_poll, NAPI_POLL_WEIGHT);
1605 
1606 	/* tie q_vector and interface together */
1607 	interface->q_vector[v_idx] = q_vector;
1608 	q_vector->interface = interface;
1609 	q_vector->v_idx = v_idx;
1610 
1611 	/* initialize pointer to rings */
1612 	ring = q_vector->ring;
1613 
1614 	/* save Tx ring container info */
1615 	q_vector->tx.ring = ring;
1616 	q_vector->tx.work_limit = FM10K_DEFAULT_TX_WORK;
1617 	q_vector->tx.itr = interface->tx_itr;
1618 	q_vector->tx.itr_scale = interface->hw.mac.itr_scale;
1619 	q_vector->tx.count = txr_count;
1620 
1621 	while (txr_count) {
1622 		/* assign generic ring traits */
1623 		ring->dev = &interface->pdev->dev;
1624 		ring->netdev = interface->netdev;
1625 
1626 		/* configure backlink on ring */
1627 		ring->q_vector = q_vector;
1628 
1629 		/* apply Tx specific ring traits */
1630 		ring->count = interface->tx_ring_count;
1631 		ring->queue_index = txr_idx;
1632 
1633 		/* assign ring to interface */
1634 		interface->tx_ring[txr_idx] = ring;
1635 
1636 		/* update count and index */
1637 		txr_count--;
1638 		txr_idx += v_count;
1639 
1640 		/* push pointer to next ring */
1641 		ring++;
1642 	}
1643 
1644 	/* save Rx ring container info */
1645 	q_vector->rx.ring = ring;
1646 	q_vector->rx.itr = interface->rx_itr;
1647 	q_vector->rx.itr_scale = interface->hw.mac.itr_scale;
1648 	q_vector->rx.count = rxr_count;
1649 
1650 	while (rxr_count) {
1651 		/* assign generic ring traits */
1652 		ring->dev = &interface->pdev->dev;
1653 		ring->netdev = interface->netdev;
1654 		rcu_assign_pointer(ring->l2_accel, interface->l2_accel);
1655 
1656 		/* configure backlink on ring */
1657 		ring->q_vector = q_vector;
1658 
1659 		/* apply Rx specific ring traits */
1660 		ring->count = interface->rx_ring_count;
1661 		ring->queue_index = rxr_idx;
1662 
1663 		/* assign ring to interface */
1664 		interface->rx_ring[rxr_idx] = ring;
1665 
1666 		/* update count and index */
1667 		rxr_count--;
1668 		rxr_idx += v_count;
1669 
1670 		/* push pointer to next ring */
1671 		ring++;
1672 	}
1673 
1674 	fm10k_dbg_q_vector_init(q_vector);
1675 
1676 	return 0;
1677 }
1678 
1679 /**
1680  * fm10k_free_q_vector - Free memory allocated for specific interrupt vector
1681  * @interface: board private structure to initialize
1682  * @v_idx: Index of vector to be freed
1683  *
1684  * This function frees the memory allocated to the q_vector.  In addition if
1685  * NAPI is enabled it will delete any references to the NAPI struct prior
1686  * to freeing the q_vector.
1687  **/
1688 static void fm10k_free_q_vector(struct fm10k_intfc *interface, int v_idx)
1689 {
1690 	struct fm10k_q_vector *q_vector = interface->q_vector[v_idx];
1691 	struct fm10k_ring *ring;
1692 
1693 	fm10k_dbg_q_vector_exit(q_vector);
1694 
1695 	fm10k_for_each_ring(ring, q_vector->tx)
1696 		interface->tx_ring[ring->queue_index] = NULL;
1697 
1698 	fm10k_for_each_ring(ring, q_vector->rx)
1699 		interface->rx_ring[ring->queue_index] = NULL;
1700 
1701 	interface->q_vector[v_idx] = NULL;
1702 	netif_napi_del(&q_vector->napi);
1703 	kfree_rcu(q_vector, rcu);
1704 }
1705 
1706 /**
1707  * fm10k_alloc_q_vectors - Allocate memory for interrupt vectors
1708  * @interface: board private structure to initialize
1709  *
1710  * We allocate one q_vector per queue interrupt.  If allocation fails we
1711  * return -ENOMEM.
1712  **/
1713 static int fm10k_alloc_q_vectors(struct fm10k_intfc *interface)
1714 {
1715 	unsigned int q_vectors = interface->num_q_vectors;
1716 	unsigned int rxr_remaining = interface->num_rx_queues;
1717 	unsigned int txr_remaining = interface->num_tx_queues;
1718 	unsigned int rxr_idx = 0, txr_idx = 0, v_idx = 0;
1719 	int err;
1720 
1721 	if (q_vectors >= (rxr_remaining + txr_remaining)) {
1722 		for (; rxr_remaining; v_idx++) {
1723 			err = fm10k_alloc_q_vector(interface, q_vectors, v_idx,
1724 						   0, 0, 1, rxr_idx);
1725 			if (err)
1726 				goto err_out;
1727 
1728 			/* update counts and index */
1729 			rxr_remaining--;
1730 			rxr_idx++;
1731 		}
1732 	}
1733 
1734 	for (; v_idx < q_vectors; v_idx++) {
1735 		int rqpv = DIV_ROUND_UP(rxr_remaining, q_vectors - v_idx);
1736 		int tqpv = DIV_ROUND_UP(txr_remaining, q_vectors - v_idx);
1737 
1738 		err = fm10k_alloc_q_vector(interface, q_vectors, v_idx,
1739 					   tqpv, txr_idx,
1740 					   rqpv, rxr_idx);
1741 
1742 		if (err)
1743 			goto err_out;
1744 
1745 		/* update counts and index */
1746 		rxr_remaining -= rqpv;
1747 		txr_remaining -= tqpv;
1748 		rxr_idx++;
1749 		txr_idx++;
1750 	}
1751 
1752 	return 0;
1753 
1754 err_out:
1755 	fm10k_reset_num_queues(interface);
1756 
1757 	while (v_idx--)
1758 		fm10k_free_q_vector(interface, v_idx);
1759 
1760 	return -ENOMEM;
1761 }
1762 
1763 /**
1764  * fm10k_free_q_vectors - Free memory allocated for interrupt vectors
1765  * @interface: board private structure to initialize
1766  *
1767  * This function frees the memory allocated to the q_vectors.  In addition if
1768  * NAPI is enabled it will delete any references to the NAPI struct prior
1769  * to freeing the q_vector.
1770  **/
1771 static void fm10k_free_q_vectors(struct fm10k_intfc *interface)
1772 {
1773 	int v_idx = interface->num_q_vectors;
1774 
1775 	fm10k_reset_num_queues(interface);
1776 
1777 	while (v_idx--)
1778 		fm10k_free_q_vector(interface, v_idx);
1779 }
1780 
1781 /**
1782  * f10k_reset_msix_capability - reset MSI-X capability
1783  * @interface: board private structure to initialize
1784  *
1785  * Reset the MSI-X capability back to its starting state
1786  **/
1787 static void fm10k_reset_msix_capability(struct fm10k_intfc *interface)
1788 {
1789 	pci_disable_msix(interface->pdev);
1790 	kfree(interface->msix_entries);
1791 	interface->msix_entries = NULL;
1792 }
1793 
1794 /**
1795  * f10k_init_msix_capability - configure MSI-X capability
1796  * @interface: board private structure to initialize
1797  *
1798  * Attempt to configure the interrupts using the best available
1799  * capabilities of the hardware and the kernel.
1800  **/
1801 static int fm10k_init_msix_capability(struct fm10k_intfc *interface)
1802 {
1803 	struct fm10k_hw *hw = &interface->hw;
1804 	int v_budget, vector;
1805 
1806 	/* It's easy to be greedy for MSI-X vectors, but it really
1807 	 * doesn't do us much good if we have a lot more vectors
1808 	 * than CPU's.  So let's be conservative and only ask for
1809 	 * (roughly) the same number of vectors as there are CPU's.
1810 	 * the default is to use pairs of vectors
1811 	 */
1812 	v_budget = max(interface->num_rx_queues, interface->num_tx_queues);
1813 	v_budget = min_t(u16, v_budget, num_online_cpus());
1814 
1815 	/* account for vectors not related to queues */
1816 	v_budget += NON_Q_VECTORS;
1817 
1818 	/* At the same time, hardware can only support a maximum of
1819 	 * hw.mac->max_msix_vectors vectors.  With features
1820 	 * such as RSS and VMDq, we can easily surpass the number of Rx and Tx
1821 	 * descriptor queues supported by our device.  Thus, we cap it off in
1822 	 * those rare cases where the cpu count also exceeds our vector limit.
1823 	 */
1824 	v_budget = min_t(int, v_budget, hw->mac.max_msix_vectors);
1825 
1826 	/* A failure in MSI-X entry allocation is fatal. */
1827 	interface->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
1828 					  GFP_KERNEL);
1829 	if (!interface->msix_entries)
1830 		return -ENOMEM;
1831 
1832 	/* populate entry values */
1833 	for (vector = 0; vector < v_budget; vector++)
1834 		interface->msix_entries[vector].entry = vector;
1835 
1836 	/* Attempt to enable MSI-X with requested value */
1837 	v_budget = pci_enable_msix_range(interface->pdev,
1838 					 interface->msix_entries,
1839 					 MIN_MSIX_COUNT(hw),
1840 					 v_budget);
1841 	if (v_budget < 0) {
1842 		kfree(interface->msix_entries);
1843 		interface->msix_entries = NULL;
1844 		return v_budget;
1845 	}
1846 
1847 	/* record the number of queues available for q_vectors */
1848 	interface->num_q_vectors = v_budget - NON_Q_VECTORS;
1849 
1850 	return 0;
1851 }
1852 
1853 /**
1854  * fm10k_cache_ring_qos - Descriptor ring to register mapping for QoS
1855  * @interface: Interface structure continaining rings and devices
1856  *
1857  * Cache the descriptor ring offsets for Qos
1858  **/
1859 static bool fm10k_cache_ring_qos(struct fm10k_intfc *interface)
1860 {
1861 	struct net_device *dev = interface->netdev;
1862 	int pc, offset, rss_i, i;
1863 	u16 pc_stride = interface->ring_feature[RING_F_QOS].mask + 1;
1864 	u8 num_pcs = netdev_get_num_tc(dev);
1865 
1866 	if (num_pcs <= 1)
1867 		return false;
1868 
1869 	rss_i = interface->ring_feature[RING_F_RSS].indices;
1870 
1871 	for (pc = 0, offset = 0; pc < num_pcs; pc++, offset += rss_i) {
1872 		int q_idx = pc;
1873 
1874 		for (i = 0; i < rss_i; i++) {
1875 			interface->tx_ring[offset + i]->reg_idx = q_idx;
1876 			interface->tx_ring[offset + i]->qos_pc = pc;
1877 			interface->rx_ring[offset + i]->reg_idx = q_idx;
1878 			interface->rx_ring[offset + i]->qos_pc = pc;
1879 			q_idx += pc_stride;
1880 		}
1881 	}
1882 
1883 	return true;
1884 }
1885 
1886 /**
1887  * fm10k_cache_ring_rss - Descriptor ring to register mapping for RSS
1888  * @interface: Interface structure continaining rings and devices
1889  *
1890  * Cache the descriptor ring offsets for RSS
1891  **/
1892 static void fm10k_cache_ring_rss(struct fm10k_intfc *interface)
1893 {
1894 	int i;
1895 
1896 	for (i = 0; i < interface->num_rx_queues; i++)
1897 		interface->rx_ring[i]->reg_idx = i;
1898 
1899 	for (i = 0; i < interface->num_tx_queues; i++)
1900 		interface->tx_ring[i]->reg_idx = i;
1901 }
1902 
1903 /**
1904  * fm10k_assign_rings - Map rings to network devices
1905  * @interface: Interface structure containing rings and devices
1906  *
1907  * This function is meant to go though and configure both the network
1908  * devices so that they contain rings, and configure the rings so that
1909  * they function with their network devices.
1910  **/
1911 static void fm10k_assign_rings(struct fm10k_intfc *interface)
1912 {
1913 	if (fm10k_cache_ring_qos(interface))
1914 		return;
1915 
1916 	fm10k_cache_ring_rss(interface);
1917 }
1918 
1919 static void fm10k_init_reta(struct fm10k_intfc *interface)
1920 {
1921 	u16 i, rss_i = interface->ring_feature[RING_F_RSS].indices;
1922 	u32 reta;
1923 
1924 	/* If the Rx flow indirection table has been configured manually, we
1925 	 * need to maintain it when possible.
1926 	 */
1927 	if (netif_is_rxfh_configured(interface->netdev)) {
1928 		for (i = FM10K_RETA_SIZE; i--;) {
1929 			reta = interface->reta[i];
1930 			if ((((reta << 24) >> 24) < rss_i) &&
1931 			    (((reta << 16) >> 24) < rss_i) &&
1932 			    (((reta <<  8) >> 24) < rss_i) &&
1933 			    (((reta)       >> 24) < rss_i))
1934 				continue;
1935 
1936 			/* this should never happen */
1937 			dev_err(&interface->pdev->dev,
1938 				"RSS indirection table assigned flows out of queue bounds. Reconfiguring.\n");
1939 			goto repopulate_reta;
1940 		}
1941 
1942 		/* do nothing if all of the elements are in bounds */
1943 		return;
1944 	}
1945 
1946 repopulate_reta:
1947 	fm10k_write_reta(interface, NULL);
1948 }
1949 
1950 /**
1951  * fm10k_init_queueing_scheme - Determine proper queueing scheme
1952  * @interface: board private structure to initialize
1953  *
1954  * We determine which queueing scheme to use based on...
1955  * - Hardware queue count (num_*_queues)
1956  *   - defined by miscellaneous hardware support/features (RSS, etc.)
1957  **/
1958 int fm10k_init_queueing_scheme(struct fm10k_intfc *interface)
1959 {
1960 	int err;
1961 
1962 	/* Number of supported queues */
1963 	fm10k_set_num_queues(interface);
1964 
1965 	/* Configure MSI-X capability */
1966 	err = fm10k_init_msix_capability(interface);
1967 	if (err) {
1968 		dev_err(&interface->pdev->dev,
1969 			"Unable to initialize MSI-X capability\n");
1970 		goto err_init_msix;
1971 	}
1972 
1973 	/* Allocate memory for queues */
1974 	err = fm10k_alloc_q_vectors(interface);
1975 	if (err) {
1976 		dev_err(&interface->pdev->dev,
1977 			"Unable to allocate queue vectors\n");
1978 		goto err_alloc_q_vectors;
1979 	}
1980 
1981 	/* Map rings to devices, and map devices to physical queues */
1982 	fm10k_assign_rings(interface);
1983 
1984 	/* Initialize RSS redirection table */
1985 	fm10k_init_reta(interface);
1986 
1987 	return 0;
1988 
1989 err_alloc_q_vectors:
1990 	fm10k_reset_msix_capability(interface);
1991 err_init_msix:
1992 	fm10k_reset_num_queues(interface);
1993 	return err;
1994 }
1995 
1996 /**
1997  * fm10k_clear_queueing_scheme - Clear the current queueing scheme settings
1998  * @interface: board private structure to clear queueing scheme on
1999  *
2000  * We go through and clear queueing specific resources and reset the structure
2001  * to pre-load conditions
2002  **/
2003 void fm10k_clear_queueing_scheme(struct fm10k_intfc *interface)
2004 {
2005 	fm10k_free_q_vectors(interface);
2006 	fm10k_reset_msix_capability(interface);
2007 }
2008