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