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