xref: /linux/drivers/net/ethernet/intel/iavf/iavf_txrx.c (revision 860a9bed265146b10311bcadbbcef59c3af4454d)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2013 - 2018 Intel Corporation. */
3 
4 #include <linux/bitfield.h>
5 #include <linux/prefetch.h>
6 
7 #include "iavf.h"
8 #include "iavf_trace.h"
9 #include "iavf_prototype.h"
10 
11 static __le64 build_ctob(u32 td_cmd, u32 td_offset, unsigned int size,
12 			 u32 td_tag)
13 {
14 	return cpu_to_le64(IAVF_TX_DESC_DTYPE_DATA |
15 			   ((u64)td_cmd  << IAVF_TXD_QW1_CMD_SHIFT) |
16 			   ((u64)td_offset << IAVF_TXD_QW1_OFFSET_SHIFT) |
17 			   ((u64)size  << IAVF_TXD_QW1_TX_BUF_SZ_SHIFT) |
18 			   ((u64)td_tag  << IAVF_TXD_QW1_L2TAG1_SHIFT));
19 }
20 
21 #define IAVF_TXD_CMD (IAVF_TX_DESC_CMD_EOP | IAVF_TX_DESC_CMD_RS)
22 
23 /**
24  * iavf_unmap_and_free_tx_resource - Release a Tx buffer
25  * @ring:      the ring that owns the buffer
26  * @tx_buffer: the buffer to free
27  **/
28 static void iavf_unmap_and_free_tx_resource(struct iavf_ring *ring,
29 					    struct iavf_tx_buffer *tx_buffer)
30 {
31 	if (tx_buffer->skb) {
32 		if (tx_buffer->tx_flags & IAVF_TX_FLAGS_FD_SB)
33 			kfree(tx_buffer->raw_buf);
34 		else
35 			dev_kfree_skb_any(tx_buffer->skb);
36 		if (dma_unmap_len(tx_buffer, len))
37 			dma_unmap_single(ring->dev,
38 					 dma_unmap_addr(tx_buffer, dma),
39 					 dma_unmap_len(tx_buffer, len),
40 					 DMA_TO_DEVICE);
41 	} else if (dma_unmap_len(tx_buffer, len)) {
42 		dma_unmap_page(ring->dev,
43 			       dma_unmap_addr(tx_buffer, dma),
44 			       dma_unmap_len(tx_buffer, len),
45 			       DMA_TO_DEVICE);
46 	}
47 
48 	tx_buffer->next_to_watch = NULL;
49 	tx_buffer->skb = NULL;
50 	dma_unmap_len_set(tx_buffer, len, 0);
51 	/* tx_buffer must be completely set up in the transmit path */
52 }
53 
54 /**
55  * iavf_clean_tx_ring - Free any empty Tx buffers
56  * @tx_ring: ring to be cleaned
57  **/
58 static void iavf_clean_tx_ring(struct iavf_ring *tx_ring)
59 {
60 	unsigned long bi_size;
61 	u16 i;
62 
63 	/* ring already cleared, nothing to do */
64 	if (!tx_ring->tx_bi)
65 		return;
66 
67 	/* Free all the Tx ring sk_buffs */
68 	for (i = 0; i < tx_ring->count; i++)
69 		iavf_unmap_and_free_tx_resource(tx_ring, &tx_ring->tx_bi[i]);
70 
71 	bi_size = sizeof(struct iavf_tx_buffer) * tx_ring->count;
72 	memset(tx_ring->tx_bi, 0, bi_size);
73 
74 	/* Zero out the descriptor ring */
75 	memset(tx_ring->desc, 0, tx_ring->size);
76 
77 	tx_ring->next_to_use = 0;
78 	tx_ring->next_to_clean = 0;
79 
80 	if (!tx_ring->netdev)
81 		return;
82 
83 	/* cleanup Tx queue statistics */
84 	netdev_tx_reset_queue(txring_txq(tx_ring));
85 }
86 
87 /**
88  * iavf_free_tx_resources - Free Tx resources per queue
89  * @tx_ring: Tx descriptor ring for a specific queue
90  *
91  * Free all transmit software resources
92  **/
93 void iavf_free_tx_resources(struct iavf_ring *tx_ring)
94 {
95 	iavf_clean_tx_ring(tx_ring);
96 	kfree(tx_ring->tx_bi);
97 	tx_ring->tx_bi = NULL;
98 
99 	if (tx_ring->desc) {
100 		dma_free_coherent(tx_ring->dev, tx_ring->size,
101 				  tx_ring->desc, tx_ring->dma);
102 		tx_ring->desc = NULL;
103 	}
104 }
105 
106 /**
107  * iavf_get_tx_pending - how many Tx descriptors not processed
108  * @ring: the ring of descriptors
109  * @in_sw: is tx_pending being checked in SW or HW
110  *
111  * Since there is no access to the ring head register
112  * in XL710, we need to use our local copies
113  **/
114 static u32 iavf_get_tx_pending(struct iavf_ring *ring, bool in_sw)
115 {
116 	u32 head, tail;
117 
118 	/* underlying hardware might not allow access and/or always return
119 	 * 0 for the head/tail registers so just use the cached values
120 	 */
121 	head = ring->next_to_clean;
122 	tail = ring->next_to_use;
123 
124 	if (head != tail)
125 		return (head < tail) ?
126 			tail - head : (tail + ring->count - head);
127 
128 	return 0;
129 }
130 
131 /**
132  * iavf_force_wb - Issue SW Interrupt so HW does a wb
133  * @vsi: the VSI we care about
134  * @q_vector: the vector on which to force writeback
135  **/
136 static void iavf_force_wb(struct iavf_vsi *vsi, struct iavf_q_vector *q_vector)
137 {
138 	u32 val = IAVF_VFINT_DYN_CTLN1_INTENA_MASK |
139 		  IAVF_VFINT_DYN_CTLN1_ITR_INDX_MASK | /* set noitr */
140 		  IAVF_VFINT_DYN_CTLN1_SWINT_TRIG_MASK |
141 		  IAVF_VFINT_DYN_CTLN1_SW_ITR_INDX_ENA_MASK
142 		  /* allow 00 to be written to the index */;
143 
144 	wr32(&vsi->back->hw,
145 	     IAVF_VFINT_DYN_CTLN1(q_vector->reg_idx),
146 	     val);
147 }
148 
149 /**
150  * iavf_detect_recover_hung - Function to detect and recover hung_queues
151  * @vsi:  pointer to vsi struct with tx queues
152  *
153  * VSI has netdev and netdev has TX queues. This function is to check each of
154  * those TX queues if they are hung, trigger recovery by issuing SW interrupt.
155  **/
156 void iavf_detect_recover_hung(struct iavf_vsi *vsi)
157 {
158 	struct iavf_ring *tx_ring = NULL;
159 	struct net_device *netdev;
160 	unsigned int i;
161 	int packets;
162 
163 	if (!vsi)
164 		return;
165 
166 	if (test_bit(__IAVF_VSI_DOWN, vsi->state))
167 		return;
168 
169 	netdev = vsi->netdev;
170 	if (!netdev)
171 		return;
172 
173 	if (!netif_carrier_ok(netdev))
174 		return;
175 
176 	for (i = 0; i < vsi->back->num_active_queues; i++) {
177 		tx_ring = &vsi->back->tx_rings[i];
178 		if (tx_ring && tx_ring->desc) {
179 			/* If packet counter has not changed the queue is
180 			 * likely stalled, so force an interrupt for this
181 			 * queue.
182 			 *
183 			 * prev_pkt_ctr would be negative if there was no
184 			 * pending work.
185 			 */
186 			packets = tx_ring->stats.packets & INT_MAX;
187 			if (tx_ring->tx_stats.prev_pkt_ctr == packets) {
188 				iavf_force_wb(vsi, tx_ring->q_vector);
189 				continue;
190 			}
191 
192 			/* Memory barrier between read of packet count and call
193 			 * to iavf_get_tx_pending()
194 			 */
195 			smp_rmb();
196 			tx_ring->tx_stats.prev_pkt_ctr =
197 			  iavf_get_tx_pending(tx_ring, true) ? packets : -1;
198 		}
199 	}
200 }
201 
202 #define WB_STRIDE 4
203 
204 /**
205  * iavf_clean_tx_irq - Reclaim resources after transmit completes
206  * @vsi: the VSI we care about
207  * @tx_ring: Tx ring to clean
208  * @napi_budget: Used to determine if we are in netpoll
209  *
210  * Returns true if there's any budget left (e.g. the clean is finished)
211  **/
212 static bool iavf_clean_tx_irq(struct iavf_vsi *vsi,
213 			      struct iavf_ring *tx_ring, int napi_budget)
214 {
215 	int i = tx_ring->next_to_clean;
216 	struct iavf_tx_buffer *tx_buf;
217 	struct iavf_tx_desc *tx_desc;
218 	unsigned int total_bytes = 0, total_packets = 0;
219 	unsigned int budget = IAVF_DEFAULT_IRQ_WORK;
220 
221 	tx_buf = &tx_ring->tx_bi[i];
222 	tx_desc = IAVF_TX_DESC(tx_ring, i);
223 	i -= tx_ring->count;
224 
225 	do {
226 		struct iavf_tx_desc *eop_desc = tx_buf->next_to_watch;
227 
228 		/* if next_to_watch is not set then there is no work pending */
229 		if (!eop_desc)
230 			break;
231 
232 		/* prevent any other reads prior to eop_desc */
233 		smp_rmb();
234 
235 		iavf_trace(clean_tx_irq, tx_ring, tx_desc, tx_buf);
236 		/* if the descriptor isn't done, no work yet to do */
237 		if (!(eop_desc->cmd_type_offset_bsz &
238 		      cpu_to_le64(IAVF_TX_DESC_DTYPE_DESC_DONE)))
239 			break;
240 
241 		/* clear next_to_watch to prevent false hangs */
242 		tx_buf->next_to_watch = NULL;
243 
244 		/* update the statistics for this packet */
245 		total_bytes += tx_buf->bytecount;
246 		total_packets += tx_buf->gso_segs;
247 
248 		/* free the skb */
249 		napi_consume_skb(tx_buf->skb, napi_budget);
250 
251 		/* unmap skb header data */
252 		dma_unmap_single(tx_ring->dev,
253 				 dma_unmap_addr(tx_buf, dma),
254 				 dma_unmap_len(tx_buf, len),
255 				 DMA_TO_DEVICE);
256 
257 		/* clear tx_buffer data */
258 		tx_buf->skb = NULL;
259 		dma_unmap_len_set(tx_buf, len, 0);
260 
261 		/* unmap remaining buffers */
262 		while (tx_desc != eop_desc) {
263 			iavf_trace(clean_tx_irq_unmap,
264 				   tx_ring, tx_desc, tx_buf);
265 
266 			tx_buf++;
267 			tx_desc++;
268 			i++;
269 			if (unlikely(!i)) {
270 				i -= tx_ring->count;
271 				tx_buf = tx_ring->tx_bi;
272 				tx_desc = IAVF_TX_DESC(tx_ring, 0);
273 			}
274 
275 			/* unmap any remaining paged data */
276 			if (dma_unmap_len(tx_buf, len)) {
277 				dma_unmap_page(tx_ring->dev,
278 					       dma_unmap_addr(tx_buf, dma),
279 					       dma_unmap_len(tx_buf, len),
280 					       DMA_TO_DEVICE);
281 				dma_unmap_len_set(tx_buf, len, 0);
282 			}
283 		}
284 
285 		/* move us one more past the eop_desc for start of next pkt */
286 		tx_buf++;
287 		tx_desc++;
288 		i++;
289 		if (unlikely(!i)) {
290 			i -= tx_ring->count;
291 			tx_buf = tx_ring->tx_bi;
292 			tx_desc = IAVF_TX_DESC(tx_ring, 0);
293 		}
294 
295 		prefetch(tx_desc);
296 
297 		/* update budget accounting */
298 		budget--;
299 	} while (likely(budget));
300 
301 	i += tx_ring->count;
302 	tx_ring->next_to_clean = i;
303 	u64_stats_update_begin(&tx_ring->syncp);
304 	tx_ring->stats.bytes += total_bytes;
305 	tx_ring->stats.packets += total_packets;
306 	u64_stats_update_end(&tx_ring->syncp);
307 	tx_ring->q_vector->tx.total_bytes += total_bytes;
308 	tx_ring->q_vector->tx.total_packets += total_packets;
309 
310 	if (tx_ring->flags & IAVF_TXR_FLAGS_WB_ON_ITR) {
311 		/* check to see if there are < 4 descriptors
312 		 * waiting to be written back, then kick the hardware to force
313 		 * them to be written back in case we stay in NAPI.
314 		 * In this mode on X722 we do not enable Interrupt.
315 		 */
316 		unsigned int j = iavf_get_tx_pending(tx_ring, false);
317 
318 		if (budget &&
319 		    ((j / WB_STRIDE) == 0) && (j > 0) &&
320 		    !test_bit(__IAVF_VSI_DOWN, vsi->state) &&
321 		    (IAVF_DESC_UNUSED(tx_ring) != tx_ring->count))
322 			tx_ring->arm_wb = true;
323 	}
324 
325 	/* notify netdev of completed buffers */
326 	netdev_tx_completed_queue(txring_txq(tx_ring),
327 				  total_packets, total_bytes);
328 
329 #define TX_WAKE_THRESHOLD ((s16)(DESC_NEEDED * 2))
330 	if (unlikely(total_packets && netif_carrier_ok(tx_ring->netdev) &&
331 		     (IAVF_DESC_UNUSED(tx_ring) >= TX_WAKE_THRESHOLD))) {
332 		/* Make sure that anybody stopping the queue after this
333 		 * sees the new next_to_clean.
334 		 */
335 		smp_mb();
336 		if (__netif_subqueue_stopped(tx_ring->netdev,
337 					     tx_ring->queue_index) &&
338 		   !test_bit(__IAVF_VSI_DOWN, vsi->state)) {
339 			netif_wake_subqueue(tx_ring->netdev,
340 					    tx_ring->queue_index);
341 			++tx_ring->tx_stats.restart_queue;
342 		}
343 	}
344 
345 	return !!budget;
346 }
347 
348 /**
349  * iavf_enable_wb_on_itr - Arm hardware to do a wb, interrupts are not enabled
350  * @vsi: the VSI we care about
351  * @q_vector: the vector on which to enable writeback
352  *
353  **/
354 static void iavf_enable_wb_on_itr(struct iavf_vsi *vsi,
355 				  struct iavf_q_vector *q_vector)
356 {
357 	u16 flags = q_vector->tx.ring[0].flags;
358 	u32 val;
359 
360 	if (!(flags & IAVF_TXR_FLAGS_WB_ON_ITR))
361 		return;
362 
363 	if (q_vector->arm_wb_state)
364 		return;
365 
366 	val = IAVF_VFINT_DYN_CTLN1_WB_ON_ITR_MASK |
367 	      IAVF_VFINT_DYN_CTLN1_ITR_INDX_MASK; /* set noitr */
368 
369 	wr32(&vsi->back->hw,
370 	     IAVF_VFINT_DYN_CTLN1(q_vector->reg_idx), val);
371 	q_vector->arm_wb_state = true;
372 }
373 
374 static bool iavf_container_is_rx(struct iavf_q_vector *q_vector,
375 				 struct iavf_ring_container *rc)
376 {
377 	return &q_vector->rx == rc;
378 }
379 
380 #define IAVF_AIM_MULTIPLIER_100G	2560
381 #define IAVF_AIM_MULTIPLIER_50G		1280
382 #define IAVF_AIM_MULTIPLIER_40G		1024
383 #define IAVF_AIM_MULTIPLIER_20G		512
384 #define IAVF_AIM_MULTIPLIER_10G		256
385 #define IAVF_AIM_MULTIPLIER_1G		32
386 
387 static unsigned int iavf_mbps_itr_multiplier(u32 speed_mbps)
388 {
389 	switch (speed_mbps) {
390 	case SPEED_100000:
391 		return IAVF_AIM_MULTIPLIER_100G;
392 	case SPEED_50000:
393 		return IAVF_AIM_MULTIPLIER_50G;
394 	case SPEED_40000:
395 		return IAVF_AIM_MULTIPLIER_40G;
396 	case SPEED_25000:
397 	case SPEED_20000:
398 		return IAVF_AIM_MULTIPLIER_20G;
399 	case SPEED_10000:
400 	default:
401 		return IAVF_AIM_MULTIPLIER_10G;
402 	case SPEED_1000:
403 	case SPEED_100:
404 		return IAVF_AIM_MULTIPLIER_1G;
405 	}
406 }
407 
408 static unsigned int
409 iavf_virtchnl_itr_multiplier(enum virtchnl_link_speed speed_virtchnl)
410 {
411 	switch (speed_virtchnl) {
412 	case VIRTCHNL_LINK_SPEED_40GB:
413 		return IAVF_AIM_MULTIPLIER_40G;
414 	case VIRTCHNL_LINK_SPEED_25GB:
415 	case VIRTCHNL_LINK_SPEED_20GB:
416 		return IAVF_AIM_MULTIPLIER_20G;
417 	case VIRTCHNL_LINK_SPEED_10GB:
418 	default:
419 		return IAVF_AIM_MULTIPLIER_10G;
420 	case VIRTCHNL_LINK_SPEED_1GB:
421 	case VIRTCHNL_LINK_SPEED_100MB:
422 		return IAVF_AIM_MULTIPLIER_1G;
423 	}
424 }
425 
426 static unsigned int iavf_itr_divisor(struct iavf_adapter *adapter)
427 {
428 	if (ADV_LINK_SUPPORT(adapter))
429 		return IAVF_ITR_ADAPTIVE_MIN_INC *
430 			iavf_mbps_itr_multiplier(adapter->link_speed_mbps);
431 	else
432 		return IAVF_ITR_ADAPTIVE_MIN_INC *
433 			iavf_virtchnl_itr_multiplier(adapter->link_speed);
434 }
435 
436 /**
437  * iavf_update_itr - update the dynamic ITR value based on statistics
438  * @q_vector: structure containing interrupt and ring information
439  * @rc: structure containing ring performance data
440  *
441  * Stores a new ITR value based on packets and byte
442  * counts during the last interrupt.  The advantage of per interrupt
443  * computation is faster updates and more accurate ITR for the current
444  * traffic pattern.  Constants in this function were computed
445  * based on theoretical maximum wire speed and thresholds were set based
446  * on testing data as well as attempting to minimize response time
447  * while increasing bulk throughput.
448  **/
449 static void iavf_update_itr(struct iavf_q_vector *q_vector,
450 			    struct iavf_ring_container *rc)
451 {
452 	unsigned int avg_wire_size, packets, bytes, itr;
453 	unsigned long next_update = jiffies;
454 
455 	/* If we don't have any rings just leave ourselves set for maximum
456 	 * possible latency so we take ourselves out of the equation.
457 	 */
458 	if (!rc->ring || !ITR_IS_DYNAMIC(rc->ring->itr_setting))
459 		return;
460 
461 	/* For Rx we want to push the delay up and default to low latency.
462 	 * for Tx we want to pull the delay down and default to high latency.
463 	 */
464 	itr = iavf_container_is_rx(q_vector, rc) ?
465 	      IAVF_ITR_ADAPTIVE_MIN_USECS | IAVF_ITR_ADAPTIVE_LATENCY :
466 	      IAVF_ITR_ADAPTIVE_MAX_USECS | IAVF_ITR_ADAPTIVE_LATENCY;
467 
468 	/* If we didn't update within up to 1 - 2 jiffies we can assume
469 	 * that either packets are coming in so slow there hasn't been
470 	 * any work, or that there is so much work that NAPI is dealing
471 	 * with interrupt moderation and we don't need to do anything.
472 	 */
473 	if (time_after(next_update, rc->next_update))
474 		goto clear_counts;
475 
476 	/* If itr_countdown is set it means we programmed an ITR within
477 	 * the last 4 interrupt cycles. This has a side effect of us
478 	 * potentially firing an early interrupt. In order to work around
479 	 * this we need to throw out any data received for a few
480 	 * interrupts following the update.
481 	 */
482 	if (q_vector->itr_countdown) {
483 		itr = rc->target_itr;
484 		goto clear_counts;
485 	}
486 
487 	packets = rc->total_packets;
488 	bytes = rc->total_bytes;
489 
490 	if (iavf_container_is_rx(q_vector, rc)) {
491 		/* If Rx there are 1 to 4 packets and bytes are less than
492 		 * 9000 assume insufficient data to use bulk rate limiting
493 		 * approach unless Tx is already in bulk rate limiting. We
494 		 * are likely latency driven.
495 		 */
496 		if (packets && packets < 4 && bytes < 9000 &&
497 		    (q_vector->tx.target_itr & IAVF_ITR_ADAPTIVE_LATENCY)) {
498 			itr = IAVF_ITR_ADAPTIVE_LATENCY;
499 			goto adjust_by_size;
500 		}
501 	} else if (packets < 4) {
502 		/* If we have Tx and Rx ITR maxed and Tx ITR is running in
503 		 * bulk mode and we are receiving 4 or fewer packets just
504 		 * reset the ITR_ADAPTIVE_LATENCY bit for latency mode so
505 		 * that the Rx can relax.
506 		 */
507 		if (rc->target_itr == IAVF_ITR_ADAPTIVE_MAX_USECS &&
508 		    (q_vector->rx.target_itr & IAVF_ITR_MASK) ==
509 		     IAVF_ITR_ADAPTIVE_MAX_USECS)
510 			goto clear_counts;
511 	} else if (packets > 32) {
512 		/* If we have processed over 32 packets in a single interrupt
513 		 * for Tx assume we need to switch over to "bulk" mode.
514 		 */
515 		rc->target_itr &= ~IAVF_ITR_ADAPTIVE_LATENCY;
516 	}
517 
518 	/* We have no packets to actually measure against. This means
519 	 * either one of the other queues on this vector is active or
520 	 * we are a Tx queue doing TSO with too high of an interrupt rate.
521 	 *
522 	 * Between 4 and 56 we can assume that our current interrupt delay
523 	 * is only slightly too low. As such we should increase it by a small
524 	 * fixed amount.
525 	 */
526 	if (packets < 56) {
527 		itr = rc->target_itr + IAVF_ITR_ADAPTIVE_MIN_INC;
528 		if ((itr & IAVF_ITR_MASK) > IAVF_ITR_ADAPTIVE_MAX_USECS) {
529 			itr &= IAVF_ITR_ADAPTIVE_LATENCY;
530 			itr += IAVF_ITR_ADAPTIVE_MAX_USECS;
531 		}
532 		goto clear_counts;
533 	}
534 
535 	if (packets <= 256) {
536 		itr = min(q_vector->tx.current_itr, q_vector->rx.current_itr);
537 		itr &= IAVF_ITR_MASK;
538 
539 		/* Between 56 and 112 is our "goldilocks" zone where we are
540 		 * working out "just right". Just report that our current
541 		 * ITR is good for us.
542 		 */
543 		if (packets <= 112)
544 			goto clear_counts;
545 
546 		/* If packet count is 128 or greater we are likely looking
547 		 * at a slight overrun of the delay we want. Try halving
548 		 * our delay to see if that will cut the number of packets
549 		 * in half per interrupt.
550 		 */
551 		itr /= 2;
552 		itr &= IAVF_ITR_MASK;
553 		if (itr < IAVF_ITR_ADAPTIVE_MIN_USECS)
554 			itr = IAVF_ITR_ADAPTIVE_MIN_USECS;
555 
556 		goto clear_counts;
557 	}
558 
559 	/* The paths below assume we are dealing with a bulk ITR since
560 	 * number of packets is greater than 256. We are just going to have
561 	 * to compute a value and try to bring the count under control,
562 	 * though for smaller packet sizes there isn't much we can do as
563 	 * NAPI polling will likely be kicking in sooner rather than later.
564 	 */
565 	itr = IAVF_ITR_ADAPTIVE_BULK;
566 
567 adjust_by_size:
568 	/* If packet counts are 256 or greater we can assume we have a gross
569 	 * overestimation of what the rate should be. Instead of trying to fine
570 	 * tune it just use the formula below to try and dial in an exact value
571 	 * give the current packet size of the frame.
572 	 */
573 	avg_wire_size = bytes / packets;
574 
575 	/* The following is a crude approximation of:
576 	 *  wmem_default / (size + overhead) = desired_pkts_per_int
577 	 *  rate / bits_per_byte / (size + ethernet overhead) = pkt_rate
578 	 *  (desired_pkt_rate / pkt_rate) * usecs_per_sec = ITR value
579 	 *
580 	 * Assuming wmem_default is 212992 and overhead is 640 bytes per
581 	 * packet, (256 skb, 64 headroom, 320 shared info), we can reduce the
582 	 * formula down to
583 	 *
584 	 *  (170 * (size + 24)) / (size + 640) = ITR
585 	 *
586 	 * We first do some math on the packet size and then finally bitshift
587 	 * by 8 after rounding up. We also have to account for PCIe link speed
588 	 * difference as ITR scales based on this.
589 	 */
590 	if (avg_wire_size <= 60) {
591 		/* Start at 250k ints/sec */
592 		avg_wire_size = 4096;
593 	} else if (avg_wire_size <= 380) {
594 		/* 250K ints/sec to 60K ints/sec */
595 		avg_wire_size *= 40;
596 		avg_wire_size += 1696;
597 	} else if (avg_wire_size <= 1084) {
598 		/* 60K ints/sec to 36K ints/sec */
599 		avg_wire_size *= 15;
600 		avg_wire_size += 11452;
601 	} else if (avg_wire_size <= 1980) {
602 		/* 36K ints/sec to 30K ints/sec */
603 		avg_wire_size *= 5;
604 		avg_wire_size += 22420;
605 	} else {
606 		/* plateau at a limit of 30K ints/sec */
607 		avg_wire_size = 32256;
608 	}
609 
610 	/* If we are in low latency mode halve our delay which doubles the
611 	 * rate to somewhere between 100K to 16K ints/sec
612 	 */
613 	if (itr & IAVF_ITR_ADAPTIVE_LATENCY)
614 		avg_wire_size /= 2;
615 
616 	/* Resultant value is 256 times larger than it needs to be. This
617 	 * gives us room to adjust the value as needed to either increase
618 	 * or decrease the value based on link speeds of 10G, 2.5G, 1G, etc.
619 	 *
620 	 * Use addition as we have already recorded the new latency flag
621 	 * for the ITR value.
622 	 */
623 	itr += DIV_ROUND_UP(avg_wire_size,
624 			    iavf_itr_divisor(q_vector->adapter)) *
625 		IAVF_ITR_ADAPTIVE_MIN_INC;
626 
627 	if ((itr & IAVF_ITR_MASK) > IAVF_ITR_ADAPTIVE_MAX_USECS) {
628 		itr &= IAVF_ITR_ADAPTIVE_LATENCY;
629 		itr += IAVF_ITR_ADAPTIVE_MAX_USECS;
630 	}
631 
632 clear_counts:
633 	/* write back value */
634 	rc->target_itr = itr;
635 
636 	/* next update should occur within next jiffy */
637 	rc->next_update = next_update + 1;
638 
639 	rc->total_bytes = 0;
640 	rc->total_packets = 0;
641 }
642 
643 /**
644  * iavf_setup_tx_descriptors - Allocate the Tx descriptors
645  * @tx_ring: the tx ring to set up
646  *
647  * Return 0 on success, negative on error
648  **/
649 int iavf_setup_tx_descriptors(struct iavf_ring *tx_ring)
650 {
651 	struct device *dev = tx_ring->dev;
652 	int bi_size;
653 
654 	if (!dev)
655 		return -ENOMEM;
656 
657 	/* warn if we are about to overwrite the pointer */
658 	WARN_ON(tx_ring->tx_bi);
659 	bi_size = sizeof(struct iavf_tx_buffer) * tx_ring->count;
660 	tx_ring->tx_bi = kzalloc(bi_size, GFP_KERNEL);
661 	if (!tx_ring->tx_bi)
662 		goto err;
663 
664 	/* round up to nearest 4K */
665 	tx_ring->size = tx_ring->count * sizeof(struct iavf_tx_desc);
666 	tx_ring->size = ALIGN(tx_ring->size, 4096);
667 	tx_ring->desc = dma_alloc_coherent(dev, tx_ring->size,
668 					   &tx_ring->dma, GFP_KERNEL);
669 	if (!tx_ring->desc) {
670 		dev_info(dev, "Unable to allocate memory for the Tx descriptor ring, size=%d\n",
671 			 tx_ring->size);
672 		goto err;
673 	}
674 
675 	tx_ring->next_to_use = 0;
676 	tx_ring->next_to_clean = 0;
677 	tx_ring->tx_stats.prev_pkt_ctr = -1;
678 	return 0;
679 
680 err:
681 	kfree(tx_ring->tx_bi);
682 	tx_ring->tx_bi = NULL;
683 	return -ENOMEM;
684 }
685 
686 /**
687  * iavf_clean_rx_ring - Free Rx buffers
688  * @rx_ring: ring to be cleaned
689  **/
690 static void iavf_clean_rx_ring(struct iavf_ring *rx_ring)
691 {
692 	unsigned long bi_size;
693 	u16 i;
694 
695 	/* ring already cleared, nothing to do */
696 	if (!rx_ring->rx_bi)
697 		return;
698 
699 	if (rx_ring->skb) {
700 		dev_kfree_skb(rx_ring->skb);
701 		rx_ring->skb = NULL;
702 	}
703 
704 	/* Free all the Rx ring sk_buffs */
705 	for (i = 0; i < rx_ring->count; i++) {
706 		struct iavf_rx_buffer *rx_bi = &rx_ring->rx_bi[i];
707 
708 		if (!rx_bi->page)
709 			continue;
710 
711 		/* Invalidate cache lines that may have been written to by
712 		 * device so that we avoid corrupting memory.
713 		 */
714 		dma_sync_single_range_for_cpu(rx_ring->dev,
715 					      rx_bi->dma,
716 					      rx_bi->page_offset,
717 					      rx_ring->rx_buf_len,
718 					      DMA_FROM_DEVICE);
719 
720 		/* free resources associated with mapping */
721 		dma_unmap_page_attrs(rx_ring->dev, rx_bi->dma,
722 				     iavf_rx_pg_size(rx_ring),
723 				     DMA_FROM_DEVICE,
724 				     IAVF_RX_DMA_ATTR);
725 
726 		__page_frag_cache_drain(rx_bi->page, rx_bi->pagecnt_bias);
727 
728 		rx_bi->page = NULL;
729 		rx_bi->page_offset = 0;
730 	}
731 
732 	bi_size = sizeof(struct iavf_rx_buffer) * rx_ring->count;
733 	memset(rx_ring->rx_bi, 0, bi_size);
734 
735 	/* Zero out the descriptor ring */
736 	memset(rx_ring->desc, 0, rx_ring->size);
737 
738 	rx_ring->next_to_alloc = 0;
739 	rx_ring->next_to_clean = 0;
740 	rx_ring->next_to_use = 0;
741 }
742 
743 /**
744  * iavf_free_rx_resources - Free Rx resources
745  * @rx_ring: ring to clean the resources from
746  *
747  * Free all receive software resources
748  **/
749 void iavf_free_rx_resources(struct iavf_ring *rx_ring)
750 {
751 	iavf_clean_rx_ring(rx_ring);
752 	kfree(rx_ring->rx_bi);
753 	rx_ring->rx_bi = NULL;
754 
755 	if (rx_ring->desc) {
756 		dma_free_coherent(rx_ring->dev, rx_ring->size,
757 				  rx_ring->desc, rx_ring->dma);
758 		rx_ring->desc = NULL;
759 	}
760 }
761 
762 /**
763  * iavf_setup_rx_descriptors - Allocate Rx descriptors
764  * @rx_ring: Rx descriptor ring (for a specific queue) to setup
765  *
766  * Returns 0 on success, negative on failure
767  **/
768 int iavf_setup_rx_descriptors(struct iavf_ring *rx_ring)
769 {
770 	struct device *dev = rx_ring->dev;
771 	int bi_size;
772 
773 	/* warn if we are about to overwrite the pointer */
774 	WARN_ON(rx_ring->rx_bi);
775 	bi_size = sizeof(struct iavf_rx_buffer) * rx_ring->count;
776 	rx_ring->rx_bi = kzalloc(bi_size, GFP_KERNEL);
777 	if (!rx_ring->rx_bi)
778 		goto err;
779 
780 	u64_stats_init(&rx_ring->syncp);
781 
782 	/* Round up to nearest 4K */
783 	rx_ring->size = rx_ring->count * sizeof(union iavf_32byte_rx_desc);
784 	rx_ring->size = ALIGN(rx_ring->size, 4096);
785 	rx_ring->desc = dma_alloc_coherent(dev, rx_ring->size,
786 					   &rx_ring->dma, GFP_KERNEL);
787 
788 	if (!rx_ring->desc) {
789 		dev_info(dev, "Unable to allocate memory for the Rx descriptor ring, size=%d\n",
790 			 rx_ring->size);
791 		goto err;
792 	}
793 
794 	rx_ring->next_to_alloc = 0;
795 	rx_ring->next_to_clean = 0;
796 	rx_ring->next_to_use = 0;
797 
798 	return 0;
799 err:
800 	kfree(rx_ring->rx_bi);
801 	rx_ring->rx_bi = NULL;
802 	return -ENOMEM;
803 }
804 
805 /**
806  * iavf_release_rx_desc - Store the new tail and head values
807  * @rx_ring: ring to bump
808  * @val: new head index
809  **/
810 static void iavf_release_rx_desc(struct iavf_ring *rx_ring, u32 val)
811 {
812 	rx_ring->next_to_use = val;
813 
814 	/* update next to alloc since we have filled the ring */
815 	rx_ring->next_to_alloc = val;
816 
817 	/* Force memory writes to complete before letting h/w
818 	 * know there are new descriptors to fetch.  (Only
819 	 * applicable for weak-ordered memory model archs,
820 	 * such as IA-64).
821 	 */
822 	wmb();
823 	writel(val, rx_ring->tail);
824 }
825 
826 /**
827  * iavf_rx_offset - Return expected offset into page to access data
828  * @rx_ring: Ring we are requesting offset of
829  *
830  * Returns the offset value for ring into the data buffer.
831  */
832 static unsigned int iavf_rx_offset(struct iavf_ring *rx_ring)
833 {
834 	return ring_uses_build_skb(rx_ring) ? IAVF_SKB_PAD : 0;
835 }
836 
837 /**
838  * iavf_alloc_mapped_page - recycle or make a new page
839  * @rx_ring: ring to use
840  * @bi: rx_buffer struct to modify
841  *
842  * Returns true if the page was successfully allocated or
843  * reused.
844  **/
845 static bool iavf_alloc_mapped_page(struct iavf_ring *rx_ring,
846 				   struct iavf_rx_buffer *bi)
847 {
848 	struct page *page = bi->page;
849 	dma_addr_t dma;
850 
851 	/* since we are recycling buffers we should seldom need to alloc */
852 	if (likely(page)) {
853 		rx_ring->rx_stats.page_reuse_count++;
854 		return true;
855 	}
856 
857 	/* alloc new page for storage */
858 	page = dev_alloc_pages(iavf_rx_pg_order(rx_ring));
859 	if (unlikely(!page)) {
860 		rx_ring->rx_stats.alloc_page_failed++;
861 		return false;
862 	}
863 
864 	/* map page for use */
865 	dma = dma_map_page_attrs(rx_ring->dev, page, 0,
866 				 iavf_rx_pg_size(rx_ring),
867 				 DMA_FROM_DEVICE,
868 				 IAVF_RX_DMA_ATTR);
869 
870 	/* if mapping failed free memory back to system since
871 	 * there isn't much point in holding memory we can't use
872 	 */
873 	if (dma_mapping_error(rx_ring->dev, dma)) {
874 		__free_pages(page, iavf_rx_pg_order(rx_ring));
875 		rx_ring->rx_stats.alloc_page_failed++;
876 		return false;
877 	}
878 
879 	bi->dma = dma;
880 	bi->page = page;
881 	bi->page_offset = iavf_rx_offset(rx_ring);
882 
883 	/* initialize pagecnt_bias to 1 representing we fully own page */
884 	bi->pagecnt_bias = 1;
885 
886 	return true;
887 }
888 
889 /**
890  * iavf_receive_skb - Send a completed packet up the stack
891  * @rx_ring:  rx ring in play
892  * @skb: packet to send up
893  * @vlan_tag: vlan tag for packet
894  **/
895 static void iavf_receive_skb(struct iavf_ring *rx_ring,
896 			     struct sk_buff *skb, u16 vlan_tag)
897 {
898 	struct iavf_q_vector *q_vector = rx_ring->q_vector;
899 
900 	if ((rx_ring->netdev->features & NETIF_F_HW_VLAN_CTAG_RX) &&
901 	    (vlan_tag & VLAN_VID_MASK))
902 		__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vlan_tag);
903 	else if ((rx_ring->netdev->features & NETIF_F_HW_VLAN_STAG_RX) &&
904 		 vlan_tag & VLAN_VID_MASK)
905 		__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021AD), vlan_tag);
906 
907 	napi_gro_receive(&q_vector->napi, skb);
908 }
909 
910 /**
911  * iavf_alloc_rx_buffers - Replace used receive buffers
912  * @rx_ring: ring to place buffers on
913  * @cleaned_count: number of buffers to replace
914  *
915  * Returns false if all allocations were successful, true if any fail
916  **/
917 bool iavf_alloc_rx_buffers(struct iavf_ring *rx_ring, u16 cleaned_count)
918 {
919 	u16 ntu = rx_ring->next_to_use;
920 	union iavf_rx_desc *rx_desc;
921 	struct iavf_rx_buffer *bi;
922 
923 	/* do nothing if no valid netdev defined */
924 	if (!rx_ring->netdev || !cleaned_count)
925 		return false;
926 
927 	rx_desc = IAVF_RX_DESC(rx_ring, ntu);
928 	bi = &rx_ring->rx_bi[ntu];
929 
930 	do {
931 		if (!iavf_alloc_mapped_page(rx_ring, bi))
932 			goto no_buffers;
933 
934 		/* sync the buffer for use by the device */
935 		dma_sync_single_range_for_device(rx_ring->dev, bi->dma,
936 						 bi->page_offset,
937 						 rx_ring->rx_buf_len,
938 						 DMA_FROM_DEVICE);
939 
940 		/* Refresh the desc even if buffer_addrs didn't change
941 		 * because each write-back erases this info.
942 		 */
943 		rx_desc->read.pkt_addr = cpu_to_le64(bi->dma + bi->page_offset);
944 
945 		rx_desc++;
946 		bi++;
947 		ntu++;
948 		if (unlikely(ntu == rx_ring->count)) {
949 			rx_desc = IAVF_RX_DESC(rx_ring, 0);
950 			bi = rx_ring->rx_bi;
951 			ntu = 0;
952 		}
953 
954 		/* clear the status bits for the next_to_use descriptor */
955 		rx_desc->wb.qword1.status_error_len = 0;
956 
957 		cleaned_count--;
958 	} while (cleaned_count);
959 
960 	if (rx_ring->next_to_use != ntu)
961 		iavf_release_rx_desc(rx_ring, ntu);
962 
963 	return false;
964 
965 no_buffers:
966 	if (rx_ring->next_to_use != ntu)
967 		iavf_release_rx_desc(rx_ring, ntu);
968 
969 	/* make sure to come back via polling to try again after
970 	 * allocation failure
971 	 */
972 	return true;
973 }
974 
975 /**
976  * iavf_rx_checksum - Indicate in skb if hw indicated a good cksum
977  * @vsi: the VSI we care about
978  * @skb: skb currently being received and modified
979  * @rx_desc: the receive descriptor
980  **/
981 static void iavf_rx_checksum(struct iavf_vsi *vsi,
982 			     struct sk_buff *skb,
983 			     union iavf_rx_desc *rx_desc)
984 {
985 	struct iavf_rx_ptype_decoded decoded;
986 	u32 rx_error, rx_status;
987 	bool ipv4, ipv6;
988 	u8 ptype;
989 	u64 qword;
990 
991 	qword = le64_to_cpu(rx_desc->wb.qword1.status_error_len);
992 	ptype = FIELD_GET(IAVF_RXD_QW1_PTYPE_MASK, qword);
993 	rx_error = FIELD_GET(IAVF_RXD_QW1_ERROR_MASK, qword);
994 	rx_status = FIELD_GET(IAVF_RXD_QW1_STATUS_MASK, qword);
995 	decoded = decode_rx_desc_ptype(ptype);
996 
997 	skb->ip_summed = CHECKSUM_NONE;
998 
999 	skb_checksum_none_assert(skb);
1000 
1001 	/* Rx csum enabled and ip headers found? */
1002 	if (!(vsi->netdev->features & NETIF_F_RXCSUM))
1003 		return;
1004 
1005 	/* did the hardware decode the packet and checksum? */
1006 	if (!(rx_status & BIT(IAVF_RX_DESC_STATUS_L3L4P_SHIFT)))
1007 		return;
1008 
1009 	/* both known and outer_ip must be set for the below code to work */
1010 	if (!(decoded.known && decoded.outer_ip))
1011 		return;
1012 
1013 	ipv4 = (decoded.outer_ip == IAVF_RX_PTYPE_OUTER_IP) &&
1014 	       (decoded.outer_ip_ver == IAVF_RX_PTYPE_OUTER_IPV4);
1015 	ipv6 = (decoded.outer_ip == IAVF_RX_PTYPE_OUTER_IP) &&
1016 	       (decoded.outer_ip_ver == IAVF_RX_PTYPE_OUTER_IPV6);
1017 
1018 	if (ipv4 &&
1019 	    (rx_error & (BIT(IAVF_RX_DESC_ERROR_IPE_SHIFT) |
1020 			 BIT(IAVF_RX_DESC_ERROR_EIPE_SHIFT))))
1021 		goto checksum_fail;
1022 
1023 	/* likely incorrect csum if alternate IP extension headers found */
1024 	if (ipv6 &&
1025 	    rx_status & BIT(IAVF_RX_DESC_STATUS_IPV6EXADD_SHIFT))
1026 		/* don't increment checksum err here, non-fatal err */
1027 		return;
1028 
1029 	/* there was some L4 error, count error and punt packet to the stack */
1030 	if (rx_error & BIT(IAVF_RX_DESC_ERROR_L4E_SHIFT))
1031 		goto checksum_fail;
1032 
1033 	/* handle packets that were not able to be checksummed due
1034 	 * to arrival speed, in this case the stack can compute
1035 	 * the csum.
1036 	 */
1037 	if (rx_error & BIT(IAVF_RX_DESC_ERROR_PPRS_SHIFT))
1038 		return;
1039 
1040 	/* Only report checksum unnecessary for TCP, UDP, or SCTP */
1041 	switch (decoded.inner_prot) {
1042 	case IAVF_RX_PTYPE_INNER_PROT_TCP:
1043 	case IAVF_RX_PTYPE_INNER_PROT_UDP:
1044 	case IAVF_RX_PTYPE_INNER_PROT_SCTP:
1045 		skb->ip_summed = CHECKSUM_UNNECESSARY;
1046 		fallthrough;
1047 	default:
1048 		break;
1049 	}
1050 
1051 	return;
1052 
1053 checksum_fail:
1054 	vsi->back->hw_csum_rx_error++;
1055 }
1056 
1057 /**
1058  * iavf_ptype_to_htype - get a hash type
1059  * @ptype: the ptype value from the descriptor
1060  *
1061  * Returns a hash type to be used by skb_set_hash
1062  **/
1063 static int iavf_ptype_to_htype(u8 ptype)
1064 {
1065 	struct iavf_rx_ptype_decoded decoded = decode_rx_desc_ptype(ptype);
1066 
1067 	if (!decoded.known)
1068 		return PKT_HASH_TYPE_NONE;
1069 
1070 	if (decoded.outer_ip == IAVF_RX_PTYPE_OUTER_IP &&
1071 	    decoded.payload_layer == IAVF_RX_PTYPE_PAYLOAD_LAYER_PAY4)
1072 		return PKT_HASH_TYPE_L4;
1073 	else if (decoded.outer_ip == IAVF_RX_PTYPE_OUTER_IP &&
1074 		 decoded.payload_layer == IAVF_RX_PTYPE_PAYLOAD_LAYER_PAY3)
1075 		return PKT_HASH_TYPE_L3;
1076 	else
1077 		return PKT_HASH_TYPE_L2;
1078 }
1079 
1080 /**
1081  * iavf_rx_hash - set the hash value in the skb
1082  * @ring: descriptor ring
1083  * @rx_desc: specific descriptor
1084  * @skb: skb currently being received and modified
1085  * @rx_ptype: Rx packet type
1086  **/
1087 static void iavf_rx_hash(struct iavf_ring *ring,
1088 			 union iavf_rx_desc *rx_desc,
1089 			 struct sk_buff *skb,
1090 			 u8 rx_ptype)
1091 {
1092 	u32 hash;
1093 	const __le64 rss_mask =
1094 		cpu_to_le64((u64)IAVF_RX_DESC_FLTSTAT_RSS_HASH <<
1095 			    IAVF_RX_DESC_STATUS_FLTSTAT_SHIFT);
1096 
1097 	if (!(ring->netdev->features & NETIF_F_RXHASH))
1098 		return;
1099 
1100 	if ((rx_desc->wb.qword1.status_error_len & rss_mask) == rss_mask) {
1101 		hash = le32_to_cpu(rx_desc->wb.qword0.hi_dword.rss);
1102 		skb_set_hash(skb, hash, iavf_ptype_to_htype(rx_ptype));
1103 	}
1104 }
1105 
1106 /**
1107  * iavf_process_skb_fields - Populate skb header fields from Rx descriptor
1108  * @rx_ring: rx descriptor ring packet is being transacted on
1109  * @rx_desc: pointer to the EOP Rx descriptor
1110  * @skb: pointer to current skb being populated
1111  * @rx_ptype: the packet type decoded by hardware
1112  *
1113  * This function checks the ring, descriptor, and packet information in
1114  * order to populate the hash, checksum, VLAN, protocol, and
1115  * other fields within the skb.
1116  **/
1117 static void
1118 iavf_process_skb_fields(struct iavf_ring *rx_ring,
1119 			union iavf_rx_desc *rx_desc, struct sk_buff *skb,
1120 			u8 rx_ptype)
1121 {
1122 	iavf_rx_hash(rx_ring, rx_desc, skb, rx_ptype);
1123 
1124 	iavf_rx_checksum(rx_ring->vsi, skb, rx_desc);
1125 
1126 	skb_record_rx_queue(skb, rx_ring->queue_index);
1127 
1128 	/* modifies the skb - consumes the enet header */
1129 	skb->protocol = eth_type_trans(skb, rx_ring->netdev);
1130 }
1131 
1132 /**
1133  * iavf_cleanup_headers - Correct empty headers
1134  * @rx_ring: rx descriptor ring packet is being transacted on
1135  * @skb: pointer to current skb being fixed
1136  *
1137  * Also address the case where we are pulling data in on pages only
1138  * and as such no data is present in the skb header.
1139  *
1140  * In addition if skb is not at least 60 bytes we need to pad it so that
1141  * it is large enough to qualify as a valid Ethernet frame.
1142  *
1143  * Returns true if an error was encountered and skb was freed.
1144  **/
1145 static bool iavf_cleanup_headers(struct iavf_ring *rx_ring, struct sk_buff *skb)
1146 {
1147 	/* if eth_skb_pad returns an error the skb was freed */
1148 	if (eth_skb_pad(skb))
1149 		return true;
1150 
1151 	return false;
1152 }
1153 
1154 /**
1155  * iavf_reuse_rx_page - page flip buffer and store it back on the ring
1156  * @rx_ring: rx descriptor ring to store buffers on
1157  * @old_buff: donor buffer to have page reused
1158  *
1159  * Synchronizes page for reuse by the adapter
1160  **/
1161 static void iavf_reuse_rx_page(struct iavf_ring *rx_ring,
1162 			       struct iavf_rx_buffer *old_buff)
1163 {
1164 	struct iavf_rx_buffer *new_buff;
1165 	u16 nta = rx_ring->next_to_alloc;
1166 
1167 	new_buff = &rx_ring->rx_bi[nta];
1168 
1169 	/* update, and store next to alloc */
1170 	nta++;
1171 	rx_ring->next_to_alloc = (nta < rx_ring->count) ? nta : 0;
1172 
1173 	/* transfer page from old buffer to new buffer */
1174 	new_buff->dma		= old_buff->dma;
1175 	new_buff->page		= old_buff->page;
1176 	new_buff->page_offset	= old_buff->page_offset;
1177 	new_buff->pagecnt_bias	= old_buff->pagecnt_bias;
1178 }
1179 
1180 /**
1181  * iavf_can_reuse_rx_page - Determine if this page can be reused by
1182  * the adapter for another receive
1183  *
1184  * @rx_buffer: buffer containing the page
1185  *
1186  * If page is reusable, rx_buffer->page_offset is adjusted to point to
1187  * an unused region in the page.
1188  *
1189  * For small pages, @truesize will be a constant value, half the size
1190  * of the memory at page.  We'll attempt to alternate between high and
1191  * low halves of the page, with one half ready for use by the hardware
1192  * and the other half being consumed by the stack.  We use the page
1193  * ref count to determine whether the stack has finished consuming the
1194  * portion of this page that was passed up with a previous packet.  If
1195  * the page ref count is >1, we'll assume the "other" half page is
1196  * still busy, and this page cannot be reused.
1197  *
1198  * For larger pages, @truesize will be the actual space used by the
1199  * received packet (adjusted upward to an even multiple of the cache
1200  * line size).  This will advance through the page by the amount
1201  * actually consumed by the received packets while there is still
1202  * space for a buffer.  Each region of larger pages will be used at
1203  * most once, after which the page will not be reused.
1204  *
1205  * In either case, if the page is reusable its refcount is increased.
1206  **/
1207 static bool iavf_can_reuse_rx_page(struct iavf_rx_buffer *rx_buffer)
1208 {
1209 	unsigned int pagecnt_bias = rx_buffer->pagecnt_bias;
1210 	struct page *page = rx_buffer->page;
1211 
1212 	/* Is any reuse possible? */
1213 	if (!dev_page_is_reusable(page))
1214 		return false;
1215 
1216 #if (PAGE_SIZE < 8192)
1217 	/* if we are only owner of page we can reuse it */
1218 	if (unlikely((page_count(page) - pagecnt_bias) > 1))
1219 		return false;
1220 #else
1221 #define IAVF_LAST_OFFSET \
1222 	(SKB_WITH_OVERHEAD(PAGE_SIZE) - IAVF_RXBUFFER_2048)
1223 	if (rx_buffer->page_offset > IAVF_LAST_OFFSET)
1224 		return false;
1225 #endif
1226 
1227 	/* If we have drained the page fragment pool we need to update
1228 	 * the pagecnt_bias and page count so that we fully restock the
1229 	 * number of references the driver holds.
1230 	 */
1231 	if (unlikely(!pagecnt_bias)) {
1232 		page_ref_add(page, USHRT_MAX);
1233 		rx_buffer->pagecnt_bias = USHRT_MAX;
1234 	}
1235 
1236 	return true;
1237 }
1238 
1239 /**
1240  * iavf_add_rx_frag - Add contents of Rx buffer to sk_buff
1241  * @rx_ring: rx descriptor ring to transact packets on
1242  * @rx_buffer: buffer containing page to add
1243  * @skb: sk_buff to place the data into
1244  * @size: packet length from rx_desc
1245  *
1246  * This function will add the data contained in rx_buffer->page to the skb.
1247  * It will just attach the page as a frag to the skb.
1248  *
1249  * The function will then update the page offset.
1250  **/
1251 static void iavf_add_rx_frag(struct iavf_ring *rx_ring,
1252 			     struct iavf_rx_buffer *rx_buffer,
1253 			     struct sk_buff *skb,
1254 			     unsigned int size)
1255 {
1256 #if (PAGE_SIZE < 8192)
1257 	unsigned int truesize = iavf_rx_pg_size(rx_ring) / 2;
1258 #else
1259 	unsigned int truesize = SKB_DATA_ALIGN(size + iavf_rx_offset(rx_ring));
1260 #endif
1261 
1262 	if (!size)
1263 		return;
1264 
1265 	skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, rx_buffer->page,
1266 			rx_buffer->page_offset, size, truesize);
1267 
1268 	/* page is being used so we must update the page offset */
1269 #if (PAGE_SIZE < 8192)
1270 	rx_buffer->page_offset ^= truesize;
1271 #else
1272 	rx_buffer->page_offset += truesize;
1273 #endif
1274 }
1275 
1276 /**
1277  * iavf_get_rx_buffer - Fetch Rx buffer and synchronize data for use
1278  * @rx_ring: rx descriptor ring to transact packets on
1279  * @size: size of buffer to add to skb
1280  *
1281  * This function will pull an Rx buffer from the ring and synchronize it
1282  * for use by the CPU.
1283  */
1284 static struct iavf_rx_buffer *iavf_get_rx_buffer(struct iavf_ring *rx_ring,
1285 						 const unsigned int size)
1286 {
1287 	struct iavf_rx_buffer *rx_buffer;
1288 
1289 	rx_buffer = &rx_ring->rx_bi[rx_ring->next_to_clean];
1290 	prefetchw(rx_buffer->page);
1291 	if (!size)
1292 		return rx_buffer;
1293 
1294 	/* we are reusing so sync this buffer for CPU use */
1295 	dma_sync_single_range_for_cpu(rx_ring->dev,
1296 				      rx_buffer->dma,
1297 				      rx_buffer->page_offset,
1298 				      size,
1299 				      DMA_FROM_DEVICE);
1300 
1301 	/* We have pulled a buffer for use, so decrement pagecnt_bias */
1302 	rx_buffer->pagecnt_bias--;
1303 
1304 	return rx_buffer;
1305 }
1306 
1307 /**
1308  * iavf_construct_skb - Allocate skb and populate it
1309  * @rx_ring: rx descriptor ring to transact packets on
1310  * @rx_buffer: rx buffer to pull data from
1311  * @size: size of buffer to add to skb
1312  *
1313  * This function allocates an skb.  It then populates it with the page
1314  * data from the current receive descriptor, taking care to set up the
1315  * skb correctly.
1316  */
1317 static struct sk_buff *iavf_construct_skb(struct iavf_ring *rx_ring,
1318 					  struct iavf_rx_buffer *rx_buffer,
1319 					  unsigned int size)
1320 {
1321 	void *va;
1322 #if (PAGE_SIZE < 8192)
1323 	unsigned int truesize = iavf_rx_pg_size(rx_ring) / 2;
1324 #else
1325 	unsigned int truesize = SKB_DATA_ALIGN(size);
1326 #endif
1327 	unsigned int headlen;
1328 	struct sk_buff *skb;
1329 
1330 	if (!rx_buffer)
1331 		return NULL;
1332 	/* prefetch first cache line of first page */
1333 	va = page_address(rx_buffer->page) + rx_buffer->page_offset;
1334 	net_prefetch(va);
1335 
1336 	/* allocate a skb to store the frags */
1337 	skb = napi_alloc_skb(&rx_ring->q_vector->napi, IAVF_RX_HDR_SIZE);
1338 	if (unlikely(!skb))
1339 		return NULL;
1340 
1341 	/* Determine available headroom for copy */
1342 	headlen = size;
1343 	if (headlen > IAVF_RX_HDR_SIZE)
1344 		headlen = eth_get_headlen(skb->dev, va, IAVF_RX_HDR_SIZE);
1345 
1346 	/* align pull length to size of long to optimize memcpy performance */
1347 	memcpy(__skb_put(skb, headlen), va, ALIGN(headlen, sizeof(long)));
1348 
1349 	/* update all of the pointers */
1350 	size -= headlen;
1351 	if (size) {
1352 		skb_add_rx_frag(skb, 0, rx_buffer->page,
1353 				rx_buffer->page_offset + headlen,
1354 				size, truesize);
1355 
1356 		/* buffer is used by skb, update page_offset */
1357 #if (PAGE_SIZE < 8192)
1358 		rx_buffer->page_offset ^= truesize;
1359 #else
1360 		rx_buffer->page_offset += truesize;
1361 #endif
1362 	} else {
1363 		/* buffer is unused, reset bias back to rx_buffer */
1364 		rx_buffer->pagecnt_bias++;
1365 	}
1366 
1367 	return skb;
1368 }
1369 
1370 /**
1371  * iavf_build_skb - Build skb around an existing buffer
1372  * @rx_ring: Rx descriptor ring to transact packets on
1373  * @rx_buffer: Rx buffer to pull data from
1374  * @size: size of buffer to add to skb
1375  *
1376  * This function builds an skb around an existing Rx buffer, taking care
1377  * to set up the skb correctly and avoid any memcpy overhead.
1378  */
1379 static struct sk_buff *iavf_build_skb(struct iavf_ring *rx_ring,
1380 				      struct iavf_rx_buffer *rx_buffer,
1381 				      unsigned int size)
1382 {
1383 	void *va;
1384 #if (PAGE_SIZE < 8192)
1385 	unsigned int truesize = iavf_rx_pg_size(rx_ring) / 2;
1386 #else
1387 	unsigned int truesize = SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) +
1388 				SKB_DATA_ALIGN(IAVF_SKB_PAD + size);
1389 #endif
1390 	struct sk_buff *skb;
1391 
1392 	if (!rx_buffer || !size)
1393 		return NULL;
1394 	/* prefetch first cache line of first page */
1395 	va = page_address(rx_buffer->page) + rx_buffer->page_offset;
1396 	net_prefetch(va);
1397 
1398 	/* build an skb around the page buffer */
1399 	skb = napi_build_skb(va - IAVF_SKB_PAD, truesize);
1400 	if (unlikely(!skb))
1401 		return NULL;
1402 
1403 	/* update pointers within the skb to store the data */
1404 	skb_reserve(skb, IAVF_SKB_PAD);
1405 	__skb_put(skb, size);
1406 
1407 	/* buffer is used by skb, update page_offset */
1408 #if (PAGE_SIZE < 8192)
1409 	rx_buffer->page_offset ^= truesize;
1410 #else
1411 	rx_buffer->page_offset += truesize;
1412 #endif
1413 
1414 	return skb;
1415 }
1416 
1417 /**
1418  * iavf_put_rx_buffer - Clean up used buffer and either recycle or free
1419  * @rx_ring: rx descriptor ring to transact packets on
1420  * @rx_buffer: rx buffer to pull data from
1421  *
1422  * This function will clean up the contents of the rx_buffer.  It will
1423  * either recycle the buffer or unmap it and free the associated resources.
1424  */
1425 static void iavf_put_rx_buffer(struct iavf_ring *rx_ring,
1426 			       struct iavf_rx_buffer *rx_buffer)
1427 {
1428 	if (!rx_buffer)
1429 		return;
1430 
1431 	if (iavf_can_reuse_rx_page(rx_buffer)) {
1432 		/* hand second half of page back to the ring */
1433 		iavf_reuse_rx_page(rx_ring, rx_buffer);
1434 		rx_ring->rx_stats.page_reuse_count++;
1435 	} else {
1436 		/* we are not reusing the buffer so unmap it */
1437 		dma_unmap_page_attrs(rx_ring->dev, rx_buffer->dma,
1438 				     iavf_rx_pg_size(rx_ring),
1439 				     DMA_FROM_DEVICE, IAVF_RX_DMA_ATTR);
1440 		__page_frag_cache_drain(rx_buffer->page,
1441 					rx_buffer->pagecnt_bias);
1442 	}
1443 
1444 	/* clear contents of buffer_info */
1445 	rx_buffer->page = NULL;
1446 }
1447 
1448 /**
1449  * iavf_is_non_eop - process handling of non-EOP buffers
1450  * @rx_ring: Rx ring being processed
1451  * @rx_desc: Rx descriptor for current buffer
1452  * @skb: Current socket buffer containing buffer in progress
1453  *
1454  * This function updates next to clean.  If the buffer is an EOP buffer
1455  * this function exits returning false, otherwise it will place the
1456  * sk_buff in the next buffer to be chained and return true indicating
1457  * that this is in fact a non-EOP buffer.
1458  **/
1459 static bool iavf_is_non_eop(struct iavf_ring *rx_ring,
1460 			    union iavf_rx_desc *rx_desc,
1461 			    struct sk_buff *skb)
1462 {
1463 	u32 ntc = rx_ring->next_to_clean + 1;
1464 
1465 	/* fetch, update, and store next to clean */
1466 	ntc = (ntc < rx_ring->count) ? ntc : 0;
1467 	rx_ring->next_to_clean = ntc;
1468 
1469 	prefetch(IAVF_RX_DESC(rx_ring, ntc));
1470 
1471 	/* if we are the last buffer then there is nothing else to do */
1472 #define IAVF_RXD_EOF BIT(IAVF_RX_DESC_STATUS_EOF_SHIFT)
1473 	if (likely(iavf_test_staterr(rx_desc, IAVF_RXD_EOF)))
1474 		return false;
1475 
1476 	rx_ring->rx_stats.non_eop_descs++;
1477 
1478 	return true;
1479 }
1480 
1481 /**
1482  * iavf_clean_rx_irq - Clean completed descriptors from Rx ring - bounce buf
1483  * @rx_ring: rx descriptor ring to transact packets on
1484  * @budget: Total limit on number of packets to process
1485  *
1486  * This function provides a "bounce buffer" approach to Rx interrupt
1487  * processing.  The advantage to this is that on systems that have
1488  * expensive overhead for IOMMU access this provides a means of avoiding
1489  * it by maintaining the mapping of the page to the system.
1490  *
1491  * Returns amount of work completed
1492  **/
1493 static int iavf_clean_rx_irq(struct iavf_ring *rx_ring, int budget)
1494 {
1495 	unsigned int total_rx_bytes = 0, total_rx_packets = 0;
1496 	struct sk_buff *skb = rx_ring->skb;
1497 	u16 cleaned_count = IAVF_DESC_UNUSED(rx_ring);
1498 	bool failure = false;
1499 
1500 	while (likely(total_rx_packets < (unsigned int)budget)) {
1501 		struct iavf_rx_buffer *rx_buffer;
1502 		union iavf_rx_desc *rx_desc;
1503 		unsigned int size;
1504 		u16 vlan_tag = 0;
1505 		u8 rx_ptype;
1506 		u64 qword;
1507 
1508 		/* return some buffers to hardware, one at a time is too slow */
1509 		if (cleaned_count >= IAVF_RX_BUFFER_WRITE) {
1510 			failure = failure ||
1511 				  iavf_alloc_rx_buffers(rx_ring, cleaned_count);
1512 			cleaned_count = 0;
1513 		}
1514 
1515 		rx_desc = IAVF_RX_DESC(rx_ring, rx_ring->next_to_clean);
1516 
1517 		/* status_error_len will always be zero for unused descriptors
1518 		 * because it's cleared in cleanup, and overlaps with hdr_addr
1519 		 * which is always zero because packet split isn't used, if the
1520 		 * hardware wrote DD then the length will be non-zero
1521 		 */
1522 		qword = le64_to_cpu(rx_desc->wb.qword1.status_error_len);
1523 
1524 		/* This memory barrier is needed to keep us from reading
1525 		 * any other fields out of the rx_desc until we have
1526 		 * verified the descriptor has been written back.
1527 		 */
1528 		dma_rmb();
1529 #define IAVF_RXD_DD BIT(IAVF_RX_DESC_STATUS_DD_SHIFT)
1530 		if (!iavf_test_staterr(rx_desc, IAVF_RXD_DD))
1531 			break;
1532 
1533 		size = FIELD_GET(IAVF_RXD_QW1_LENGTH_PBUF_MASK, qword);
1534 
1535 		iavf_trace(clean_rx_irq, rx_ring, rx_desc, skb);
1536 		rx_buffer = iavf_get_rx_buffer(rx_ring, size);
1537 
1538 		/* retrieve a buffer from the ring */
1539 		if (skb)
1540 			iavf_add_rx_frag(rx_ring, rx_buffer, skb, size);
1541 		else if (ring_uses_build_skb(rx_ring))
1542 			skb = iavf_build_skb(rx_ring, rx_buffer, size);
1543 		else
1544 			skb = iavf_construct_skb(rx_ring, rx_buffer, size);
1545 
1546 		/* exit if we failed to retrieve a buffer */
1547 		if (!skb) {
1548 			rx_ring->rx_stats.alloc_buff_failed++;
1549 			if (rx_buffer && size)
1550 				rx_buffer->pagecnt_bias++;
1551 			break;
1552 		}
1553 
1554 		iavf_put_rx_buffer(rx_ring, rx_buffer);
1555 		cleaned_count++;
1556 
1557 		if (iavf_is_non_eop(rx_ring, rx_desc, skb))
1558 			continue;
1559 
1560 		/* ERR_MASK will only have valid bits if EOP set, and
1561 		 * what we are doing here is actually checking
1562 		 * IAVF_RX_DESC_ERROR_RXE_SHIFT, since it is the zeroth bit in
1563 		 * the error field
1564 		 */
1565 		if (unlikely(iavf_test_staterr(rx_desc, BIT(IAVF_RXD_QW1_ERROR_SHIFT)))) {
1566 			dev_kfree_skb_any(skb);
1567 			skb = NULL;
1568 			continue;
1569 		}
1570 
1571 		if (iavf_cleanup_headers(rx_ring, skb)) {
1572 			skb = NULL;
1573 			continue;
1574 		}
1575 
1576 		/* probably a little skewed due to removing CRC */
1577 		total_rx_bytes += skb->len;
1578 
1579 		qword = le64_to_cpu(rx_desc->wb.qword1.status_error_len);
1580 		rx_ptype = FIELD_GET(IAVF_RXD_QW1_PTYPE_MASK, qword);
1581 
1582 		/* populate checksum, VLAN, and protocol */
1583 		iavf_process_skb_fields(rx_ring, rx_desc, skb, rx_ptype);
1584 
1585 		if (qword & BIT(IAVF_RX_DESC_STATUS_L2TAG1P_SHIFT) &&
1586 		    rx_ring->flags & IAVF_TXRX_FLAGS_VLAN_TAG_LOC_L2TAG1)
1587 			vlan_tag = le16_to_cpu(rx_desc->wb.qword0.lo_dword.l2tag1);
1588 		if (rx_desc->wb.qword2.ext_status &
1589 		    cpu_to_le16(BIT(IAVF_RX_DESC_EXT_STATUS_L2TAG2P_SHIFT)) &&
1590 		    rx_ring->flags & IAVF_RXR_FLAGS_VLAN_TAG_LOC_L2TAG2_2)
1591 			vlan_tag = le16_to_cpu(rx_desc->wb.qword2.l2tag2_2);
1592 
1593 		iavf_trace(clean_rx_irq_rx, rx_ring, rx_desc, skb);
1594 		iavf_receive_skb(rx_ring, skb, vlan_tag);
1595 		skb = NULL;
1596 
1597 		/* update budget accounting */
1598 		total_rx_packets++;
1599 	}
1600 
1601 	rx_ring->skb = skb;
1602 
1603 	u64_stats_update_begin(&rx_ring->syncp);
1604 	rx_ring->stats.packets += total_rx_packets;
1605 	rx_ring->stats.bytes += total_rx_bytes;
1606 	u64_stats_update_end(&rx_ring->syncp);
1607 	rx_ring->q_vector->rx.total_packets += total_rx_packets;
1608 	rx_ring->q_vector->rx.total_bytes += total_rx_bytes;
1609 
1610 	/* guarantee a trip back through this routine if there was a failure */
1611 	return failure ? budget : (int)total_rx_packets;
1612 }
1613 
1614 static inline u32 iavf_buildreg_itr(const int type, u16 itr)
1615 {
1616 	u32 val;
1617 
1618 	/* We don't bother with setting the CLEARPBA bit as the data sheet
1619 	 * points out doing so is "meaningless since it was already
1620 	 * auto-cleared". The auto-clearing happens when the interrupt is
1621 	 * asserted.
1622 	 *
1623 	 * Hardware errata 28 for also indicates that writing to a
1624 	 * xxINT_DYN_CTLx CSR with INTENA_MSK (bit 31) set to 0 will clear
1625 	 * an event in the PBA anyway so we need to rely on the automask
1626 	 * to hold pending events for us until the interrupt is re-enabled
1627 	 *
1628 	 * The itr value is reported in microseconds, and the register
1629 	 * value is recorded in 2 microsecond units. For this reason we
1630 	 * only need to shift by the interval shift - 1 instead of the
1631 	 * full value.
1632 	 */
1633 	itr &= IAVF_ITR_MASK;
1634 
1635 	val = IAVF_VFINT_DYN_CTLN1_INTENA_MASK |
1636 	      (type << IAVF_VFINT_DYN_CTLN1_ITR_INDX_SHIFT) |
1637 	      (itr << (IAVF_VFINT_DYN_CTLN1_INTERVAL_SHIFT - 1));
1638 
1639 	return val;
1640 }
1641 
1642 /* a small macro to shorten up some long lines */
1643 #define INTREG IAVF_VFINT_DYN_CTLN1
1644 
1645 /* The act of updating the ITR will cause it to immediately trigger. In order
1646  * to prevent this from throwing off adaptive update statistics we defer the
1647  * update so that it can only happen so often. So after either Tx or Rx are
1648  * updated we make the adaptive scheme wait until either the ITR completely
1649  * expires via the next_update expiration or we have been through at least
1650  * 3 interrupts.
1651  */
1652 #define ITR_COUNTDOWN_START 3
1653 
1654 /**
1655  * iavf_update_enable_itr - Update itr and re-enable MSIX interrupt
1656  * @vsi: the VSI we care about
1657  * @q_vector: q_vector for which itr is being updated and interrupt enabled
1658  *
1659  **/
1660 static void iavf_update_enable_itr(struct iavf_vsi *vsi,
1661 				   struct iavf_q_vector *q_vector)
1662 {
1663 	struct iavf_hw *hw = &vsi->back->hw;
1664 	u32 intval;
1665 
1666 	/* These will do nothing if dynamic updates are not enabled */
1667 	iavf_update_itr(q_vector, &q_vector->tx);
1668 	iavf_update_itr(q_vector, &q_vector->rx);
1669 
1670 	/* This block of logic allows us to get away with only updating
1671 	 * one ITR value with each interrupt. The idea is to perform a
1672 	 * pseudo-lazy update with the following criteria.
1673 	 *
1674 	 * 1. Rx is given higher priority than Tx if both are in same state
1675 	 * 2. If we must reduce an ITR that is given highest priority.
1676 	 * 3. We then give priority to increasing ITR based on amount.
1677 	 */
1678 	if (q_vector->rx.target_itr < q_vector->rx.current_itr) {
1679 		/* Rx ITR needs to be reduced, this is highest priority */
1680 		intval = iavf_buildreg_itr(IAVF_RX_ITR,
1681 					   q_vector->rx.target_itr);
1682 		q_vector->rx.current_itr = q_vector->rx.target_itr;
1683 		q_vector->itr_countdown = ITR_COUNTDOWN_START;
1684 	} else if ((q_vector->tx.target_itr < q_vector->tx.current_itr) ||
1685 		   ((q_vector->rx.target_itr - q_vector->rx.current_itr) <
1686 		    (q_vector->tx.target_itr - q_vector->tx.current_itr))) {
1687 		/* Tx ITR needs to be reduced, this is second priority
1688 		 * Tx ITR needs to be increased more than Rx, fourth priority
1689 		 */
1690 		intval = iavf_buildreg_itr(IAVF_TX_ITR,
1691 					   q_vector->tx.target_itr);
1692 		q_vector->tx.current_itr = q_vector->tx.target_itr;
1693 		q_vector->itr_countdown = ITR_COUNTDOWN_START;
1694 	} else if (q_vector->rx.current_itr != q_vector->rx.target_itr) {
1695 		/* Rx ITR needs to be increased, third priority */
1696 		intval = iavf_buildreg_itr(IAVF_RX_ITR,
1697 					   q_vector->rx.target_itr);
1698 		q_vector->rx.current_itr = q_vector->rx.target_itr;
1699 		q_vector->itr_countdown = ITR_COUNTDOWN_START;
1700 	} else {
1701 		/* No ITR update, lowest priority */
1702 		intval = iavf_buildreg_itr(IAVF_ITR_NONE, 0);
1703 		if (q_vector->itr_countdown)
1704 			q_vector->itr_countdown--;
1705 	}
1706 
1707 	if (!test_bit(__IAVF_VSI_DOWN, vsi->state))
1708 		wr32(hw, INTREG(q_vector->reg_idx), intval);
1709 }
1710 
1711 /**
1712  * iavf_napi_poll - NAPI polling Rx/Tx cleanup routine
1713  * @napi: napi struct with our devices info in it
1714  * @budget: amount of work driver is allowed to do this pass, in packets
1715  *
1716  * This function will clean all queues associated with a q_vector.
1717  *
1718  * Returns the amount of work done
1719  **/
1720 int iavf_napi_poll(struct napi_struct *napi, int budget)
1721 {
1722 	struct iavf_q_vector *q_vector =
1723 			       container_of(napi, struct iavf_q_vector, napi);
1724 	struct iavf_vsi *vsi = q_vector->vsi;
1725 	struct iavf_ring *ring;
1726 	bool clean_complete = true;
1727 	bool arm_wb = false;
1728 	int budget_per_ring;
1729 	int work_done = 0;
1730 
1731 	if (test_bit(__IAVF_VSI_DOWN, vsi->state)) {
1732 		napi_complete(napi);
1733 		return 0;
1734 	}
1735 
1736 	/* Since the actual Tx work is minimal, we can give the Tx a larger
1737 	 * budget and be more aggressive about cleaning up the Tx descriptors.
1738 	 */
1739 	iavf_for_each_ring(ring, q_vector->tx) {
1740 		if (!iavf_clean_tx_irq(vsi, ring, budget)) {
1741 			clean_complete = false;
1742 			continue;
1743 		}
1744 		arm_wb |= ring->arm_wb;
1745 		ring->arm_wb = false;
1746 	}
1747 
1748 	/* Handle case where we are called by netpoll with a budget of 0 */
1749 	if (budget <= 0)
1750 		goto tx_only;
1751 
1752 	/* We attempt to distribute budget to each Rx queue fairly, but don't
1753 	 * allow the budget to go below 1 because that would exit polling early.
1754 	 */
1755 	budget_per_ring = max(budget/q_vector->num_ringpairs, 1);
1756 
1757 	iavf_for_each_ring(ring, q_vector->rx) {
1758 		int cleaned = iavf_clean_rx_irq(ring, budget_per_ring);
1759 
1760 		work_done += cleaned;
1761 		/* if we clean as many as budgeted, we must not be done */
1762 		if (cleaned >= budget_per_ring)
1763 			clean_complete = false;
1764 	}
1765 
1766 	/* If work not completed, return budget and polling will return */
1767 	if (!clean_complete) {
1768 		int cpu_id = smp_processor_id();
1769 
1770 		/* It is possible that the interrupt affinity has changed but,
1771 		 * if the cpu is pegged at 100%, polling will never exit while
1772 		 * traffic continues and the interrupt will be stuck on this
1773 		 * cpu.  We check to make sure affinity is correct before we
1774 		 * continue to poll, otherwise we must stop polling so the
1775 		 * interrupt can move to the correct cpu.
1776 		 */
1777 		if (!cpumask_test_cpu(cpu_id, &q_vector->affinity_mask)) {
1778 			/* Tell napi that we are done polling */
1779 			napi_complete_done(napi, work_done);
1780 
1781 			/* Force an interrupt */
1782 			iavf_force_wb(vsi, q_vector);
1783 
1784 			/* Return budget-1 so that polling stops */
1785 			return budget - 1;
1786 		}
1787 tx_only:
1788 		if (arm_wb) {
1789 			q_vector->tx.ring[0].tx_stats.tx_force_wb++;
1790 			iavf_enable_wb_on_itr(vsi, q_vector);
1791 		}
1792 		return budget;
1793 	}
1794 
1795 	if (vsi->back->flags & IAVF_TXR_FLAGS_WB_ON_ITR)
1796 		q_vector->arm_wb_state = false;
1797 
1798 	/* Exit the polling mode, but don't re-enable interrupts if stack might
1799 	 * poll us due to busy-polling
1800 	 */
1801 	if (likely(napi_complete_done(napi, work_done)))
1802 		iavf_update_enable_itr(vsi, q_vector);
1803 
1804 	return min_t(int, work_done, budget - 1);
1805 }
1806 
1807 /**
1808  * iavf_tx_prepare_vlan_flags - prepare generic TX VLAN tagging flags for HW
1809  * @skb:     send buffer
1810  * @tx_ring: ring to send buffer on
1811  * @flags:   the tx flags to be set
1812  *
1813  * Checks the skb and set up correspondingly several generic transmit flags
1814  * related to VLAN tagging for the HW, such as VLAN, DCB, etc.
1815  *
1816  * Returns error code indicate the frame should be dropped upon error and the
1817  * otherwise  returns 0 to indicate the flags has been set properly.
1818  **/
1819 static void iavf_tx_prepare_vlan_flags(struct sk_buff *skb,
1820 				       struct iavf_ring *tx_ring, u32 *flags)
1821 {
1822 	u32  tx_flags = 0;
1823 
1824 
1825 	/* stack will only request hardware VLAN insertion offload for protocols
1826 	 * that the driver supports and has enabled
1827 	 */
1828 	if (!skb_vlan_tag_present(skb))
1829 		return;
1830 
1831 	tx_flags |= skb_vlan_tag_get(skb) << IAVF_TX_FLAGS_VLAN_SHIFT;
1832 	if (tx_ring->flags & IAVF_TXR_FLAGS_VLAN_TAG_LOC_L2TAG2) {
1833 		tx_flags |= IAVF_TX_FLAGS_HW_OUTER_SINGLE_VLAN;
1834 	} else if (tx_ring->flags & IAVF_TXRX_FLAGS_VLAN_TAG_LOC_L2TAG1) {
1835 		tx_flags |= IAVF_TX_FLAGS_HW_VLAN;
1836 	} else {
1837 		dev_dbg(tx_ring->dev, "Unsupported Tx VLAN tag location requested\n");
1838 		return;
1839 	}
1840 
1841 	*flags = tx_flags;
1842 }
1843 
1844 /**
1845  * iavf_tso - set up the tso context descriptor
1846  * @first:    pointer to first Tx buffer for xmit
1847  * @hdr_len:  ptr to the size of the packet header
1848  * @cd_type_cmd_tso_mss: Quad Word 1
1849  *
1850  * Returns 0 if no TSO can happen, 1 if tso is going, or error
1851  **/
1852 static int iavf_tso(struct iavf_tx_buffer *first, u8 *hdr_len,
1853 		    u64 *cd_type_cmd_tso_mss)
1854 {
1855 	struct sk_buff *skb = first->skb;
1856 	u64 cd_cmd, cd_tso_len, cd_mss;
1857 	union {
1858 		struct iphdr *v4;
1859 		struct ipv6hdr *v6;
1860 		unsigned char *hdr;
1861 	} ip;
1862 	union {
1863 		struct tcphdr *tcp;
1864 		struct udphdr *udp;
1865 		unsigned char *hdr;
1866 	} l4;
1867 	u32 paylen, l4_offset;
1868 	u16 gso_segs, gso_size;
1869 	int err;
1870 
1871 	if (skb->ip_summed != CHECKSUM_PARTIAL)
1872 		return 0;
1873 
1874 	if (!skb_is_gso(skb))
1875 		return 0;
1876 
1877 	err = skb_cow_head(skb, 0);
1878 	if (err < 0)
1879 		return err;
1880 
1881 	ip.hdr = skb_network_header(skb);
1882 	l4.hdr = skb_transport_header(skb);
1883 
1884 	/* initialize outer IP header fields */
1885 	if (ip.v4->version == 4) {
1886 		ip.v4->tot_len = 0;
1887 		ip.v4->check = 0;
1888 	} else {
1889 		ip.v6->payload_len = 0;
1890 	}
1891 
1892 	if (skb_shinfo(skb)->gso_type & (SKB_GSO_GRE |
1893 					 SKB_GSO_GRE_CSUM |
1894 					 SKB_GSO_IPXIP4 |
1895 					 SKB_GSO_IPXIP6 |
1896 					 SKB_GSO_UDP_TUNNEL |
1897 					 SKB_GSO_UDP_TUNNEL_CSUM)) {
1898 		if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL) &&
1899 		    (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_TUNNEL_CSUM)) {
1900 			l4.udp->len = 0;
1901 
1902 			/* determine offset of outer transport header */
1903 			l4_offset = l4.hdr - skb->data;
1904 
1905 			/* remove payload length from outer checksum */
1906 			paylen = skb->len - l4_offset;
1907 			csum_replace_by_diff(&l4.udp->check,
1908 					     (__force __wsum)htonl(paylen));
1909 		}
1910 
1911 		/* reset pointers to inner headers */
1912 		ip.hdr = skb_inner_network_header(skb);
1913 		l4.hdr = skb_inner_transport_header(skb);
1914 
1915 		/* initialize inner IP header fields */
1916 		if (ip.v4->version == 4) {
1917 			ip.v4->tot_len = 0;
1918 			ip.v4->check = 0;
1919 		} else {
1920 			ip.v6->payload_len = 0;
1921 		}
1922 	}
1923 
1924 	/* determine offset of inner transport header */
1925 	l4_offset = l4.hdr - skb->data;
1926 	/* remove payload length from inner checksum */
1927 	paylen = skb->len - l4_offset;
1928 
1929 	if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) {
1930 		csum_replace_by_diff(&l4.udp->check,
1931 				     (__force __wsum)htonl(paylen));
1932 		/* compute length of UDP segmentation header */
1933 		*hdr_len = (u8)sizeof(l4.udp) + l4_offset;
1934 	} else {
1935 		csum_replace_by_diff(&l4.tcp->check,
1936 				     (__force __wsum)htonl(paylen));
1937 		/* compute length of TCP segmentation header */
1938 		*hdr_len = (u8)((l4.tcp->doff * 4) + l4_offset);
1939 	}
1940 
1941 	/* pull values out of skb_shinfo */
1942 	gso_size = skb_shinfo(skb)->gso_size;
1943 	gso_segs = skb_shinfo(skb)->gso_segs;
1944 
1945 	/* update GSO size and bytecount with header size */
1946 	first->gso_segs = gso_segs;
1947 	first->bytecount += (first->gso_segs - 1) * *hdr_len;
1948 
1949 	/* find the field values */
1950 	cd_cmd = IAVF_TX_CTX_DESC_TSO;
1951 	cd_tso_len = skb->len - *hdr_len;
1952 	cd_mss = gso_size;
1953 	*cd_type_cmd_tso_mss |= (cd_cmd << IAVF_TXD_CTX_QW1_CMD_SHIFT) |
1954 				(cd_tso_len << IAVF_TXD_CTX_QW1_TSO_LEN_SHIFT) |
1955 				(cd_mss << IAVF_TXD_CTX_QW1_MSS_SHIFT);
1956 	return 1;
1957 }
1958 
1959 /**
1960  * iavf_tx_enable_csum - Enable Tx checksum offloads
1961  * @skb: send buffer
1962  * @tx_flags: pointer to Tx flags currently set
1963  * @td_cmd: Tx descriptor command bits to set
1964  * @td_offset: Tx descriptor header offsets to set
1965  * @tx_ring: Tx descriptor ring
1966  * @cd_tunneling: ptr to context desc bits
1967  **/
1968 static int iavf_tx_enable_csum(struct sk_buff *skb, u32 *tx_flags,
1969 			       u32 *td_cmd, u32 *td_offset,
1970 			       struct iavf_ring *tx_ring,
1971 			       u32 *cd_tunneling)
1972 {
1973 	union {
1974 		struct iphdr *v4;
1975 		struct ipv6hdr *v6;
1976 		unsigned char *hdr;
1977 	} ip;
1978 	union {
1979 		struct tcphdr *tcp;
1980 		struct udphdr *udp;
1981 		unsigned char *hdr;
1982 	} l4;
1983 	unsigned char *exthdr;
1984 	u32 offset, cmd = 0;
1985 	__be16 frag_off;
1986 	u8 l4_proto = 0;
1987 
1988 	if (skb->ip_summed != CHECKSUM_PARTIAL)
1989 		return 0;
1990 
1991 	ip.hdr = skb_network_header(skb);
1992 	l4.hdr = skb_transport_header(skb);
1993 
1994 	/* compute outer L2 header size */
1995 	offset = ((ip.hdr - skb->data) / 2) << IAVF_TX_DESC_LENGTH_MACLEN_SHIFT;
1996 
1997 	if (skb->encapsulation) {
1998 		u32 tunnel = 0;
1999 		/* define outer network header type */
2000 		if (*tx_flags & IAVF_TX_FLAGS_IPV4) {
2001 			tunnel |= (*tx_flags & IAVF_TX_FLAGS_TSO) ?
2002 				  IAVF_TX_CTX_EXT_IP_IPV4 :
2003 				  IAVF_TX_CTX_EXT_IP_IPV4_NO_CSUM;
2004 
2005 			l4_proto = ip.v4->protocol;
2006 		} else if (*tx_flags & IAVF_TX_FLAGS_IPV6) {
2007 			tunnel |= IAVF_TX_CTX_EXT_IP_IPV6;
2008 
2009 			exthdr = ip.hdr + sizeof(*ip.v6);
2010 			l4_proto = ip.v6->nexthdr;
2011 			if (l4.hdr != exthdr)
2012 				ipv6_skip_exthdr(skb, exthdr - skb->data,
2013 						 &l4_proto, &frag_off);
2014 		}
2015 
2016 		/* define outer transport */
2017 		switch (l4_proto) {
2018 		case IPPROTO_UDP:
2019 			tunnel |= IAVF_TXD_CTX_UDP_TUNNELING;
2020 			*tx_flags |= IAVF_TX_FLAGS_VXLAN_TUNNEL;
2021 			break;
2022 		case IPPROTO_GRE:
2023 			tunnel |= IAVF_TXD_CTX_GRE_TUNNELING;
2024 			*tx_flags |= IAVF_TX_FLAGS_VXLAN_TUNNEL;
2025 			break;
2026 		case IPPROTO_IPIP:
2027 		case IPPROTO_IPV6:
2028 			*tx_flags |= IAVF_TX_FLAGS_VXLAN_TUNNEL;
2029 			l4.hdr = skb_inner_network_header(skb);
2030 			break;
2031 		default:
2032 			if (*tx_flags & IAVF_TX_FLAGS_TSO)
2033 				return -1;
2034 
2035 			skb_checksum_help(skb);
2036 			return 0;
2037 		}
2038 
2039 		/* compute outer L3 header size */
2040 		tunnel |= ((l4.hdr - ip.hdr) / 4) <<
2041 			  IAVF_TXD_CTX_QW0_EXT_IPLEN_SHIFT;
2042 
2043 		/* switch IP header pointer from outer to inner header */
2044 		ip.hdr = skb_inner_network_header(skb);
2045 
2046 		/* compute tunnel header size */
2047 		tunnel |= ((ip.hdr - l4.hdr) / 2) <<
2048 			  IAVF_TXD_CTX_QW0_NATLEN_SHIFT;
2049 
2050 		/* indicate if we need to offload outer UDP header */
2051 		if ((*tx_flags & IAVF_TX_FLAGS_TSO) &&
2052 		    !(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL) &&
2053 		    (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_TUNNEL_CSUM))
2054 			tunnel |= IAVF_TXD_CTX_QW0_L4T_CS_MASK;
2055 
2056 		/* record tunnel offload values */
2057 		*cd_tunneling |= tunnel;
2058 
2059 		/* switch L4 header pointer from outer to inner */
2060 		l4.hdr = skb_inner_transport_header(skb);
2061 		l4_proto = 0;
2062 
2063 		/* reset type as we transition from outer to inner headers */
2064 		*tx_flags &= ~(IAVF_TX_FLAGS_IPV4 | IAVF_TX_FLAGS_IPV6);
2065 		if (ip.v4->version == 4)
2066 			*tx_flags |= IAVF_TX_FLAGS_IPV4;
2067 		if (ip.v6->version == 6)
2068 			*tx_flags |= IAVF_TX_FLAGS_IPV6;
2069 	}
2070 
2071 	/* Enable IP checksum offloads */
2072 	if (*tx_flags & IAVF_TX_FLAGS_IPV4) {
2073 		l4_proto = ip.v4->protocol;
2074 		/* the stack computes the IP header already, the only time we
2075 		 * need the hardware to recompute it is in the case of TSO.
2076 		 */
2077 		cmd |= (*tx_flags & IAVF_TX_FLAGS_TSO) ?
2078 		       IAVF_TX_DESC_CMD_IIPT_IPV4_CSUM :
2079 		       IAVF_TX_DESC_CMD_IIPT_IPV4;
2080 	} else if (*tx_flags & IAVF_TX_FLAGS_IPV6) {
2081 		cmd |= IAVF_TX_DESC_CMD_IIPT_IPV6;
2082 
2083 		exthdr = ip.hdr + sizeof(*ip.v6);
2084 		l4_proto = ip.v6->nexthdr;
2085 		if (l4.hdr != exthdr)
2086 			ipv6_skip_exthdr(skb, exthdr - skb->data,
2087 					 &l4_proto, &frag_off);
2088 	}
2089 
2090 	/* compute inner L3 header size */
2091 	offset |= ((l4.hdr - ip.hdr) / 4) << IAVF_TX_DESC_LENGTH_IPLEN_SHIFT;
2092 
2093 	/* Enable L4 checksum offloads */
2094 	switch (l4_proto) {
2095 	case IPPROTO_TCP:
2096 		/* enable checksum offloads */
2097 		cmd |= IAVF_TX_DESC_CMD_L4T_EOFT_TCP;
2098 		offset |= l4.tcp->doff << IAVF_TX_DESC_LENGTH_L4_FC_LEN_SHIFT;
2099 		break;
2100 	case IPPROTO_SCTP:
2101 		/* enable SCTP checksum offload */
2102 		cmd |= IAVF_TX_DESC_CMD_L4T_EOFT_SCTP;
2103 		offset |= (sizeof(struct sctphdr) >> 2) <<
2104 			  IAVF_TX_DESC_LENGTH_L4_FC_LEN_SHIFT;
2105 		break;
2106 	case IPPROTO_UDP:
2107 		/* enable UDP checksum offload */
2108 		cmd |= IAVF_TX_DESC_CMD_L4T_EOFT_UDP;
2109 		offset |= (sizeof(struct udphdr) >> 2) <<
2110 			  IAVF_TX_DESC_LENGTH_L4_FC_LEN_SHIFT;
2111 		break;
2112 	default:
2113 		if (*tx_flags & IAVF_TX_FLAGS_TSO)
2114 			return -1;
2115 		skb_checksum_help(skb);
2116 		return 0;
2117 	}
2118 
2119 	*td_cmd |= cmd;
2120 	*td_offset |= offset;
2121 
2122 	return 1;
2123 }
2124 
2125 /**
2126  * iavf_create_tx_ctx - Build the Tx context descriptor
2127  * @tx_ring:  ring to create the descriptor on
2128  * @cd_type_cmd_tso_mss: Quad Word 1
2129  * @cd_tunneling: Quad Word 0 - bits 0-31
2130  * @cd_l2tag2: Quad Word 0 - bits 32-63
2131  **/
2132 static void iavf_create_tx_ctx(struct iavf_ring *tx_ring,
2133 			       const u64 cd_type_cmd_tso_mss,
2134 			       const u32 cd_tunneling, const u32 cd_l2tag2)
2135 {
2136 	struct iavf_tx_context_desc *context_desc;
2137 	int i = tx_ring->next_to_use;
2138 
2139 	if ((cd_type_cmd_tso_mss == IAVF_TX_DESC_DTYPE_CONTEXT) &&
2140 	    !cd_tunneling && !cd_l2tag2)
2141 		return;
2142 
2143 	/* grab the next descriptor */
2144 	context_desc = IAVF_TX_CTXTDESC(tx_ring, i);
2145 
2146 	i++;
2147 	tx_ring->next_to_use = (i < tx_ring->count) ? i : 0;
2148 
2149 	/* cpu_to_le32 and assign to struct fields */
2150 	context_desc->tunneling_params = cpu_to_le32(cd_tunneling);
2151 	context_desc->l2tag2 = cpu_to_le16(cd_l2tag2);
2152 	context_desc->rsvd = cpu_to_le16(0);
2153 	context_desc->type_cmd_tso_mss = cpu_to_le64(cd_type_cmd_tso_mss);
2154 }
2155 
2156 /**
2157  * __iavf_chk_linearize - Check if there are more than 8 buffers per packet
2158  * @skb:      send buffer
2159  *
2160  * Note: Our HW can't DMA more than 8 buffers to build a packet on the wire
2161  * and so we need to figure out the cases where we need to linearize the skb.
2162  *
2163  * For TSO we need to count the TSO header and segment payload separately.
2164  * As such we need to check cases where we have 7 fragments or more as we
2165  * can potentially require 9 DMA transactions, 1 for the TSO header, 1 for
2166  * the segment payload in the first descriptor, and another 7 for the
2167  * fragments.
2168  **/
2169 bool __iavf_chk_linearize(struct sk_buff *skb)
2170 {
2171 	const skb_frag_t *frag, *stale;
2172 	int nr_frags, sum;
2173 
2174 	/* no need to check if number of frags is less than 7 */
2175 	nr_frags = skb_shinfo(skb)->nr_frags;
2176 	if (nr_frags < (IAVF_MAX_BUFFER_TXD - 1))
2177 		return false;
2178 
2179 	/* We need to walk through the list and validate that each group
2180 	 * of 6 fragments totals at least gso_size.
2181 	 */
2182 	nr_frags -= IAVF_MAX_BUFFER_TXD - 2;
2183 	frag = &skb_shinfo(skb)->frags[0];
2184 
2185 	/* Initialize size to the negative value of gso_size minus 1.  We
2186 	 * use this as the worst case scenerio in which the frag ahead
2187 	 * of us only provides one byte which is why we are limited to 6
2188 	 * descriptors for a single transmit as the header and previous
2189 	 * fragment are already consuming 2 descriptors.
2190 	 */
2191 	sum = 1 - skb_shinfo(skb)->gso_size;
2192 
2193 	/* Add size of frags 0 through 4 to create our initial sum */
2194 	sum += skb_frag_size(frag++);
2195 	sum += skb_frag_size(frag++);
2196 	sum += skb_frag_size(frag++);
2197 	sum += skb_frag_size(frag++);
2198 	sum += skb_frag_size(frag++);
2199 
2200 	/* Walk through fragments adding latest fragment, testing it, and
2201 	 * then removing stale fragments from the sum.
2202 	 */
2203 	for (stale = &skb_shinfo(skb)->frags[0];; stale++) {
2204 		int stale_size = skb_frag_size(stale);
2205 
2206 		sum += skb_frag_size(frag++);
2207 
2208 		/* The stale fragment may present us with a smaller
2209 		 * descriptor than the actual fragment size. To account
2210 		 * for that we need to remove all the data on the front and
2211 		 * figure out what the remainder would be in the last
2212 		 * descriptor associated with the fragment.
2213 		 */
2214 		if (stale_size > IAVF_MAX_DATA_PER_TXD) {
2215 			int align_pad = -(skb_frag_off(stale)) &
2216 					(IAVF_MAX_READ_REQ_SIZE - 1);
2217 
2218 			sum -= align_pad;
2219 			stale_size -= align_pad;
2220 
2221 			do {
2222 				sum -= IAVF_MAX_DATA_PER_TXD_ALIGNED;
2223 				stale_size -= IAVF_MAX_DATA_PER_TXD_ALIGNED;
2224 			} while (stale_size > IAVF_MAX_DATA_PER_TXD);
2225 		}
2226 
2227 		/* if sum is negative we failed to make sufficient progress */
2228 		if (sum < 0)
2229 			return true;
2230 
2231 		if (!nr_frags--)
2232 			break;
2233 
2234 		sum -= stale_size;
2235 	}
2236 
2237 	return false;
2238 }
2239 
2240 /**
2241  * __iavf_maybe_stop_tx - 2nd level check for tx stop conditions
2242  * @tx_ring: the ring to be checked
2243  * @size:    the size buffer we want to assure is available
2244  *
2245  * Returns -EBUSY if a stop is needed, else 0
2246  **/
2247 int __iavf_maybe_stop_tx(struct iavf_ring *tx_ring, int size)
2248 {
2249 	netif_stop_subqueue(tx_ring->netdev, tx_ring->queue_index);
2250 	/* Memory barrier before checking head and tail */
2251 	smp_mb();
2252 
2253 	/* Check again in a case another CPU has just made room available. */
2254 	if (likely(IAVF_DESC_UNUSED(tx_ring) < size))
2255 		return -EBUSY;
2256 
2257 	/* A reprieve! - use start_queue because it doesn't call schedule */
2258 	netif_start_subqueue(tx_ring->netdev, tx_ring->queue_index);
2259 	++tx_ring->tx_stats.restart_queue;
2260 	return 0;
2261 }
2262 
2263 /**
2264  * iavf_tx_map - Build the Tx descriptor
2265  * @tx_ring:  ring to send buffer on
2266  * @skb:      send buffer
2267  * @first:    first buffer info buffer to use
2268  * @tx_flags: collected send information
2269  * @hdr_len:  size of the packet header
2270  * @td_cmd:   the command field in the descriptor
2271  * @td_offset: offset for checksum or crc
2272  **/
2273 static void iavf_tx_map(struct iavf_ring *tx_ring, struct sk_buff *skb,
2274 			struct iavf_tx_buffer *first, u32 tx_flags,
2275 			const u8 hdr_len, u32 td_cmd, u32 td_offset)
2276 {
2277 	unsigned int data_len = skb->data_len;
2278 	unsigned int size = skb_headlen(skb);
2279 	skb_frag_t *frag;
2280 	struct iavf_tx_buffer *tx_bi;
2281 	struct iavf_tx_desc *tx_desc;
2282 	u16 i = tx_ring->next_to_use;
2283 	u32 td_tag = 0;
2284 	dma_addr_t dma;
2285 
2286 	if (tx_flags & IAVF_TX_FLAGS_HW_VLAN) {
2287 		td_cmd |= IAVF_TX_DESC_CMD_IL2TAG1;
2288 		td_tag = FIELD_GET(IAVF_TX_FLAGS_VLAN_MASK, tx_flags);
2289 	}
2290 
2291 	first->tx_flags = tx_flags;
2292 
2293 	dma = dma_map_single(tx_ring->dev, skb->data, size, DMA_TO_DEVICE);
2294 
2295 	tx_desc = IAVF_TX_DESC(tx_ring, i);
2296 	tx_bi = first;
2297 
2298 	for (frag = &skb_shinfo(skb)->frags[0];; frag++) {
2299 		unsigned int max_data = IAVF_MAX_DATA_PER_TXD_ALIGNED;
2300 
2301 		if (dma_mapping_error(tx_ring->dev, dma))
2302 			goto dma_error;
2303 
2304 		/* record length, and DMA address */
2305 		dma_unmap_len_set(tx_bi, len, size);
2306 		dma_unmap_addr_set(tx_bi, dma, dma);
2307 
2308 		/* align size to end of page */
2309 		max_data += -dma & (IAVF_MAX_READ_REQ_SIZE - 1);
2310 		tx_desc->buffer_addr = cpu_to_le64(dma);
2311 
2312 		while (unlikely(size > IAVF_MAX_DATA_PER_TXD)) {
2313 			tx_desc->cmd_type_offset_bsz =
2314 				build_ctob(td_cmd, td_offset,
2315 					   max_data, td_tag);
2316 
2317 			tx_desc++;
2318 			i++;
2319 
2320 			if (i == tx_ring->count) {
2321 				tx_desc = IAVF_TX_DESC(tx_ring, 0);
2322 				i = 0;
2323 			}
2324 
2325 			dma += max_data;
2326 			size -= max_data;
2327 
2328 			max_data = IAVF_MAX_DATA_PER_TXD_ALIGNED;
2329 			tx_desc->buffer_addr = cpu_to_le64(dma);
2330 		}
2331 
2332 		if (likely(!data_len))
2333 			break;
2334 
2335 		tx_desc->cmd_type_offset_bsz = build_ctob(td_cmd, td_offset,
2336 							  size, td_tag);
2337 
2338 		tx_desc++;
2339 		i++;
2340 
2341 		if (i == tx_ring->count) {
2342 			tx_desc = IAVF_TX_DESC(tx_ring, 0);
2343 			i = 0;
2344 		}
2345 
2346 		size = skb_frag_size(frag);
2347 		data_len -= size;
2348 
2349 		dma = skb_frag_dma_map(tx_ring->dev, frag, 0, size,
2350 				       DMA_TO_DEVICE);
2351 
2352 		tx_bi = &tx_ring->tx_bi[i];
2353 	}
2354 
2355 	netdev_tx_sent_queue(txring_txq(tx_ring), first->bytecount);
2356 
2357 	i++;
2358 	if (i == tx_ring->count)
2359 		i = 0;
2360 
2361 	tx_ring->next_to_use = i;
2362 
2363 	iavf_maybe_stop_tx(tx_ring, DESC_NEEDED);
2364 
2365 	/* write last descriptor with RS and EOP bits */
2366 	td_cmd |= IAVF_TXD_CMD;
2367 	tx_desc->cmd_type_offset_bsz =
2368 			build_ctob(td_cmd, td_offset, size, td_tag);
2369 
2370 	skb_tx_timestamp(skb);
2371 
2372 	/* Force memory writes to complete before letting h/w know there
2373 	 * are new descriptors to fetch.
2374 	 *
2375 	 * We also use this memory barrier to make certain all of the
2376 	 * status bits have been updated before next_to_watch is written.
2377 	 */
2378 	wmb();
2379 
2380 	/* set next_to_watch value indicating a packet is present */
2381 	first->next_to_watch = tx_desc;
2382 
2383 	/* notify HW of packet */
2384 	if (netif_xmit_stopped(txring_txq(tx_ring)) || !netdev_xmit_more()) {
2385 		writel(i, tx_ring->tail);
2386 	}
2387 
2388 	return;
2389 
2390 dma_error:
2391 	dev_info(tx_ring->dev, "TX DMA map failed\n");
2392 
2393 	/* clear dma mappings for failed tx_bi map */
2394 	for (;;) {
2395 		tx_bi = &tx_ring->tx_bi[i];
2396 		iavf_unmap_and_free_tx_resource(tx_ring, tx_bi);
2397 		if (tx_bi == first)
2398 			break;
2399 		if (i == 0)
2400 			i = tx_ring->count;
2401 		i--;
2402 	}
2403 
2404 	tx_ring->next_to_use = i;
2405 }
2406 
2407 /**
2408  * iavf_xmit_frame_ring - Sends buffer on Tx ring
2409  * @skb:     send buffer
2410  * @tx_ring: ring to send buffer on
2411  *
2412  * Returns NETDEV_TX_OK if sent, else an error code
2413  **/
2414 static netdev_tx_t iavf_xmit_frame_ring(struct sk_buff *skb,
2415 					struct iavf_ring *tx_ring)
2416 {
2417 	u64 cd_type_cmd_tso_mss = IAVF_TX_DESC_DTYPE_CONTEXT;
2418 	u32 cd_tunneling = 0, cd_l2tag2 = 0;
2419 	struct iavf_tx_buffer *first;
2420 	u32 td_offset = 0;
2421 	u32 tx_flags = 0;
2422 	__be16 protocol;
2423 	u32 td_cmd = 0;
2424 	u8 hdr_len = 0;
2425 	int tso, count;
2426 
2427 	/* prefetch the data, we'll need it later */
2428 	prefetch(skb->data);
2429 
2430 	iavf_trace(xmit_frame_ring, skb, tx_ring);
2431 
2432 	count = iavf_xmit_descriptor_count(skb);
2433 	if (iavf_chk_linearize(skb, count)) {
2434 		if (__skb_linearize(skb)) {
2435 			dev_kfree_skb_any(skb);
2436 			return NETDEV_TX_OK;
2437 		}
2438 		count = iavf_txd_use_count(skb->len);
2439 		tx_ring->tx_stats.tx_linearize++;
2440 	}
2441 
2442 	/* need: 1 descriptor per page * PAGE_SIZE/IAVF_MAX_DATA_PER_TXD,
2443 	 *       + 1 desc for skb_head_len/IAVF_MAX_DATA_PER_TXD,
2444 	 *       + 4 desc gap to avoid the cache line where head is,
2445 	 *       + 1 desc for context descriptor,
2446 	 * otherwise try next time
2447 	 */
2448 	if (iavf_maybe_stop_tx(tx_ring, count + 4 + 1)) {
2449 		tx_ring->tx_stats.tx_busy++;
2450 		return NETDEV_TX_BUSY;
2451 	}
2452 
2453 	/* record the location of the first descriptor for this packet */
2454 	first = &tx_ring->tx_bi[tx_ring->next_to_use];
2455 	first->skb = skb;
2456 	first->bytecount = skb->len;
2457 	first->gso_segs = 1;
2458 
2459 	/* prepare the xmit flags */
2460 	iavf_tx_prepare_vlan_flags(skb, tx_ring, &tx_flags);
2461 	if (tx_flags & IAVF_TX_FLAGS_HW_OUTER_SINGLE_VLAN) {
2462 		cd_type_cmd_tso_mss |= IAVF_TX_CTX_DESC_IL2TAG2 <<
2463 			IAVF_TXD_CTX_QW1_CMD_SHIFT;
2464 		cd_l2tag2 = FIELD_GET(IAVF_TX_FLAGS_VLAN_MASK, tx_flags);
2465 	}
2466 
2467 	/* obtain protocol of skb */
2468 	protocol = vlan_get_protocol(skb);
2469 
2470 	/* setup IPv4/IPv6 offloads */
2471 	if (protocol == htons(ETH_P_IP))
2472 		tx_flags |= IAVF_TX_FLAGS_IPV4;
2473 	else if (protocol == htons(ETH_P_IPV6))
2474 		tx_flags |= IAVF_TX_FLAGS_IPV6;
2475 
2476 	tso = iavf_tso(first, &hdr_len, &cd_type_cmd_tso_mss);
2477 
2478 	if (tso < 0)
2479 		goto out_drop;
2480 	else if (tso)
2481 		tx_flags |= IAVF_TX_FLAGS_TSO;
2482 
2483 	/* Always offload the checksum, since it's in the data descriptor */
2484 	tso = iavf_tx_enable_csum(skb, &tx_flags, &td_cmd, &td_offset,
2485 				  tx_ring, &cd_tunneling);
2486 	if (tso < 0)
2487 		goto out_drop;
2488 
2489 	/* always enable CRC insertion offload */
2490 	td_cmd |= IAVF_TX_DESC_CMD_ICRC;
2491 
2492 	iavf_create_tx_ctx(tx_ring, cd_type_cmd_tso_mss,
2493 			   cd_tunneling, cd_l2tag2);
2494 
2495 	iavf_tx_map(tx_ring, skb, first, tx_flags, hdr_len,
2496 		    td_cmd, td_offset);
2497 
2498 	return NETDEV_TX_OK;
2499 
2500 out_drop:
2501 	iavf_trace(xmit_frame_ring_drop, first->skb, tx_ring);
2502 	dev_kfree_skb_any(first->skb);
2503 	first->skb = NULL;
2504 	return NETDEV_TX_OK;
2505 }
2506 
2507 /**
2508  * iavf_xmit_frame - Selects the correct VSI and Tx queue to send buffer
2509  * @skb:    send buffer
2510  * @netdev: network interface device structure
2511  *
2512  * Returns NETDEV_TX_OK if sent, else an error code
2513  **/
2514 netdev_tx_t iavf_xmit_frame(struct sk_buff *skb, struct net_device *netdev)
2515 {
2516 	struct iavf_adapter *adapter = netdev_priv(netdev);
2517 	struct iavf_ring *tx_ring = &adapter->tx_rings[skb->queue_mapping];
2518 
2519 	/* hardware can't handle really short frames, hardware padding works
2520 	 * beyond this point
2521 	 */
2522 	if (unlikely(skb->len < IAVF_MIN_TX_LEN)) {
2523 		if (skb_pad(skb, IAVF_MIN_TX_LEN - skb->len))
2524 			return NETDEV_TX_OK;
2525 		skb->len = IAVF_MIN_TX_LEN;
2526 		skb_set_tail_pointer(skb, IAVF_MIN_TX_LEN);
2527 	}
2528 
2529 	return iavf_xmit_frame_ring(skb, tx_ring);
2530 }
2531