net/virtio: add Rx descriptor check
[dpdk.git] / drivers / net / virtio / virtio_rxtx.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include <stdint.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <errno.h>
39
40 #include <rte_cycles.h>
41 #include <rte_memory.h>
42 #include <rte_memzone.h>
43 #include <rte_branch_prediction.h>
44 #include <rte_mempool.h>
45 #include <rte_malloc.h>
46 #include <rte_mbuf.h>
47 #include <rte_ether.h>
48 #include <rte_ethdev.h>
49 #include <rte_prefetch.h>
50 #include <rte_string_fns.h>
51 #include <rte_errno.h>
52 #include <rte_byteorder.h>
53 #include <rte_cpuflags.h>
54 #include <rte_net.h>
55 #include <rte_ip.h>
56 #include <rte_udp.h>
57 #include <rte_tcp.h>
58
59 #include "virtio_logs.h"
60 #include "virtio_ethdev.h"
61 #include "virtio_pci.h"
62 #include "virtqueue.h"
63 #include "virtio_rxtx.h"
64
65 #ifdef RTE_LIBRTE_VIRTIO_DEBUG_DUMP
66 #define VIRTIO_DUMP_PACKET(m, len) rte_pktmbuf_dump(stdout, m, len)
67 #else
68 #define  VIRTIO_DUMP_PACKET(m, len) do { } while (0)
69 #endif
70
71
72 #define VIRTIO_SIMPLE_FLAGS ((uint32_t)ETH_TXQ_FLAGS_NOMULTSEGS | \
73         ETH_TXQ_FLAGS_NOOFFLOADS)
74
75 int
76 virtio_dev_rx_queue_done(void *rxq, uint16_t offset)
77 {
78         struct virtnet_rx *rxvq = rxq;
79         struct virtqueue *vq = rxvq->vq;
80
81         return VIRTQUEUE_NUSED(vq) >= offset;
82 }
83
84 static void
85 vq_ring_free_chain(struct virtqueue *vq, uint16_t desc_idx)
86 {
87         struct vring_desc *dp, *dp_tail;
88         struct vq_desc_extra *dxp;
89         uint16_t desc_idx_last = desc_idx;
90
91         dp  = &vq->vq_ring.desc[desc_idx];
92         dxp = &vq->vq_descx[desc_idx];
93         vq->vq_free_cnt = (uint16_t)(vq->vq_free_cnt + dxp->ndescs);
94         if ((dp->flags & VRING_DESC_F_INDIRECT) == 0) {
95                 while (dp->flags & VRING_DESC_F_NEXT) {
96                         desc_idx_last = dp->next;
97                         dp = &vq->vq_ring.desc[dp->next];
98                 }
99         }
100         dxp->ndescs = 0;
101
102         /*
103          * We must append the existing free chain, if any, to the end of
104          * newly freed chain. If the virtqueue was completely used, then
105          * head would be VQ_RING_DESC_CHAIN_END (ASSERTed above).
106          */
107         if (vq->vq_desc_tail_idx == VQ_RING_DESC_CHAIN_END) {
108                 vq->vq_desc_head_idx = desc_idx;
109         } else {
110                 dp_tail = &vq->vq_ring.desc[vq->vq_desc_tail_idx];
111                 dp_tail->next = desc_idx;
112         }
113
114         vq->vq_desc_tail_idx = desc_idx_last;
115         dp->next = VQ_RING_DESC_CHAIN_END;
116 }
117
118 static uint16_t
119 virtqueue_dequeue_burst_rx(struct virtqueue *vq, struct rte_mbuf **rx_pkts,
120                            uint32_t *len, uint16_t num)
121 {
122         struct vring_used_elem *uep;
123         struct rte_mbuf *cookie;
124         uint16_t used_idx, desc_idx;
125         uint16_t i;
126
127         /*  Caller does the check */
128         for (i = 0; i < num ; i++) {
129                 used_idx = (uint16_t)(vq->vq_used_cons_idx & (vq->vq_nentries - 1));
130                 uep = &vq->vq_ring.used->ring[used_idx];
131                 desc_idx = (uint16_t) uep->id;
132                 len[i] = uep->len;
133                 cookie = (struct rte_mbuf *)vq->vq_descx[desc_idx].cookie;
134
135                 if (unlikely(cookie == NULL)) {
136                         PMD_DRV_LOG(ERR, "vring descriptor with no mbuf cookie at %u\n",
137                                 vq->vq_used_cons_idx);
138                         break;
139                 }
140
141                 rte_prefetch0(cookie);
142                 rte_packet_prefetch(rte_pktmbuf_mtod(cookie, void *));
143                 rx_pkts[i]  = cookie;
144                 vq->vq_used_cons_idx++;
145                 vq_ring_free_chain(vq, desc_idx);
146                 vq->vq_descx[desc_idx].cookie = NULL;
147         }
148
149         return i;
150 }
151
152 #ifndef DEFAULT_TX_FREE_THRESH
153 #define DEFAULT_TX_FREE_THRESH 32
154 #endif
155
156 /* Cleanup from completed transmits. */
157 static void
158 virtio_xmit_cleanup(struct virtqueue *vq, uint16_t num)
159 {
160         uint16_t i, used_idx, desc_idx;
161         for (i = 0; i < num; i++) {
162                 struct vring_used_elem *uep;
163                 struct vq_desc_extra *dxp;
164
165                 used_idx = (uint16_t)(vq->vq_used_cons_idx & (vq->vq_nentries - 1));
166                 uep = &vq->vq_ring.used->ring[used_idx];
167
168                 desc_idx = (uint16_t) uep->id;
169                 dxp = &vq->vq_descx[desc_idx];
170                 vq->vq_used_cons_idx++;
171                 vq_ring_free_chain(vq, desc_idx);
172
173                 if (dxp->cookie != NULL) {
174                         rte_pktmbuf_free(dxp->cookie);
175                         dxp->cookie = NULL;
176                 }
177         }
178 }
179
180
181 static inline int
182 virtqueue_enqueue_recv_refill(struct virtqueue *vq, struct rte_mbuf *cookie)
183 {
184         struct vq_desc_extra *dxp;
185         struct virtio_hw *hw = vq->hw;
186         struct vring_desc *start_dp;
187         uint16_t needed = 1;
188         uint16_t head_idx, idx;
189
190         if (unlikely(vq->vq_free_cnt == 0))
191                 return -ENOSPC;
192         if (unlikely(vq->vq_free_cnt < needed))
193                 return -EMSGSIZE;
194
195         head_idx = vq->vq_desc_head_idx;
196         if (unlikely(head_idx >= vq->vq_nentries))
197                 return -EFAULT;
198
199         idx = head_idx;
200         dxp = &vq->vq_descx[idx];
201         dxp->cookie = (void *)cookie;
202         dxp->ndescs = needed;
203
204         start_dp = vq->vq_ring.desc;
205         start_dp[idx].addr =
206                 VIRTIO_MBUF_ADDR(cookie, vq) +
207                 RTE_PKTMBUF_HEADROOM - hw->vtnet_hdr_size;
208         start_dp[idx].len =
209                 cookie->buf_len - RTE_PKTMBUF_HEADROOM + hw->vtnet_hdr_size;
210         start_dp[idx].flags =  VRING_DESC_F_WRITE;
211         idx = start_dp[idx].next;
212         vq->vq_desc_head_idx = idx;
213         if (vq->vq_desc_head_idx == VQ_RING_DESC_CHAIN_END)
214                 vq->vq_desc_tail_idx = idx;
215         vq->vq_free_cnt = (uint16_t)(vq->vq_free_cnt - needed);
216         vq_update_avail_ring(vq, head_idx);
217
218         return 0;
219 }
220
221 /* When doing TSO, the IP length is not included in the pseudo header
222  * checksum of the packet given to the PMD, but for virtio it is
223  * expected.
224  */
225 static void
226 virtio_tso_fix_cksum(struct rte_mbuf *m)
227 {
228         /* common case: header is not fragmented */
229         if (likely(rte_pktmbuf_data_len(m) >= m->l2_len + m->l3_len +
230                         m->l4_len)) {
231                 struct ipv4_hdr *iph;
232                 struct ipv6_hdr *ip6h;
233                 struct tcp_hdr *th;
234                 uint16_t prev_cksum, new_cksum, ip_len, ip_paylen;
235                 uint32_t tmp;
236
237                 iph = rte_pktmbuf_mtod_offset(m, struct ipv4_hdr *, m->l2_len);
238                 th = RTE_PTR_ADD(iph, m->l3_len);
239                 if ((iph->version_ihl >> 4) == 4) {
240                         iph->hdr_checksum = 0;
241                         iph->hdr_checksum = rte_ipv4_cksum(iph);
242                         ip_len = iph->total_length;
243                         ip_paylen = rte_cpu_to_be_16(rte_be_to_cpu_16(ip_len) -
244                                 m->l3_len);
245                 } else {
246                         ip6h = (struct ipv6_hdr *)iph;
247                         ip_paylen = ip6h->payload_len;
248                 }
249
250                 /* calculate the new phdr checksum not including ip_paylen */
251                 prev_cksum = th->cksum;
252                 tmp = prev_cksum;
253                 tmp += ip_paylen;
254                 tmp = (tmp & 0xffff) + (tmp >> 16);
255                 new_cksum = tmp;
256
257                 /* replace it in the packet */
258                 th->cksum = new_cksum;
259         }
260 }
261
262 static inline int
263 tx_offload_enabled(struct virtio_hw *hw)
264 {
265         return vtpci_with_feature(hw, VIRTIO_NET_F_CSUM) ||
266                 vtpci_with_feature(hw, VIRTIO_NET_F_HOST_TSO4) ||
267                 vtpci_with_feature(hw, VIRTIO_NET_F_HOST_TSO6);
268 }
269
270 static inline void
271 virtqueue_enqueue_xmit(struct virtnet_tx *txvq, struct rte_mbuf *cookie,
272                        uint16_t needed, int use_indirect, int can_push)
273 {
274         struct virtio_tx_region *txr = txvq->virtio_net_hdr_mz->addr;
275         struct vq_desc_extra *dxp;
276         struct virtqueue *vq = txvq->vq;
277         struct vring_desc *start_dp;
278         uint16_t seg_num = cookie->nb_segs;
279         uint16_t head_idx, idx;
280         uint16_t head_size = vq->hw->vtnet_hdr_size;
281         struct virtio_net_hdr *hdr;
282         int offload;
283
284         offload = tx_offload_enabled(vq->hw);
285         head_idx = vq->vq_desc_head_idx;
286         idx = head_idx;
287         dxp = &vq->vq_descx[idx];
288         dxp->cookie = (void *)cookie;
289         dxp->ndescs = needed;
290
291         start_dp = vq->vq_ring.desc;
292
293         if (can_push) {
294                 /* prepend cannot fail, checked by caller */
295                 hdr = (struct virtio_net_hdr *)
296                         rte_pktmbuf_prepend(cookie, head_size);
297                 /* if offload disabled, it is not zeroed below, do it now */
298                 if (offload == 0)
299                         memset(hdr, 0, head_size);
300         } else if (use_indirect) {
301                 /* setup tx ring slot to point to indirect
302                  * descriptor list stored in reserved region.
303                  *
304                  * the first slot in indirect ring is already preset
305                  * to point to the header in reserved region
306                  */
307                 start_dp[idx].addr  = txvq->virtio_net_hdr_mem +
308                         RTE_PTR_DIFF(&txr[idx].tx_indir, txr);
309                 start_dp[idx].len   = (seg_num + 1) * sizeof(struct vring_desc);
310                 start_dp[idx].flags = VRING_DESC_F_INDIRECT;
311                 hdr = (struct virtio_net_hdr *)&txr[idx].tx_hdr;
312
313                 /* loop below will fill in rest of the indirect elements */
314                 start_dp = txr[idx].tx_indir;
315                 idx = 1;
316         } else {
317                 /* setup first tx ring slot to point to header
318                  * stored in reserved region.
319                  */
320                 start_dp[idx].addr  = txvq->virtio_net_hdr_mem +
321                         RTE_PTR_DIFF(&txr[idx].tx_hdr, txr);
322                 start_dp[idx].len   = vq->hw->vtnet_hdr_size;
323                 start_dp[idx].flags = VRING_DESC_F_NEXT;
324                 hdr = (struct virtio_net_hdr *)&txr[idx].tx_hdr;
325
326                 idx = start_dp[idx].next;
327         }
328
329         /* Checksum Offload / TSO */
330         if (offload) {
331                 if (cookie->ol_flags & PKT_TX_TCP_SEG)
332                         cookie->ol_flags |= PKT_TX_TCP_CKSUM;
333
334                 switch (cookie->ol_flags & PKT_TX_L4_MASK) {
335                 case PKT_TX_UDP_CKSUM:
336                         hdr->csum_start = cookie->l2_len + cookie->l3_len;
337                         hdr->csum_offset = offsetof(struct udp_hdr,
338                                 dgram_cksum);
339                         hdr->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
340                         break;
341
342                 case PKT_TX_TCP_CKSUM:
343                         hdr->csum_start = cookie->l2_len + cookie->l3_len;
344                         hdr->csum_offset = offsetof(struct tcp_hdr, cksum);
345                         hdr->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
346                         break;
347
348                 default:
349                         hdr->csum_start = 0;
350                         hdr->csum_offset = 0;
351                         hdr->flags = 0;
352                         break;
353                 }
354
355                 /* TCP Segmentation Offload */
356                 if (cookie->ol_flags & PKT_TX_TCP_SEG) {
357                         virtio_tso_fix_cksum(cookie);
358                         hdr->gso_type = (cookie->ol_flags & PKT_TX_IPV6) ?
359                                 VIRTIO_NET_HDR_GSO_TCPV6 :
360                                 VIRTIO_NET_HDR_GSO_TCPV4;
361                         hdr->gso_size = cookie->tso_segsz;
362                         hdr->hdr_len =
363                                 cookie->l2_len +
364                                 cookie->l3_len +
365                                 cookie->l4_len;
366                 } else {
367                         hdr->gso_type = 0;
368                         hdr->gso_size = 0;
369                         hdr->hdr_len = 0;
370                 }
371         }
372
373         do {
374                 start_dp[idx].addr  = VIRTIO_MBUF_DATA_DMA_ADDR(cookie, vq);
375                 start_dp[idx].len   = cookie->data_len;
376                 start_dp[idx].flags = cookie->next ? VRING_DESC_F_NEXT : 0;
377                 idx = start_dp[idx].next;
378         } while ((cookie = cookie->next) != NULL);
379
380         if (use_indirect)
381                 idx = vq->vq_ring.desc[head_idx].next;
382
383         vq->vq_desc_head_idx = idx;
384         if (vq->vq_desc_head_idx == VQ_RING_DESC_CHAIN_END)
385                 vq->vq_desc_tail_idx = idx;
386         vq->vq_free_cnt = (uint16_t)(vq->vq_free_cnt - needed);
387         vq_update_avail_ring(vq, head_idx);
388 }
389
390 void
391 virtio_dev_cq_start(struct rte_eth_dev *dev)
392 {
393         struct virtio_hw *hw = dev->data->dev_private;
394
395         if (hw->cvq && hw->cvq->vq) {
396                 VIRTQUEUE_DUMP((struct virtqueue *)hw->cvq->vq);
397         }
398 }
399
400 int
401 virtio_dev_rx_queue_setup(struct rte_eth_dev *dev,
402                         uint16_t queue_idx,
403                         uint16_t nb_desc,
404                         unsigned int socket_id __rte_unused,
405                         __rte_unused const struct rte_eth_rxconf *rx_conf,
406                         struct rte_mempool *mp)
407 {
408         uint16_t vtpci_queue_idx = 2 * queue_idx + VTNET_SQ_RQ_QUEUE_IDX;
409         struct virtio_hw *hw = dev->data->dev_private;
410         struct virtqueue *vq = hw->vqs[vtpci_queue_idx];
411         struct virtnet_rx *rxvq;
412         int error, nbufs;
413         struct rte_mbuf *m;
414         uint16_t desc_idx;
415
416         PMD_INIT_FUNC_TRACE();
417
418         if (nb_desc == 0 || nb_desc > vq->vq_nentries)
419                 nb_desc = vq->vq_nentries;
420         vq->vq_free_cnt = RTE_MIN(vq->vq_free_cnt, nb_desc);
421
422         rxvq = &vq->rxq;
423         rxvq->queue_id = queue_idx;
424         rxvq->mpool = mp;
425         if (rxvq->mpool == NULL) {
426                 rte_exit(EXIT_FAILURE,
427                         "Cannot allocate mbufs for rx virtqueue");
428         }
429         dev->data->rx_queues[queue_idx] = rxvq;
430
431
432         /* Allocate blank mbufs for the each rx descriptor */
433         nbufs = 0;
434         error = ENOSPC;
435
436         if (hw->use_simple_rxtx) {
437                 for (desc_idx = 0; desc_idx < vq->vq_nentries;
438                      desc_idx++) {
439                         vq->vq_ring.avail->ring[desc_idx] = desc_idx;
440                         vq->vq_ring.desc[desc_idx].flags =
441                                 VRING_DESC_F_WRITE;
442                 }
443         }
444
445         memset(&rxvq->fake_mbuf, 0, sizeof(rxvq->fake_mbuf));
446         for (desc_idx = 0; desc_idx < RTE_PMD_VIRTIO_RX_MAX_BURST;
447              desc_idx++) {
448                 vq->sw_ring[vq->vq_nentries + desc_idx] =
449                         &rxvq->fake_mbuf;
450         }
451
452         while (!virtqueue_full(vq)) {
453                 m = rte_mbuf_raw_alloc(rxvq->mpool);
454                 if (m == NULL)
455                         break;
456
457                 /* Enqueue allocated buffers */
458                 if (hw->use_simple_rxtx)
459                         error = virtqueue_enqueue_recv_refill_simple(vq, m);
460                 else
461                         error = virtqueue_enqueue_recv_refill(vq, m);
462
463                 if (error) {
464                         rte_pktmbuf_free(m);
465                         break;
466                 }
467                 nbufs++;
468         }
469
470         vq_update_avail_idx(vq);
471
472         PMD_INIT_LOG(DEBUG, "Allocated %d bufs", nbufs);
473
474         virtio_rxq_vec_setup(rxvq);
475
476         VIRTQUEUE_DUMP(vq);
477
478         return 0;
479 }
480
481 static void
482 virtio_update_rxtx_handler(struct rte_eth_dev *dev,
483                            const struct rte_eth_txconf *tx_conf)
484 {
485         uint8_t use_simple_rxtx = 0;
486         struct virtio_hw *hw = dev->data->dev_private;
487
488 #if defined RTE_ARCH_X86
489         if (rte_cpu_get_flag_enabled(RTE_CPUFLAG_SSE3))
490                 use_simple_rxtx = 1;
491 #elif defined RTE_ARCH_ARM64 || defined CONFIG_RTE_ARCH_ARM
492         if (rte_cpu_get_flag_enabled(RTE_CPUFLAG_NEON))
493                 use_simple_rxtx = 1;
494 #endif
495         /* Use simple rx/tx func if single segment and no offloads */
496         if (use_simple_rxtx &&
497             (tx_conf->txq_flags & VIRTIO_SIMPLE_FLAGS) == VIRTIO_SIMPLE_FLAGS &&
498             !vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF)) {
499                 PMD_INIT_LOG(INFO, "Using simple rx/tx path");
500                 dev->tx_pkt_burst = virtio_xmit_pkts_simple;
501                 dev->rx_pkt_burst = virtio_recv_pkts_vec;
502                 hw->use_simple_rxtx = use_simple_rxtx;
503         }
504 }
505
506 /*
507  * struct rte_eth_dev *dev: Used to update dev
508  * uint16_t nb_desc: Defaults to values read from config space
509  * unsigned int socket_id: Used to allocate memzone
510  * const struct rte_eth_txconf *tx_conf: Used to setup tx engine
511  * uint16_t queue_idx: Just used as an index in dev txq list
512  */
513 int
514 virtio_dev_tx_queue_setup(struct rte_eth_dev *dev,
515                         uint16_t queue_idx,
516                         uint16_t nb_desc,
517                         unsigned int socket_id __rte_unused,
518                         const struct rte_eth_txconf *tx_conf)
519 {
520         uint8_t vtpci_queue_idx = 2 * queue_idx + VTNET_SQ_TQ_QUEUE_IDX;
521         struct virtio_hw *hw = dev->data->dev_private;
522         struct virtqueue *vq = hw->vqs[vtpci_queue_idx];
523         struct virtnet_tx *txvq;
524         uint16_t tx_free_thresh;
525         uint16_t desc_idx;
526
527         PMD_INIT_FUNC_TRACE();
528
529         virtio_update_rxtx_handler(dev, tx_conf);
530
531         if (nb_desc == 0 || nb_desc > vq->vq_nentries)
532                 nb_desc = vq->vq_nentries;
533         vq->vq_free_cnt = RTE_MIN(vq->vq_free_cnt, nb_desc);
534
535         txvq = &vq->txq;
536         txvq->queue_id = queue_idx;
537
538         tx_free_thresh = tx_conf->tx_free_thresh;
539         if (tx_free_thresh == 0)
540                 tx_free_thresh =
541                         RTE_MIN(vq->vq_nentries / 4, DEFAULT_TX_FREE_THRESH);
542
543         if (tx_free_thresh >= (vq->vq_nentries - 3)) {
544                 RTE_LOG(ERR, PMD, "tx_free_thresh must be less than the "
545                         "number of TX entries minus 3 (%u)."
546                         " (tx_free_thresh=%u port=%u queue=%u)\n",
547                         vq->vq_nentries - 3,
548                         tx_free_thresh, dev->data->port_id, queue_idx);
549                 return -EINVAL;
550         }
551
552         vq->vq_free_thresh = tx_free_thresh;
553
554         if (hw->use_simple_rxtx) {
555                 uint16_t mid_idx  = vq->vq_nentries >> 1;
556
557                 for (desc_idx = 0; desc_idx < mid_idx; desc_idx++) {
558                         vq->vq_ring.avail->ring[desc_idx] =
559                                 desc_idx + mid_idx;
560                         vq->vq_ring.desc[desc_idx + mid_idx].next =
561                                 desc_idx;
562                         vq->vq_ring.desc[desc_idx + mid_idx].addr =
563                                 txvq->virtio_net_hdr_mem +
564                                 offsetof(struct virtio_tx_region, tx_hdr);
565                         vq->vq_ring.desc[desc_idx + mid_idx].len =
566                                 vq->hw->vtnet_hdr_size;
567                         vq->vq_ring.desc[desc_idx + mid_idx].flags =
568                                 VRING_DESC_F_NEXT;
569                         vq->vq_ring.desc[desc_idx].flags = 0;
570                 }
571                 for (desc_idx = mid_idx; desc_idx < vq->vq_nentries;
572                      desc_idx++)
573                         vq->vq_ring.avail->ring[desc_idx] = desc_idx;
574         }
575
576         VIRTQUEUE_DUMP(vq);
577
578         dev->data->tx_queues[queue_idx] = txvq;
579         return 0;
580 }
581
582 static void
583 virtio_discard_rxbuf(struct virtqueue *vq, struct rte_mbuf *m)
584 {
585         int error;
586         /*
587          * Requeue the discarded mbuf. This should always be
588          * successful since it was just dequeued.
589          */
590         error = virtqueue_enqueue_recv_refill(vq, m);
591         if (unlikely(error)) {
592                 RTE_LOG(ERR, PMD, "cannot requeue discarded mbuf");
593                 rte_pktmbuf_free(m);
594         }
595 }
596
597 static void
598 virtio_update_packet_stats(struct virtnet_stats *stats, struct rte_mbuf *mbuf)
599 {
600         uint32_t s = mbuf->pkt_len;
601         struct ether_addr *ea;
602
603         if (s == 64) {
604                 stats->size_bins[1]++;
605         } else if (s > 64 && s < 1024) {
606                 uint32_t bin;
607
608                 /* count zeros, and offset into correct bin */
609                 bin = (sizeof(s) * 8) - __builtin_clz(s) - 5;
610                 stats->size_bins[bin]++;
611         } else {
612                 if (s < 64)
613                         stats->size_bins[0]++;
614                 else if (s < 1519)
615                         stats->size_bins[6]++;
616                 else if (s >= 1519)
617                         stats->size_bins[7]++;
618         }
619
620         ea = rte_pktmbuf_mtod(mbuf, struct ether_addr *);
621         if (is_multicast_ether_addr(ea)) {
622                 if (is_broadcast_ether_addr(ea))
623                         stats->broadcast++;
624                 else
625                         stats->multicast++;
626         }
627 }
628
629 /* Optionally fill offload information in structure */
630 static int
631 virtio_rx_offload(struct rte_mbuf *m, struct virtio_net_hdr *hdr)
632 {
633         struct rte_net_hdr_lens hdr_lens;
634         uint32_t hdrlen, ptype;
635         int l4_supported = 0;
636
637         /* nothing to do */
638         if (hdr->flags == 0 && hdr->gso_type == VIRTIO_NET_HDR_GSO_NONE)
639                 return 0;
640
641         m->ol_flags |= PKT_RX_IP_CKSUM_UNKNOWN;
642
643         ptype = rte_net_get_ptype(m, &hdr_lens, RTE_PTYPE_ALL_MASK);
644         m->packet_type = ptype;
645         if ((ptype & RTE_PTYPE_L4_MASK) == RTE_PTYPE_L4_TCP ||
646             (ptype & RTE_PTYPE_L4_MASK) == RTE_PTYPE_L4_UDP ||
647             (ptype & RTE_PTYPE_L4_MASK) == RTE_PTYPE_L4_SCTP)
648                 l4_supported = 1;
649
650         if (hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
651                 hdrlen = hdr_lens.l2_len + hdr_lens.l3_len + hdr_lens.l4_len;
652                 if (hdr->csum_start <= hdrlen && l4_supported) {
653                         m->ol_flags |= PKT_RX_L4_CKSUM_NONE;
654                 } else {
655                         /* Unknown proto or tunnel, do sw cksum. We can assume
656                          * the cksum field is in the first segment since the
657                          * buffers we provided to the host are large enough.
658                          * In case of SCTP, this will be wrong since it's a CRC
659                          * but there's nothing we can do.
660                          */
661                         uint16_t csum, off;
662
663                         rte_raw_cksum_mbuf(m, hdr->csum_start,
664                                 rte_pktmbuf_pkt_len(m) - hdr->csum_start,
665                                 &csum);
666                         if (likely(csum != 0xffff))
667                                 csum = ~csum;
668                         off = hdr->csum_offset + hdr->csum_start;
669                         if (rte_pktmbuf_data_len(m) >= off + 1)
670                                 *rte_pktmbuf_mtod_offset(m, uint16_t *,
671                                         off) = csum;
672                 }
673         } else if (hdr->flags & VIRTIO_NET_HDR_F_DATA_VALID && l4_supported) {
674                 m->ol_flags |= PKT_RX_L4_CKSUM_GOOD;
675         }
676
677         /* GSO request, save required information in mbuf */
678         if (hdr->gso_type != VIRTIO_NET_HDR_GSO_NONE) {
679                 /* Check unsupported modes */
680                 if ((hdr->gso_type & VIRTIO_NET_HDR_GSO_ECN) ||
681                     (hdr->gso_size == 0)) {
682                         return -EINVAL;
683                 }
684
685                 /* Update mss lengthes in mbuf */
686                 m->tso_segsz = hdr->gso_size;
687                 switch (hdr->gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
688                         case VIRTIO_NET_HDR_GSO_TCPV4:
689                         case VIRTIO_NET_HDR_GSO_TCPV6:
690                                 m->ol_flags |= PKT_RX_LRO | \
691                                         PKT_RX_L4_CKSUM_NONE;
692                                 break;
693                         default:
694                                 return -EINVAL;
695                 }
696         }
697
698         return 0;
699 }
700
701 static inline int
702 rx_offload_enabled(struct virtio_hw *hw)
703 {
704         return vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_CSUM) ||
705                 vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_TSO4) ||
706                 vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_TSO6);
707 }
708
709 #define VIRTIO_MBUF_BURST_SZ 64
710 #define DESC_PER_CACHELINE (RTE_CACHE_LINE_SIZE / sizeof(struct vring_desc))
711 uint16_t
712 virtio_recv_pkts(void *rx_queue, struct rte_mbuf **rx_pkts, uint16_t nb_pkts)
713 {
714         struct virtnet_rx *rxvq = rx_queue;
715         struct virtqueue *vq = rxvq->vq;
716         struct virtio_hw *hw;
717         struct rte_mbuf *rxm, *new_mbuf;
718         uint16_t nb_used, num, nb_rx;
719         uint32_t len[VIRTIO_MBUF_BURST_SZ];
720         struct rte_mbuf *rcv_pkts[VIRTIO_MBUF_BURST_SZ];
721         int error;
722         uint32_t i, nb_enqueued;
723         uint32_t hdr_size;
724         int offload;
725         struct virtio_net_hdr *hdr;
726
727         nb_used = VIRTQUEUE_NUSED(vq);
728
729         virtio_rmb();
730
731         num = (uint16_t)(likely(nb_used <= nb_pkts) ? nb_used : nb_pkts);
732         num = (uint16_t)(likely(num <= VIRTIO_MBUF_BURST_SZ) ? num : VIRTIO_MBUF_BURST_SZ);
733         if (likely(num > DESC_PER_CACHELINE))
734                 num = num - ((vq->vq_used_cons_idx + num) % DESC_PER_CACHELINE);
735
736         num = virtqueue_dequeue_burst_rx(vq, rcv_pkts, len, num);
737         PMD_RX_LOG(DEBUG, "used:%d dequeue:%d", nb_used, num);
738
739         hw = vq->hw;
740         nb_rx = 0;
741         nb_enqueued = 0;
742         hdr_size = hw->vtnet_hdr_size;
743         offload = rx_offload_enabled(hw);
744
745         for (i = 0; i < num ; i++) {
746                 rxm = rcv_pkts[i];
747
748                 PMD_RX_LOG(DEBUG, "packet len:%d", len[i]);
749
750                 if (unlikely(len[i] < hdr_size + ETHER_HDR_LEN)) {
751                         PMD_RX_LOG(ERR, "Packet drop");
752                         nb_enqueued++;
753                         virtio_discard_rxbuf(vq, rxm);
754                         rxvq->stats.errors++;
755                         continue;
756                 }
757
758                 rxm->port = rxvq->port_id;
759                 rxm->data_off = RTE_PKTMBUF_HEADROOM;
760                 rxm->ol_flags = 0;
761                 rxm->vlan_tci = 0;
762
763                 rxm->nb_segs = 1;
764                 rxm->next = NULL;
765                 rxm->pkt_len = (uint32_t)(len[i] - hdr_size);
766                 rxm->data_len = (uint16_t)(len[i] - hdr_size);
767
768                 hdr = (struct virtio_net_hdr *)((char *)rxm->buf_addr +
769                         RTE_PKTMBUF_HEADROOM - hdr_size);
770
771                 if (hw->vlan_strip)
772                         rte_vlan_strip(rxm);
773
774                 if (offload && virtio_rx_offload(rxm, hdr) < 0) {
775                         virtio_discard_rxbuf(vq, rxm);
776                         rxvq->stats.errors++;
777                         continue;
778                 }
779
780                 VIRTIO_DUMP_PACKET(rxm, rxm->data_len);
781
782                 rx_pkts[nb_rx++] = rxm;
783
784                 rxvq->stats.bytes += rx_pkts[nb_rx - 1]->pkt_len;
785                 virtio_update_packet_stats(&rxvq->stats, rxm);
786         }
787
788         rxvq->stats.packets += nb_rx;
789
790         /* Allocate new mbuf for the used descriptor */
791         error = ENOSPC;
792         while (likely(!virtqueue_full(vq))) {
793                 new_mbuf = rte_mbuf_raw_alloc(rxvq->mpool);
794                 if (unlikely(new_mbuf == NULL)) {
795                         struct rte_eth_dev *dev
796                                 = &rte_eth_devices[rxvq->port_id];
797                         dev->data->rx_mbuf_alloc_failed++;
798                         break;
799                 }
800                 error = virtqueue_enqueue_recv_refill(vq, new_mbuf);
801                 if (unlikely(error)) {
802                         rte_pktmbuf_free(new_mbuf);
803                         break;
804                 }
805                 nb_enqueued++;
806         }
807
808         if (likely(nb_enqueued)) {
809                 vq_update_avail_idx(vq);
810
811                 if (unlikely(virtqueue_kick_prepare(vq))) {
812                         virtqueue_notify(vq);
813                         PMD_RX_LOG(DEBUG, "Notified");
814                 }
815         }
816
817         return nb_rx;
818 }
819
820 uint16_t
821 virtio_recv_mergeable_pkts(void *rx_queue,
822                         struct rte_mbuf **rx_pkts,
823                         uint16_t nb_pkts)
824 {
825         struct virtnet_rx *rxvq = rx_queue;
826         struct virtqueue *vq = rxvq->vq;
827         struct virtio_hw *hw;
828         struct rte_mbuf *rxm, *new_mbuf;
829         uint16_t nb_used, num, nb_rx;
830         uint32_t len[VIRTIO_MBUF_BURST_SZ];
831         struct rte_mbuf *rcv_pkts[VIRTIO_MBUF_BURST_SZ];
832         struct rte_mbuf *prev;
833         int error;
834         uint32_t i, nb_enqueued;
835         uint32_t seg_num;
836         uint16_t extra_idx;
837         uint32_t seg_res;
838         uint32_t hdr_size;
839         int offload;
840
841         nb_used = VIRTQUEUE_NUSED(vq);
842
843         virtio_rmb();
844
845         PMD_RX_LOG(DEBUG, "used:%d", nb_used);
846
847         hw = vq->hw;
848         nb_rx = 0;
849         i = 0;
850         nb_enqueued = 0;
851         seg_num = 0;
852         extra_idx = 0;
853         seg_res = 0;
854         hdr_size = hw->vtnet_hdr_size;
855         offload = rx_offload_enabled(hw);
856
857         while (i < nb_used) {
858                 struct virtio_net_hdr_mrg_rxbuf *header;
859
860                 if (nb_rx == nb_pkts)
861                         break;
862
863                 num = virtqueue_dequeue_burst_rx(vq, rcv_pkts, len, 1);
864                 if (num != 1)
865                         continue;
866
867                 i++;
868
869                 PMD_RX_LOG(DEBUG, "dequeue:%d", num);
870                 PMD_RX_LOG(DEBUG, "packet len:%d", len[0]);
871
872                 rxm = rcv_pkts[0];
873
874                 if (unlikely(len[0] < hdr_size + ETHER_HDR_LEN)) {
875                         PMD_RX_LOG(ERR, "Packet drop");
876                         nb_enqueued++;
877                         virtio_discard_rxbuf(vq, rxm);
878                         rxvq->stats.errors++;
879                         continue;
880                 }
881
882                 header = (struct virtio_net_hdr_mrg_rxbuf *)((char *)rxm->buf_addr +
883                         RTE_PKTMBUF_HEADROOM - hdr_size);
884                 seg_num = header->num_buffers;
885
886                 if (seg_num == 0)
887                         seg_num = 1;
888
889                 rxm->data_off = RTE_PKTMBUF_HEADROOM;
890                 rxm->nb_segs = seg_num;
891                 rxm->next = NULL;
892                 rxm->ol_flags = 0;
893                 rxm->vlan_tci = 0;
894                 rxm->pkt_len = (uint32_t)(len[0] - hdr_size);
895                 rxm->data_len = (uint16_t)(len[0] - hdr_size);
896
897                 rxm->port = rxvq->port_id;
898                 rx_pkts[nb_rx] = rxm;
899                 prev = rxm;
900
901                 if (offload && virtio_rx_offload(rxm, &header->hdr) < 0) {
902                         virtio_discard_rxbuf(vq, rxm);
903                         rxvq->stats.errors++;
904                         continue;
905                 }
906
907                 seg_res = seg_num - 1;
908
909                 while (seg_res != 0) {
910                         /*
911                          * Get extra segments for current uncompleted packet.
912                          */
913                         uint16_t  rcv_cnt =
914                                 RTE_MIN(seg_res, RTE_DIM(rcv_pkts));
915                         if (likely(VIRTQUEUE_NUSED(vq) >= rcv_cnt)) {
916                                 uint32_t rx_num =
917                                         virtqueue_dequeue_burst_rx(vq,
918                                         rcv_pkts, len, rcv_cnt);
919                                 i += rx_num;
920                                 rcv_cnt = rx_num;
921                         } else {
922                                 PMD_RX_LOG(ERR,
923                                            "No enough segments for packet.");
924                                 nb_enqueued++;
925                                 virtio_discard_rxbuf(vq, rxm);
926                                 rxvq->stats.errors++;
927                                 break;
928                         }
929
930                         extra_idx = 0;
931
932                         while (extra_idx < rcv_cnt) {
933                                 rxm = rcv_pkts[extra_idx];
934
935                                 rxm->data_off = RTE_PKTMBUF_HEADROOM - hdr_size;
936                                 rxm->next = NULL;
937                                 rxm->pkt_len = (uint32_t)(len[extra_idx]);
938                                 rxm->data_len = (uint16_t)(len[extra_idx]);
939
940                                 if (prev)
941                                         prev->next = rxm;
942
943                                 prev = rxm;
944                                 rx_pkts[nb_rx]->pkt_len += rxm->pkt_len;
945                                 extra_idx++;
946                         };
947                         seg_res -= rcv_cnt;
948                 }
949
950                 if (hw->vlan_strip)
951                         rte_vlan_strip(rx_pkts[nb_rx]);
952
953                 VIRTIO_DUMP_PACKET(rx_pkts[nb_rx],
954                         rx_pkts[nb_rx]->data_len);
955
956                 rxvq->stats.bytes += rx_pkts[nb_rx]->pkt_len;
957                 virtio_update_packet_stats(&rxvq->stats, rx_pkts[nb_rx]);
958                 nb_rx++;
959         }
960
961         rxvq->stats.packets += nb_rx;
962
963         /* Allocate new mbuf for the used descriptor */
964         error = ENOSPC;
965         while (likely(!virtqueue_full(vq))) {
966                 new_mbuf = rte_mbuf_raw_alloc(rxvq->mpool);
967                 if (unlikely(new_mbuf == NULL)) {
968                         struct rte_eth_dev *dev
969                                 = &rte_eth_devices[rxvq->port_id];
970                         dev->data->rx_mbuf_alloc_failed++;
971                         break;
972                 }
973                 error = virtqueue_enqueue_recv_refill(vq, new_mbuf);
974                 if (unlikely(error)) {
975                         rte_pktmbuf_free(new_mbuf);
976                         break;
977                 }
978                 nb_enqueued++;
979         }
980
981         if (likely(nb_enqueued)) {
982                 vq_update_avail_idx(vq);
983
984                 if (unlikely(virtqueue_kick_prepare(vq))) {
985                         virtqueue_notify(vq);
986                         PMD_RX_LOG(DEBUG, "Notified");
987                 }
988         }
989
990         return nb_rx;
991 }
992
993 uint16_t
994 virtio_xmit_pkts(void *tx_queue, struct rte_mbuf **tx_pkts, uint16_t nb_pkts)
995 {
996         struct virtnet_tx *txvq = tx_queue;
997         struct virtqueue *vq = txvq->vq;
998         struct virtio_hw *hw = vq->hw;
999         uint16_t hdr_size = hw->vtnet_hdr_size;
1000         uint16_t nb_used, nb_tx;
1001         int error;
1002
1003         if (unlikely(nb_pkts < 1))
1004                 return nb_pkts;
1005
1006         PMD_TX_LOG(DEBUG, "%d packets to xmit", nb_pkts);
1007         nb_used = VIRTQUEUE_NUSED(vq);
1008
1009         virtio_rmb();
1010         if (likely(nb_used > vq->vq_nentries - vq->vq_free_thresh))
1011                 virtio_xmit_cleanup(vq, nb_used);
1012
1013         for (nb_tx = 0; nb_tx < nb_pkts; nb_tx++) {
1014                 struct rte_mbuf *txm = tx_pkts[nb_tx];
1015                 int can_push = 0, use_indirect = 0, slots, need;
1016
1017                 /* Do VLAN tag insertion */
1018                 if (unlikely(txm->ol_flags & PKT_TX_VLAN_PKT)) {
1019                         error = rte_vlan_insert(&txm);
1020                         if (unlikely(error)) {
1021                                 rte_pktmbuf_free(txm);
1022                                 continue;
1023                         }
1024                 }
1025
1026                 /* optimize ring usage */
1027                 if ((vtpci_with_feature(hw, VIRTIO_F_ANY_LAYOUT) ||
1028                       vtpci_with_feature(hw, VIRTIO_F_VERSION_1)) &&
1029                     rte_mbuf_refcnt_read(txm) == 1 &&
1030                     RTE_MBUF_DIRECT(txm) &&
1031                     txm->nb_segs == 1 &&
1032                     rte_pktmbuf_headroom(txm) >= hdr_size &&
1033                     rte_is_aligned(rte_pktmbuf_mtod(txm, char *),
1034                                    __alignof__(struct virtio_net_hdr_mrg_rxbuf)))
1035                         can_push = 1;
1036                 else if (vtpci_with_feature(hw, VIRTIO_RING_F_INDIRECT_DESC) &&
1037                          txm->nb_segs < VIRTIO_MAX_TX_INDIRECT)
1038                         use_indirect = 1;
1039
1040                 /* How many main ring entries are needed to this Tx?
1041                  * any_layout => number of segments
1042                  * indirect   => 1
1043                  * default    => number of segments + 1
1044                  */
1045                 slots = use_indirect ? 1 : (txm->nb_segs + !can_push);
1046                 need = slots - vq->vq_free_cnt;
1047
1048                 /* Positive value indicates it need free vring descriptors */
1049                 if (unlikely(need > 0)) {
1050                         nb_used = VIRTQUEUE_NUSED(vq);
1051                         virtio_rmb();
1052                         need = RTE_MIN(need, (int)nb_used);
1053
1054                         virtio_xmit_cleanup(vq, need);
1055                         need = slots - vq->vq_free_cnt;
1056                         if (unlikely(need > 0)) {
1057                                 PMD_TX_LOG(ERR,
1058                                            "No free tx descriptors to transmit");
1059                                 break;
1060                         }
1061                 }
1062
1063                 /* Enqueue Packet buffers */
1064                 virtqueue_enqueue_xmit(txvq, txm, slots, use_indirect, can_push);
1065
1066                 txvq->stats.bytes += txm->pkt_len;
1067                 virtio_update_packet_stats(&txvq->stats, txm);
1068         }
1069
1070         txvq->stats.packets += nb_tx;
1071
1072         if (likely(nb_tx)) {
1073                 vq_update_avail_idx(vq);
1074
1075                 if (unlikely(virtqueue_kick_prepare(vq))) {
1076                         virtqueue_notify(vq);
1077                         PMD_TX_LOG(DEBUG, "Notified backend after xmit");
1078                 }
1079         }
1080
1081         return nb_tx;
1082 }