e6ba1282be926773805984046ffd1f1d865f7ac9
[dpdk.git] / drivers / net / virtio / virtio_ethdev.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2016 Intel Corporation
3  */
4
5 #include <stdint.h>
6 #include <string.h>
7 #include <stdio.h>
8 #include <errno.h>
9 #include <unistd.h>
10
11 #include <rte_ethdev_driver.h>
12 #include <rte_ethdev_pci.h>
13 #include <rte_memcpy.h>
14 #include <rte_string_fns.h>
15 #include <rte_memzone.h>
16 #include <rte_malloc.h>
17 #include <rte_branch_prediction.h>
18 #include <rte_pci.h>
19 #include <rte_bus_pci.h>
20 #include <rte_ether.h>
21 #include <rte_ip.h>
22 #include <rte_arp.h>
23 #include <rte_common.h>
24 #include <rte_errno.h>
25 #include <rte_cpuflags.h>
26
27 #include <rte_memory.h>
28 #include <rte_eal.h>
29 #include <rte_dev.h>
30 #include <rte_cycles.h>
31 #include <rte_kvargs.h>
32
33 #include "virtio_ethdev.h"
34 #include "virtio_pci.h"
35 #include "virtio_logs.h"
36 #include "virtqueue.h"
37 #include "virtio_rxtx.h"
38
39 static int eth_virtio_dev_uninit(struct rte_eth_dev *eth_dev);
40 static int  virtio_dev_configure(struct rte_eth_dev *dev);
41 static int  virtio_dev_start(struct rte_eth_dev *dev);
42 static void virtio_dev_stop(struct rte_eth_dev *dev);
43 static void virtio_dev_promiscuous_enable(struct rte_eth_dev *dev);
44 static void virtio_dev_promiscuous_disable(struct rte_eth_dev *dev);
45 static void virtio_dev_allmulticast_enable(struct rte_eth_dev *dev);
46 static void virtio_dev_allmulticast_disable(struct rte_eth_dev *dev);
47 static void virtio_dev_info_get(struct rte_eth_dev *dev,
48                                 struct rte_eth_dev_info *dev_info);
49 static int virtio_dev_link_update(struct rte_eth_dev *dev,
50         int wait_to_complete);
51 static int virtio_dev_vlan_offload_set(struct rte_eth_dev *dev, int mask);
52
53 static void virtio_set_hwaddr(struct virtio_hw *hw);
54 static void virtio_get_hwaddr(struct virtio_hw *hw);
55
56 static int virtio_dev_stats_get(struct rte_eth_dev *dev,
57                                  struct rte_eth_stats *stats);
58 static int virtio_dev_xstats_get(struct rte_eth_dev *dev,
59                                  struct rte_eth_xstat *xstats, unsigned n);
60 static int virtio_dev_xstats_get_names(struct rte_eth_dev *dev,
61                                        struct rte_eth_xstat_name *xstats_names,
62                                        unsigned limit);
63 static void virtio_dev_stats_reset(struct rte_eth_dev *dev);
64 static void virtio_dev_free_mbufs(struct rte_eth_dev *dev);
65 static int virtio_vlan_filter_set(struct rte_eth_dev *dev,
66                                 uint16_t vlan_id, int on);
67 static int virtio_mac_addr_add(struct rte_eth_dev *dev,
68                                 struct ether_addr *mac_addr,
69                                 uint32_t index, uint32_t vmdq);
70 static void virtio_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index);
71 static int virtio_mac_addr_set(struct rte_eth_dev *dev,
72                                 struct ether_addr *mac_addr);
73
74 static int virtio_intr_enable(struct rte_eth_dev *dev);
75 static int virtio_intr_disable(struct rte_eth_dev *dev);
76
77 static int virtio_dev_queue_stats_mapping_set(
78         struct rte_eth_dev *eth_dev,
79         uint16_t queue_id,
80         uint8_t stat_idx,
81         uint8_t is_rx);
82
83 int virtio_logtype_init;
84 int virtio_logtype_driver;
85
86 static void virtio_notify_peers(struct rte_eth_dev *dev);
87 static void virtio_ack_link_announce(struct rte_eth_dev *dev);
88
89 /*
90  * The set of PCI devices this driver supports
91  */
92 static const struct rte_pci_id pci_id_virtio_map[] = {
93         { RTE_PCI_DEVICE(VIRTIO_PCI_VENDORID, VIRTIO_PCI_LEGACY_DEVICEID_NET) },
94         { RTE_PCI_DEVICE(VIRTIO_PCI_VENDORID, VIRTIO_PCI_MODERN_DEVICEID_NET) },
95         { .vendor_id = 0, /* sentinel */ },
96 };
97
98 struct rte_virtio_xstats_name_off {
99         char name[RTE_ETH_XSTATS_NAME_SIZE];
100         unsigned offset;
101 };
102
103 /* [rt]x_qX_ is prepended to the name string here */
104 static const struct rte_virtio_xstats_name_off rte_virtio_rxq_stat_strings[] = {
105         {"good_packets",           offsetof(struct virtnet_rx, stats.packets)},
106         {"good_bytes",             offsetof(struct virtnet_rx, stats.bytes)},
107         {"errors",                 offsetof(struct virtnet_rx, stats.errors)},
108         {"multicast_packets",      offsetof(struct virtnet_rx, stats.multicast)},
109         {"broadcast_packets",      offsetof(struct virtnet_rx, stats.broadcast)},
110         {"undersize_packets",      offsetof(struct virtnet_rx, stats.size_bins[0])},
111         {"size_64_packets",        offsetof(struct virtnet_rx, stats.size_bins[1])},
112         {"size_65_127_packets",    offsetof(struct virtnet_rx, stats.size_bins[2])},
113         {"size_128_255_packets",   offsetof(struct virtnet_rx, stats.size_bins[3])},
114         {"size_256_511_packets",   offsetof(struct virtnet_rx, stats.size_bins[4])},
115         {"size_512_1023_packets",  offsetof(struct virtnet_rx, stats.size_bins[5])},
116         {"size_1024_1518_packets", offsetof(struct virtnet_rx, stats.size_bins[6])},
117         {"size_1519_max_packets",  offsetof(struct virtnet_rx, stats.size_bins[7])},
118 };
119
120 /* [rt]x_qX_ is prepended to the name string here */
121 static const struct rte_virtio_xstats_name_off rte_virtio_txq_stat_strings[] = {
122         {"good_packets",           offsetof(struct virtnet_tx, stats.packets)},
123         {"good_bytes",             offsetof(struct virtnet_tx, stats.bytes)},
124         {"errors",                 offsetof(struct virtnet_tx, stats.errors)},
125         {"multicast_packets",      offsetof(struct virtnet_tx, stats.multicast)},
126         {"broadcast_packets",      offsetof(struct virtnet_tx, stats.broadcast)},
127         {"undersize_packets",      offsetof(struct virtnet_tx, stats.size_bins[0])},
128         {"size_64_packets",        offsetof(struct virtnet_tx, stats.size_bins[1])},
129         {"size_65_127_packets",    offsetof(struct virtnet_tx, stats.size_bins[2])},
130         {"size_128_255_packets",   offsetof(struct virtnet_tx, stats.size_bins[3])},
131         {"size_256_511_packets",   offsetof(struct virtnet_tx, stats.size_bins[4])},
132         {"size_512_1023_packets",  offsetof(struct virtnet_tx, stats.size_bins[5])},
133         {"size_1024_1518_packets", offsetof(struct virtnet_tx, stats.size_bins[6])},
134         {"size_1519_max_packets",  offsetof(struct virtnet_tx, stats.size_bins[7])},
135 };
136
137 #define VIRTIO_NB_RXQ_XSTATS (sizeof(rte_virtio_rxq_stat_strings) / \
138                             sizeof(rte_virtio_rxq_stat_strings[0]))
139 #define VIRTIO_NB_TXQ_XSTATS (sizeof(rte_virtio_txq_stat_strings) / \
140                             sizeof(rte_virtio_txq_stat_strings[0]))
141
142 struct virtio_hw_internal virtio_hw_internal[RTE_MAX_ETHPORTS];
143
144 static int
145 virtio_send_command(struct virtnet_ctl *cvq, struct virtio_pmd_ctrl *ctrl,
146                 int *dlen, int pkt_num)
147 {
148         uint32_t head, i;
149         int k, sum = 0;
150         virtio_net_ctrl_ack status = ~0;
151         struct virtio_pmd_ctrl *result;
152         struct virtqueue *vq;
153
154         ctrl->status = status;
155
156         if (!cvq || !cvq->vq) {
157                 PMD_INIT_LOG(ERR, "Control queue is not supported.");
158                 return -1;
159         }
160
161         rte_spinlock_lock(&cvq->lock);
162         vq = cvq->vq;
163         head = vq->vq_desc_head_idx;
164
165         PMD_INIT_LOG(DEBUG, "vq->vq_desc_head_idx = %d, status = %d, "
166                 "vq->hw->cvq = %p vq = %p",
167                 vq->vq_desc_head_idx, status, vq->hw->cvq, vq);
168
169         if (vq->vq_free_cnt < pkt_num + 2 || pkt_num < 1) {
170                 rte_spinlock_unlock(&cvq->lock);
171                 return -1;
172         }
173
174         memcpy(cvq->virtio_net_hdr_mz->addr, ctrl,
175                 sizeof(struct virtio_pmd_ctrl));
176
177         /*
178          * Format is enforced in qemu code:
179          * One TX packet for header;
180          * At least one TX packet per argument;
181          * One RX packet for ACK.
182          */
183         vq->vq_ring.desc[head].flags = VRING_DESC_F_NEXT;
184         vq->vq_ring.desc[head].addr = cvq->virtio_net_hdr_mem;
185         vq->vq_ring.desc[head].len = sizeof(struct virtio_net_ctrl_hdr);
186         vq->vq_free_cnt--;
187         i = vq->vq_ring.desc[head].next;
188
189         for (k = 0; k < pkt_num; k++) {
190                 vq->vq_ring.desc[i].flags = VRING_DESC_F_NEXT;
191                 vq->vq_ring.desc[i].addr = cvq->virtio_net_hdr_mem
192                         + sizeof(struct virtio_net_ctrl_hdr)
193                         + sizeof(ctrl->status) + sizeof(uint8_t)*sum;
194                 vq->vq_ring.desc[i].len = dlen[k];
195                 sum += dlen[k];
196                 vq->vq_free_cnt--;
197                 i = vq->vq_ring.desc[i].next;
198         }
199
200         vq->vq_ring.desc[i].flags = VRING_DESC_F_WRITE;
201         vq->vq_ring.desc[i].addr = cvq->virtio_net_hdr_mem
202                         + sizeof(struct virtio_net_ctrl_hdr);
203         vq->vq_ring.desc[i].len = sizeof(ctrl->status);
204         vq->vq_free_cnt--;
205
206         vq->vq_desc_head_idx = vq->vq_ring.desc[i].next;
207
208         vq_update_avail_ring(vq, head);
209         vq_update_avail_idx(vq);
210
211         PMD_INIT_LOG(DEBUG, "vq->vq_queue_index = %d", vq->vq_queue_index);
212
213         virtqueue_notify(vq);
214
215         rte_rmb();
216         while (VIRTQUEUE_NUSED(vq) == 0) {
217                 rte_rmb();
218                 usleep(100);
219         }
220
221         while (VIRTQUEUE_NUSED(vq)) {
222                 uint32_t idx, desc_idx, used_idx;
223                 struct vring_used_elem *uep;
224
225                 used_idx = (uint32_t)(vq->vq_used_cons_idx
226                                 & (vq->vq_nentries - 1));
227                 uep = &vq->vq_ring.used->ring[used_idx];
228                 idx = (uint32_t) uep->id;
229                 desc_idx = idx;
230
231                 while (vq->vq_ring.desc[desc_idx].flags & VRING_DESC_F_NEXT) {
232                         desc_idx = vq->vq_ring.desc[desc_idx].next;
233                         vq->vq_free_cnt++;
234                 }
235
236                 vq->vq_ring.desc[desc_idx].next = vq->vq_desc_head_idx;
237                 vq->vq_desc_head_idx = idx;
238
239                 vq->vq_used_cons_idx++;
240                 vq->vq_free_cnt++;
241         }
242
243         PMD_INIT_LOG(DEBUG, "vq->vq_free_cnt=%d\nvq->vq_desc_head_idx=%d",
244                         vq->vq_free_cnt, vq->vq_desc_head_idx);
245
246         result = cvq->virtio_net_hdr_mz->addr;
247
248         rte_spinlock_unlock(&cvq->lock);
249         return result->status;
250 }
251
252 static int
253 virtio_set_multiple_queues(struct rte_eth_dev *dev, uint16_t nb_queues)
254 {
255         struct virtio_hw *hw = dev->data->dev_private;
256         struct virtio_pmd_ctrl ctrl;
257         int dlen[1];
258         int ret;
259
260         ctrl.hdr.class = VIRTIO_NET_CTRL_MQ;
261         ctrl.hdr.cmd = VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET;
262         memcpy(ctrl.data, &nb_queues, sizeof(uint16_t));
263
264         dlen[0] = sizeof(uint16_t);
265
266         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
267         if (ret) {
268                 PMD_INIT_LOG(ERR, "Multiqueue configured but send command "
269                           "failed, this is too late now...");
270                 return -EINVAL;
271         }
272
273         return 0;
274 }
275
276 static void
277 virtio_dev_queue_release(void *queue __rte_unused)
278 {
279         /* do nothing */
280 }
281
282 static uint16_t
283 virtio_get_nr_vq(struct virtio_hw *hw)
284 {
285         uint16_t nr_vq = hw->max_queue_pairs * 2;
286
287         if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VQ))
288                 nr_vq += 1;
289
290         return nr_vq;
291 }
292
293 static void
294 virtio_init_vring(struct virtqueue *vq)
295 {
296         int size = vq->vq_nentries;
297         struct vring *vr = &vq->vq_ring;
298         uint8_t *ring_mem = vq->vq_ring_virt_mem;
299
300         PMD_INIT_FUNC_TRACE();
301
302         memset(ring_mem, 0, vq->vq_ring_size);
303
304         vq->vq_used_cons_idx = 0;
305         vq->vq_desc_head_idx = 0;
306         vq->vq_avail_idx = 0;
307         vq->vq_desc_tail_idx = (uint16_t)(vq->vq_nentries - 1);
308         vq->vq_free_cnt = vq->vq_nentries;
309         memset(vq->vq_descx, 0, sizeof(struct vq_desc_extra) * vq->vq_nentries);
310         if (vtpci_packed_queue(vq->hw)) {
311                 vring_init_packed(&vq->ring_packed, ring_mem,
312                                   VIRTIO_PCI_VRING_ALIGN, size);
313                 vring_desc_init_packed(vq, size);
314         } else {
315                 vring_init_split(vr, ring_mem, VIRTIO_PCI_VRING_ALIGN, size);
316                 vring_desc_init_split(vr->desc, size);
317         }
318         /*
319          * Disable device(host) interrupting guest
320          */
321         virtqueue_disable_intr(vq);
322 }
323
324 static int
325 virtio_init_queue(struct rte_eth_dev *dev, uint16_t vtpci_queue_idx)
326 {
327         char vq_name[VIRTQUEUE_MAX_NAME_SZ];
328         char vq_hdr_name[VIRTQUEUE_MAX_NAME_SZ];
329         const struct rte_memzone *mz = NULL, *hdr_mz = NULL;
330         unsigned int vq_size, size;
331         struct virtio_hw *hw = dev->data->dev_private;
332         struct virtnet_rx *rxvq = NULL;
333         struct virtnet_tx *txvq = NULL;
334         struct virtnet_ctl *cvq = NULL;
335         struct virtqueue *vq;
336         size_t sz_hdr_mz = 0;
337         void *sw_ring = NULL;
338         int queue_type = virtio_get_queue_type(hw, vtpci_queue_idx);
339         int ret;
340         int numa_node = dev->device->numa_node;
341
342         PMD_INIT_LOG(INFO, "setting up queue: %u on NUMA node %d",
343                         vtpci_queue_idx, numa_node);
344
345         /*
346          * Read the virtqueue size from the Queue Size field
347          * Always power of 2 and if 0 virtqueue does not exist
348          */
349         vq_size = VTPCI_OPS(hw)->get_queue_num(hw, vtpci_queue_idx);
350         PMD_INIT_LOG(DEBUG, "vq_size: %u", vq_size);
351         if (vq_size == 0) {
352                 PMD_INIT_LOG(ERR, "virtqueue does not exist");
353                 return -EINVAL;
354         }
355
356         if (!rte_is_power_of_2(vq_size)) {
357                 PMD_INIT_LOG(ERR, "virtqueue size is not powerof 2");
358                 return -EINVAL;
359         }
360
361         snprintf(vq_name, sizeof(vq_name), "port%d_vq%d",
362                  dev->data->port_id, vtpci_queue_idx);
363
364         size = RTE_ALIGN_CEIL(sizeof(*vq) +
365                                 vq_size * sizeof(struct vq_desc_extra),
366                                 RTE_CACHE_LINE_SIZE);
367         if (queue_type == VTNET_TQ) {
368                 /*
369                  * For each xmit packet, allocate a virtio_net_hdr
370                  * and indirect ring elements
371                  */
372                 sz_hdr_mz = vq_size * sizeof(struct virtio_tx_region);
373         } else if (queue_type == VTNET_CQ) {
374                 /* Allocate a page for control vq command, data and status */
375                 sz_hdr_mz = PAGE_SIZE;
376         }
377
378         vq = rte_zmalloc_socket(vq_name, size, RTE_CACHE_LINE_SIZE,
379                                 numa_node);
380         if (vq == NULL) {
381                 PMD_INIT_LOG(ERR, "can not allocate vq");
382                 return -ENOMEM;
383         }
384         hw->vqs[vtpci_queue_idx] = vq;
385
386         vq->hw = hw;
387         vq->vq_queue_index = vtpci_queue_idx;
388         vq->vq_nentries = vq_size;
389         vq->event_flags_shadow = 0;
390         if (vtpci_packed_queue(hw)) {
391                 vq->avail_wrap_counter = 1;
392                 vq->used_wrap_counter = 1;
393         }
394
395         /*
396          * Reserve a memzone for vring elements
397          */
398         size = vring_size(hw, vq_size, VIRTIO_PCI_VRING_ALIGN);
399         vq->vq_ring_size = RTE_ALIGN_CEIL(size, VIRTIO_PCI_VRING_ALIGN);
400         PMD_INIT_LOG(DEBUG, "vring_size: %d, rounded_vring_size: %d",
401                      size, vq->vq_ring_size);
402
403         mz = rte_memzone_reserve_aligned(vq_name, vq->vq_ring_size,
404                         numa_node, RTE_MEMZONE_IOVA_CONTIG,
405                         VIRTIO_PCI_VRING_ALIGN);
406         if (mz == NULL) {
407                 if (rte_errno == EEXIST)
408                         mz = rte_memzone_lookup(vq_name);
409                 if (mz == NULL) {
410                         ret = -ENOMEM;
411                         goto fail_q_alloc;
412                 }
413         }
414
415         memset(mz->addr, 0, mz->len);
416
417         vq->vq_ring_mem = mz->iova;
418         vq->vq_ring_virt_mem = mz->addr;
419         PMD_INIT_LOG(DEBUG, "vq->vq_ring_mem:      0x%" PRIx64,
420                      (uint64_t)mz->iova);
421         PMD_INIT_LOG(DEBUG, "vq->vq_ring_virt_mem: 0x%" PRIx64,
422                      (uint64_t)(uintptr_t)mz->addr);
423
424         virtio_init_vring(vq);
425
426         if (sz_hdr_mz) {
427                 snprintf(vq_hdr_name, sizeof(vq_hdr_name), "port%d_vq%d_hdr",
428                          dev->data->port_id, vtpci_queue_idx);
429                 hdr_mz = rte_memzone_reserve_aligned(vq_hdr_name, sz_hdr_mz,
430                                 numa_node, RTE_MEMZONE_IOVA_CONTIG,
431                                 RTE_CACHE_LINE_SIZE);
432                 if (hdr_mz == NULL) {
433                         if (rte_errno == EEXIST)
434                                 hdr_mz = rte_memzone_lookup(vq_hdr_name);
435                         if (hdr_mz == NULL) {
436                                 ret = -ENOMEM;
437                                 goto fail_q_alloc;
438                         }
439                 }
440         }
441
442         if (queue_type == VTNET_RQ) {
443                 size_t sz_sw = (RTE_PMD_VIRTIO_RX_MAX_BURST + vq_size) *
444                                sizeof(vq->sw_ring[0]);
445
446                 sw_ring = rte_zmalloc_socket("sw_ring", sz_sw,
447                                 RTE_CACHE_LINE_SIZE, numa_node);
448                 if (!sw_ring) {
449                         PMD_INIT_LOG(ERR, "can not allocate RX soft ring");
450                         ret = -ENOMEM;
451                         goto fail_q_alloc;
452                 }
453
454                 vq->sw_ring = sw_ring;
455                 rxvq = &vq->rxq;
456                 rxvq->vq = vq;
457                 rxvq->port_id = dev->data->port_id;
458                 rxvq->mz = mz;
459         } else if (queue_type == VTNET_TQ) {
460                 txvq = &vq->txq;
461                 txvq->vq = vq;
462                 txvq->port_id = dev->data->port_id;
463                 txvq->mz = mz;
464                 txvq->virtio_net_hdr_mz = hdr_mz;
465                 txvq->virtio_net_hdr_mem = hdr_mz->iova;
466         } else if (queue_type == VTNET_CQ) {
467                 cvq = &vq->cq;
468                 cvq->vq = vq;
469                 cvq->mz = mz;
470                 cvq->virtio_net_hdr_mz = hdr_mz;
471                 cvq->virtio_net_hdr_mem = hdr_mz->iova;
472                 memset(cvq->virtio_net_hdr_mz->addr, 0, PAGE_SIZE);
473
474                 hw->cvq = cvq;
475         }
476
477         /* For virtio_user case (that is when hw->dev is NULL), we use
478          * virtual address. And we need properly set _offset_, please see
479          * VIRTIO_MBUF_DATA_DMA_ADDR in virtqueue.h for more information.
480          */
481         if (!hw->virtio_user_dev)
482                 vq->offset = offsetof(struct rte_mbuf, buf_iova);
483         else {
484                 vq->vq_ring_mem = (uintptr_t)mz->addr;
485                 vq->offset = offsetof(struct rte_mbuf, buf_addr);
486                 if (queue_type == VTNET_TQ)
487                         txvq->virtio_net_hdr_mem = (uintptr_t)hdr_mz->addr;
488                 else if (queue_type == VTNET_CQ)
489                         cvq->virtio_net_hdr_mem = (uintptr_t)hdr_mz->addr;
490         }
491
492         if (queue_type == VTNET_TQ) {
493                 struct virtio_tx_region *txr;
494                 unsigned int i;
495
496                 txr = hdr_mz->addr;
497                 memset(txr, 0, vq_size * sizeof(*txr));
498                 for (i = 0; i < vq_size; i++) {
499                         struct vring_desc *start_dp = txr[i].tx_indir;
500
501                         vring_desc_init_split(start_dp,
502                                               RTE_DIM(txr[i].tx_indir));
503
504                         /* first indirect descriptor is always the tx header */
505                         start_dp->addr = txvq->virtio_net_hdr_mem
506                                 + i * sizeof(*txr)
507                                 + offsetof(struct virtio_tx_region, tx_hdr);
508
509                         start_dp->len = hw->vtnet_hdr_size;
510                         start_dp->flags = VRING_DESC_F_NEXT;
511                 }
512         }
513
514         if (VTPCI_OPS(hw)->setup_queue(hw, vq) < 0) {
515                 PMD_INIT_LOG(ERR, "setup_queue failed");
516                 return -EINVAL;
517         }
518
519         return 0;
520
521 fail_q_alloc:
522         rte_free(sw_ring);
523         rte_memzone_free(hdr_mz);
524         rte_memzone_free(mz);
525         rte_free(vq);
526
527         return ret;
528 }
529
530 static void
531 virtio_free_queues(struct virtio_hw *hw)
532 {
533         uint16_t nr_vq = virtio_get_nr_vq(hw);
534         struct virtqueue *vq;
535         int queue_type;
536         uint16_t i;
537
538         if (hw->vqs == NULL)
539                 return;
540
541         for (i = 0; i < nr_vq; i++) {
542                 vq = hw->vqs[i];
543                 if (!vq)
544                         continue;
545
546                 queue_type = virtio_get_queue_type(hw, i);
547                 if (queue_type == VTNET_RQ) {
548                         rte_free(vq->sw_ring);
549                         rte_memzone_free(vq->rxq.mz);
550                 } else if (queue_type == VTNET_TQ) {
551                         rte_memzone_free(vq->txq.mz);
552                         rte_memzone_free(vq->txq.virtio_net_hdr_mz);
553                 } else {
554                         rte_memzone_free(vq->cq.mz);
555                         rte_memzone_free(vq->cq.virtio_net_hdr_mz);
556                 }
557
558                 rte_free(vq);
559                 hw->vqs[i] = NULL;
560         }
561
562         rte_free(hw->vqs);
563         hw->vqs = NULL;
564 }
565
566 static int
567 virtio_alloc_queues(struct rte_eth_dev *dev)
568 {
569         struct virtio_hw *hw = dev->data->dev_private;
570         uint16_t nr_vq = virtio_get_nr_vq(hw);
571         uint16_t i;
572         int ret;
573
574         hw->vqs = rte_zmalloc(NULL, sizeof(struct virtqueue *) * nr_vq, 0);
575         if (!hw->vqs) {
576                 PMD_INIT_LOG(ERR, "failed to allocate vqs");
577                 return -ENOMEM;
578         }
579
580         for (i = 0; i < nr_vq; i++) {
581                 ret = virtio_init_queue(dev, i);
582                 if (ret < 0) {
583                         virtio_free_queues(hw);
584                         return ret;
585                 }
586         }
587
588         return 0;
589 }
590
591 static void virtio_queues_unbind_intr(struct rte_eth_dev *dev);
592
593 static void
594 virtio_dev_close(struct rte_eth_dev *dev)
595 {
596         struct virtio_hw *hw = dev->data->dev_private;
597         struct rte_intr_conf *intr_conf = &dev->data->dev_conf.intr_conf;
598
599         PMD_INIT_LOG(DEBUG, "virtio_dev_close");
600
601         if (!hw->opened)
602                 return;
603         hw->opened = false;
604
605         /* reset the NIC */
606         if (dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
607                 VTPCI_OPS(hw)->set_config_irq(hw, VIRTIO_MSI_NO_VECTOR);
608         if (intr_conf->rxq)
609                 virtio_queues_unbind_intr(dev);
610
611         if (intr_conf->lsc || intr_conf->rxq) {
612                 virtio_intr_disable(dev);
613                 rte_intr_efd_disable(dev->intr_handle);
614                 rte_free(dev->intr_handle->intr_vec);
615                 dev->intr_handle->intr_vec = NULL;
616         }
617
618         vtpci_reset(hw);
619         virtio_dev_free_mbufs(dev);
620         virtio_free_queues(hw);
621 }
622
623 static void
624 virtio_dev_promiscuous_enable(struct rte_eth_dev *dev)
625 {
626         struct virtio_hw *hw = dev->data->dev_private;
627         struct virtio_pmd_ctrl ctrl;
628         int dlen[1];
629         int ret;
630
631         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
632                 PMD_INIT_LOG(INFO, "host does not support rx control");
633                 return;
634         }
635
636         ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
637         ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_PROMISC;
638         ctrl.data[0] = 1;
639         dlen[0] = 1;
640
641         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
642         if (ret)
643                 PMD_INIT_LOG(ERR, "Failed to enable promisc");
644 }
645
646 static void
647 virtio_dev_promiscuous_disable(struct rte_eth_dev *dev)
648 {
649         struct virtio_hw *hw = dev->data->dev_private;
650         struct virtio_pmd_ctrl ctrl;
651         int dlen[1];
652         int ret;
653
654         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
655                 PMD_INIT_LOG(INFO, "host does not support rx control");
656                 return;
657         }
658
659         ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
660         ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_PROMISC;
661         ctrl.data[0] = 0;
662         dlen[0] = 1;
663
664         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
665         if (ret)
666                 PMD_INIT_LOG(ERR, "Failed to disable promisc");
667 }
668
669 static void
670 virtio_dev_allmulticast_enable(struct rte_eth_dev *dev)
671 {
672         struct virtio_hw *hw = dev->data->dev_private;
673         struct virtio_pmd_ctrl ctrl;
674         int dlen[1];
675         int ret;
676
677         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
678                 PMD_INIT_LOG(INFO, "host does not support rx control");
679                 return;
680         }
681
682         ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
683         ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_ALLMULTI;
684         ctrl.data[0] = 1;
685         dlen[0] = 1;
686
687         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
688         if (ret)
689                 PMD_INIT_LOG(ERR, "Failed to enable allmulticast");
690 }
691
692 static void
693 virtio_dev_allmulticast_disable(struct rte_eth_dev *dev)
694 {
695         struct virtio_hw *hw = dev->data->dev_private;
696         struct virtio_pmd_ctrl ctrl;
697         int dlen[1];
698         int ret;
699
700         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
701                 PMD_INIT_LOG(INFO, "host does not support rx control");
702                 return;
703         }
704
705         ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
706         ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_ALLMULTI;
707         ctrl.data[0] = 0;
708         dlen[0] = 1;
709
710         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
711         if (ret)
712                 PMD_INIT_LOG(ERR, "Failed to disable allmulticast");
713 }
714
715 #define VLAN_TAG_LEN           4    /* 802.3ac tag (not DMA'd) */
716 static int
717 virtio_mtu_set(struct rte_eth_dev *dev, uint16_t mtu)
718 {
719         struct virtio_hw *hw = dev->data->dev_private;
720         uint32_t ether_hdr_len = ETHER_HDR_LEN + VLAN_TAG_LEN +
721                                  hw->vtnet_hdr_size;
722         uint32_t frame_size = mtu + ether_hdr_len;
723         uint32_t max_frame_size = hw->max_mtu + ether_hdr_len;
724
725         max_frame_size = RTE_MIN(max_frame_size, VIRTIO_MAX_RX_PKTLEN);
726
727         if (mtu < ETHER_MIN_MTU || frame_size > max_frame_size) {
728                 PMD_INIT_LOG(ERR, "MTU should be between %d and %d",
729                         ETHER_MIN_MTU, max_frame_size - ether_hdr_len);
730                 return -EINVAL;
731         }
732         return 0;
733 }
734
735 static int
736 virtio_dev_rx_queue_intr_enable(struct rte_eth_dev *dev, uint16_t queue_id)
737 {
738         struct virtnet_rx *rxvq = dev->data->rx_queues[queue_id];
739         struct virtqueue *vq = rxvq->vq;
740
741         virtqueue_enable_intr(vq);
742         return 0;
743 }
744
745 static int
746 virtio_dev_rx_queue_intr_disable(struct rte_eth_dev *dev, uint16_t queue_id)
747 {
748         struct virtnet_rx *rxvq = dev->data->rx_queues[queue_id];
749         struct virtqueue *vq = rxvq->vq;
750
751         virtqueue_disable_intr(vq);
752         return 0;
753 }
754
755 /*
756  * dev_ops for virtio, bare necessities for basic operation
757  */
758 static const struct eth_dev_ops virtio_eth_dev_ops = {
759         .dev_configure           = virtio_dev_configure,
760         .dev_start               = virtio_dev_start,
761         .dev_stop                = virtio_dev_stop,
762         .dev_close               = virtio_dev_close,
763         .promiscuous_enable      = virtio_dev_promiscuous_enable,
764         .promiscuous_disable     = virtio_dev_promiscuous_disable,
765         .allmulticast_enable     = virtio_dev_allmulticast_enable,
766         .allmulticast_disable    = virtio_dev_allmulticast_disable,
767         .mtu_set                 = virtio_mtu_set,
768         .dev_infos_get           = virtio_dev_info_get,
769         .stats_get               = virtio_dev_stats_get,
770         .xstats_get              = virtio_dev_xstats_get,
771         .xstats_get_names        = virtio_dev_xstats_get_names,
772         .stats_reset             = virtio_dev_stats_reset,
773         .xstats_reset            = virtio_dev_stats_reset,
774         .link_update             = virtio_dev_link_update,
775         .vlan_offload_set        = virtio_dev_vlan_offload_set,
776         .rx_queue_setup          = virtio_dev_rx_queue_setup,
777         .rx_queue_intr_enable    = virtio_dev_rx_queue_intr_enable,
778         .rx_queue_intr_disable   = virtio_dev_rx_queue_intr_disable,
779         .rx_queue_release        = virtio_dev_queue_release,
780         .rx_descriptor_done      = virtio_dev_rx_queue_done,
781         .tx_queue_setup          = virtio_dev_tx_queue_setup,
782         .tx_queue_release        = virtio_dev_queue_release,
783         /* collect stats per queue */
784         .queue_stats_mapping_set = virtio_dev_queue_stats_mapping_set,
785         .vlan_filter_set         = virtio_vlan_filter_set,
786         .mac_addr_add            = virtio_mac_addr_add,
787         .mac_addr_remove         = virtio_mac_addr_remove,
788         .mac_addr_set            = virtio_mac_addr_set,
789 };
790
791 static void
792 virtio_update_stats(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
793 {
794         unsigned i;
795
796         for (i = 0; i < dev->data->nb_tx_queues; i++) {
797                 const struct virtnet_tx *txvq = dev->data->tx_queues[i];
798                 if (txvq == NULL)
799                         continue;
800
801                 stats->opackets += txvq->stats.packets;
802                 stats->obytes += txvq->stats.bytes;
803                 stats->oerrors += txvq->stats.errors;
804
805                 if (i < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
806                         stats->q_opackets[i] = txvq->stats.packets;
807                         stats->q_obytes[i] = txvq->stats.bytes;
808                 }
809         }
810
811         for (i = 0; i < dev->data->nb_rx_queues; i++) {
812                 const struct virtnet_rx *rxvq = dev->data->rx_queues[i];
813                 if (rxvq == NULL)
814                         continue;
815
816                 stats->ipackets += rxvq->stats.packets;
817                 stats->ibytes += rxvq->stats.bytes;
818                 stats->ierrors += rxvq->stats.errors;
819
820                 if (i < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
821                         stats->q_ipackets[i] = rxvq->stats.packets;
822                         stats->q_ibytes[i] = rxvq->stats.bytes;
823                 }
824         }
825
826         stats->rx_nombuf = dev->data->rx_mbuf_alloc_failed;
827 }
828
829 static int virtio_dev_xstats_get_names(struct rte_eth_dev *dev,
830                                        struct rte_eth_xstat_name *xstats_names,
831                                        __rte_unused unsigned limit)
832 {
833         unsigned i;
834         unsigned count = 0;
835         unsigned t;
836
837         unsigned nstats = dev->data->nb_tx_queues * VIRTIO_NB_TXQ_XSTATS +
838                 dev->data->nb_rx_queues * VIRTIO_NB_RXQ_XSTATS;
839
840         if (xstats_names != NULL) {
841                 /* Note: limit checked in rte_eth_xstats_names() */
842
843                 for (i = 0; i < dev->data->nb_rx_queues; i++) {
844                         struct virtnet_rx *rxvq = dev->data->rx_queues[i];
845                         if (rxvq == NULL)
846                                 continue;
847                         for (t = 0; t < VIRTIO_NB_RXQ_XSTATS; t++) {
848                                 snprintf(xstats_names[count].name,
849                                         sizeof(xstats_names[count].name),
850                                         "rx_q%u_%s", i,
851                                         rte_virtio_rxq_stat_strings[t].name);
852                                 count++;
853                         }
854                 }
855
856                 for (i = 0; i < dev->data->nb_tx_queues; i++) {
857                         struct virtnet_tx *txvq = dev->data->tx_queues[i];
858                         if (txvq == NULL)
859                                 continue;
860                         for (t = 0; t < VIRTIO_NB_TXQ_XSTATS; t++) {
861                                 snprintf(xstats_names[count].name,
862                                         sizeof(xstats_names[count].name),
863                                         "tx_q%u_%s", i,
864                                         rte_virtio_txq_stat_strings[t].name);
865                                 count++;
866                         }
867                 }
868                 return count;
869         }
870         return nstats;
871 }
872
873 static int
874 virtio_dev_xstats_get(struct rte_eth_dev *dev, struct rte_eth_xstat *xstats,
875                       unsigned n)
876 {
877         unsigned i;
878         unsigned count = 0;
879
880         unsigned nstats = dev->data->nb_tx_queues * VIRTIO_NB_TXQ_XSTATS +
881                 dev->data->nb_rx_queues * VIRTIO_NB_RXQ_XSTATS;
882
883         if (n < nstats)
884                 return nstats;
885
886         for (i = 0; i < dev->data->nb_rx_queues; i++) {
887                 struct virtnet_rx *rxvq = dev->data->rx_queues[i];
888
889                 if (rxvq == NULL)
890                         continue;
891
892                 unsigned t;
893
894                 for (t = 0; t < VIRTIO_NB_RXQ_XSTATS; t++) {
895                         xstats[count].value = *(uint64_t *)(((char *)rxvq) +
896                                 rte_virtio_rxq_stat_strings[t].offset);
897                         xstats[count].id = count;
898                         count++;
899                 }
900         }
901
902         for (i = 0; i < dev->data->nb_tx_queues; i++) {
903                 struct virtnet_tx *txvq = dev->data->tx_queues[i];
904
905                 if (txvq == NULL)
906                         continue;
907
908                 unsigned t;
909
910                 for (t = 0; t < VIRTIO_NB_TXQ_XSTATS; t++) {
911                         xstats[count].value = *(uint64_t *)(((char *)txvq) +
912                                 rte_virtio_txq_stat_strings[t].offset);
913                         xstats[count].id = count;
914                         count++;
915                 }
916         }
917
918         return count;
919 }
920
921 static int
922 virtio_dev_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
923 {
924         virtio_update_stats(dev, stats);
925
926         return 0;
927 }
928
929 static void
930 virtio_dev_stats_reset(struct rte_eth_dev *dev)
931 {
932         unsigned int i;
933
934         for (i = 0; i < dev->data->nb_tx_queues; i++) {
935                 struct virtnet_tx *txvq = dev->data->tx_queues[i];
936                 if (txvq == NULL)
937                         continue;
938
939                 txvq->stats.packets = 0;
940                 txvq->stats.bytes = 0;
941                 txvq->stats.errors = 0;
942                 txvq->stats.multicast = 0;
943                 txvq->stats.broadcast = 0;
944                 memset(txvq->stats.size_bins, 0,
945                        sizeof(txvq->stats.size_bins[0]) * 8);
946         }
947
948         for (i = 0; i < dev->data->nb_rx_queues; i++) {
949                 struct virtnet_rx *rxvq = dev->data->rx_queues[i];
950                 if (rxvq == NULL)
951                         continue;
952
953                 rxvq->stats.packets = 0;
954                 rxvq->stats.bytes = 0;
955                 rxvq->stats.errors = 0;
956                 rxvq->stats.multicast = 0;
957                 rxvq->stats.broadcast = 0;
958                 memset(rxvq->stats.size_bins, 0,
959                        sizeof(rxvq->stats.size_bins[0]) * 8);
960         }
961 }
962
963 static void
964 virtio_set_hwaddr(struct virtio_hw *hw)
965 {
966         vtpci_write_dev_config(hw,
967                         offsetof(struct virtio_net_config, mac),
968                         &hw->mac_addr, ETHER_ADDR_LEN);
969 }
970
971 static void
972 virtio_get_hwaddr(struct virtio_hw *hw)
973 {
974         if (vtpci_with_feature(hw, VIRTIO_NET_F_MAC)) {
975                 vtpci_read_dev_config(hw,
976                         offsetof(struct virtio_net_config, mac),
977                         &hw->mac_addr, ETHER_ADDR_LEN);
978         } else {
979                 eth_random_addr(&hw->mac_addr[0]);
980                 virtio_set_hwaddr(hw);
981         }
982 }
983
984 static int
985 virtio_mac_table_set(struct virtio_hw *hw,
986                      const struct virtio_net_ctrl_mac *uc,
987                      const struct virtio_net_ctrl_mac *mc)
988 {
989         struct virtio_pmd_ctrl ctrl;
990         int err, len[2];
991
992         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
993                 PMD_DRV_LOG(INFO, "host does not support mac table");
994                 return -1;
995         }
996
997         ctrl.hdr.class = VIRTIO_NET_CTRL_MAC;
998         ctrl.hdr.cmd = VIRTIO_NET_CTRL_MAC_TABLE_SET;
999
1000         len[0] = uc->entries * ETHER_ADDR_LEN + sizeof(uc->entries);
1001         memcpy(ctrl.data, uc, len[0]);
1002
1003         len[1] = mc->entries * ETHER_ADDR_LEN + sizeof(mc->entries);
1004         memcpy(ctrl.data + len[0], mc, len[1]);
1005
1006         err = virtio_send_command(hw->cvq, &ctrl, len, 2);
1007         if (err != 0)
1008                 PMD_DRV_LOG(NOTICE, "mac table set failed: %d", err);
1009         return err;
1010 }
1011
1012 static int
1013 virtio_mac_addr_add(struct rte_eth_dev *dev, struct ether_addr *mac_addr,
1014                     uint32_t index, uint32_t vmdq __rte_unused)
1015 {
1016         struct virtio_hw *hw = dev->data->dev_private;
1017         const struct ether_addr *addrs = dev->data->mac_addrs;
1018         unsigned int i;
1019         struct virtio_net_ctrl_mac *uc, *mc;
1020
1021         if (index >= VIRTIO_MAX_MAC_ADDRS) {
1022                 PMD_DRV_LOG(ERR, "mac address index %u out of range", index);
1023                 return -EINVAL;
1024         }
1025
1026         uc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(uc->entries));
1027         uc->entries = 0;
1028         mc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(mc->entries));
1029         mc->entries = 0;
1030
1031         for (i = 0; i < VIRTIO_MAX_MAC_ADDRS; i++) {
1032                 const struct ether_addr *addr
1033                         = (i == index) ? mac_addr : addrs + i;
1034                 struct virtio_net_ctrl_mac *tbl
1035                         = is_multicast_ether_addr(addr) ? mc : uc;
1036
1037                 memcpy(&tbl->macs[tbl->entries++], addr, ETHER_ADDR_LEN);
1038         }
1039
1040         return virtio_mac_table_set(hw, uc, mc);
1041 }
1042
1043 static void
1044 virtio_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
1045 {
1046         struct virtio_hw *hw = dev->data->dev_private;
1047         struct ether_addr *addrs = dev->data->mac_addrs;
1048         struct virtio_net_ctrl_mac *uc, *mc;
1049         unsigned int i;
1050
1051         if (index >= VIRTIO_MAX_MAC_ADDRS) {
1052                 PMD_DRV_LOG(ERR, "mac address index %u out of range", index);
1053                 return;
1054         }
1055
1056         uc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(uc->entries));
1057         uc->entries = 0;
1058         mc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(mc->entries));
1059         mc->entries = 0;
1060
1061         for (i = 0; i < VIRTIO_MAX_MAC_ADDRS; i++) {
1062                 struct virtio_net_ctrl_mac *tbl;
1063
1064                 if (i == index || is_zero_ether_addr(addrs + i))
1065                         continue;
1066
1067                 tbl = is_multicast_ether_addr(addrs + i) ? mc : uc;
1068                 memcpy(&tbl->macs[tbl->entries++], addrs + i, ETHER_ADDR_LEN);
1069         }
1070
1071         virtio_mac_table_set(hw, uc, mc);
1072 }
1073
1074 static int
1075 virtio_mac_addr_set(struct rte_eth_dev *dev, struct ether_addr *mac_addr)
1076 {
1077         struct virtio_hw *hw = dev->data->dev_private;
1078
1079         memcpy(hw->mac_addr, mac_addr, ETHER_ADDR_LEN);
1080
1081         /* Use atomic update if available */
1082         if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
1083                 struct virtio_pmd_ctrl ctrl;
1084                 int len = ETHER_ADDR_LEN;
1085
1086                 ctrl.hdr.class = VIRTIO_NET_CTRL_MAC;
1087                 ctrl.hdr.cmd = VIRTIO_NET_CTRL_MAC_ADDR_SET;
1088
1089                 memcpy(ctrl.data, mac_addr, ETHER_ADDR_LEN);
1090                 return virtio_send_command(hw->cvq, &ctrl, &len, 1);
1091         }
1092
1093         if (!vtpci_with_feature(hw, VIRTIO_NET_F_MAC))
1094                 return -ENOTSUP;
1095
1096         virtio_set_hwaddr(hw);
1097         return 0;
1098 }
1099
1100 static int
1101 virtio_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
1102 {
1103         struct virtio_hw *hw = dev->data->dev_private;
1104         struct virtio_pmd_ctrl ctrl;
1105         int len;
1106
1107         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VLAN))
1108                 return -ENOTSUP;
1109
1110         ctrl.hdr.class = VIRTIO_NET_CTRL_VLAN;
1111         ctrl.hdr.cmd = on ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL;
1112         memcpy(ctrl.data, &vlan_id, sizeof(vlan_id));
1113         len = sizeof(vlan_id);
1114
1115         return virtio_send_command(hw->cvq, &ctrl, &len, 1);
1116 }
1117
1118 static int
1119 virtio_intr_enable(struct rte_eth_dev *dev)
1120 {
1121         struct virtio_hw *hw = dev->data->dev_private;
1122
1123         if (rte_intr_enable(dev->intr_handle) < 0)
1124                 return -1;
1125
1126         if (!hw->virtio_user_dev)
1127                 hw->use_msix = vtpci_msix_detect(RTE_ETH_DEV_TO_PCI(dev));
1128
1129         return 0;
1130 }
1131
1132 static int
1133 virtio_intr_disable(struct rte_eth_dev *dev)
1134 {
1135         struct virtio_hw *hw = dev->data->dev_private;
1136
1137         if (rte_intr_disable(dev->intr_handle) < 0)
1138                 return -1;
1139
1140         if (!hw->virtio_user_dev)
1141                 hw->use_msix = vtpci_msix_detect(RTE_ETH_DEV_TO_PCI(dev));
1142
1143         return 0;
1144 }
1145
1146 static int
1147 virtio_negotiate_features(struct virtio_hw *hw, uint64_t req_features)
1148 {
1149         uint64_t host_features;
1150
1151         /* Prepare guest_features: feature that driver wants to support */
1152         PMD_INIT_LOG(DEBUG, "guest_features before negotiate = %" PRIx64,
1153                 req_features);
1154
1155         /* Read device(host) feature bits */
1156         host_features = VTPCI_OPS(hw)->get_features(hw);
1157         PMD_INIT_LOG(DEBUG, "host_features before negotiate = %" PRIx64,
1158                 host_features);
1159
1160         /* If supported, ensure MTU value is valid before acknowledging it. */
1161         if (host_features & req_features & (1ULL << VIRTIO_NET_F_MTU)) {
1162                 struct virtio_net_config config;
1163
1164                 vtpci_read_dev_config(hw,
1165                         offsetof(struct virtio_net_config, mtu),
1166                         &config.mtu, sizeof(config.mtu));
1167
1168                 if (config.mtu < ETHER_MIN_MTU)
1169                         req_features &= ~(1ULL << VIRTIO_NET_F_MTU);
1170         }
1171
1172         /*
1173          * Negotiate features: Subset of device feature bits are written back
1174          * guest feature bits.
1175          */
1176         hw->guest_features = req_features;
1177         hw->guest_features = vtpci_negotiate_features(hw, host_features);
1178         PMD_INIT_LOG(DEBUG, "features after negotiate = %" PRIx64,
1179                 hw->guest_features);
1180
1181         if (hw->modern) {
1182                 if (!vtpci_with_feature(hw, VIRTIO_F_VERSION_1)) {
1183                         PMD_INIT_LOG(ERR,
1184                                 "VIRTIO_F_VERSION_1 features is not enabled.");
1185                         return -1;
1186                 }
1187                 vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_FEATURES_OK);
1188                 if (!(vtpci_get_status(hw) & VIRTIO_CONFIG_STATUS_FEATURES_OK)) {
1189                         PMD_INIT_LOG(ERR,
1190                                 "failed to set FEATURES_OK status!");
1191                         return -1;
1192                 }
1193         }
1194
1195         hw->req_guest_features = req_features;
1196
1197         return 0;
1198 }
1199
1200 int
1201 virtio_dev_pause(struct rte_eth_dev *dev)
1202 {
1203         struct virtio_hw *hw = dev->data->dev_private;
1204
1205         rte_spinlock_lock(&hw->state_lock);
1206
1207         if (hw->started == 0) {
1208                 /* Device is just stopped. */
1209                 rte_spinlock_unlock(&hw->state_lock);
1210                 return -1;
1211         }
1212         hw->started = 0;
1213         /*
1214          * Prevent the worker threads from touching queues to avoid contention,
1215          * 1 ms should be enough for the ongoing Tx function to finish.
1216          */
1217         rte_delay_ms(1);
1218         return 0;
1219 }
1220
1221 /*
1222  * Recover hw state to let the worker threads continue.
1223  */
1224 void
1225 virtio_dev_resume(struct rte_eth_dev *dev)
1226 {
1227         struct virtio_hw *hw = dev->data->dev_private;
1228
1229         hw->started = 1;
1230         rte_spinlock_unlock(&hw->state_lock);
1231 }
1232
1233 /*
1234  * Should be called only after device is paused.
1235  */
1236 int
1237 virtio_inject_pkts(struct rte_eth_dev *dev, struct rte_mbuf **tx_pkts,
1238                 int nb_pkts)
1239 {
1240         struct virtio_hw *hw = dev->data->dev_private;
1241         struct virtnet_tx *txvq = dev->data->tx_queues[0];
1242         int ret;
1243
1244         hw->inject_pkts = tx_pkts;
1245         ret = dev->tx_pkt_burst(txvq, tx_pkts, nb_pkts);
1246         hw->inject_pkts = NULL;
1247
1248         return ret;
1249 }
1250
1251 static void
1252 virtio_notify_peers(struct rte_eth_dev *dev)
1253 {
1254         struct virtio_hw *hw = dev->data->dev_private;
1255         struct virtnet_rx *rxvq;
1256         struct rte_mbuf *rarp_mbuf;
1257
1258         if (!dev->data->rx_queues)
1259                 return;
1260
1261         rxvq = dev->data->rx_queues[0];
1262         if (!rxvq)
1263                 return;
1264
1265         rarp_mbuf = rte_net_make_rarp_packet(rxvq->mpool,
1266                         (struct ether_addr *)hw->mac_addr);
1267         if (rarp_mbuf == NULL) {
1268                 PMD_DRV_LOG(ERR, "failed to make RARP packet.");
1269                 return;
1270         }
1271
1272         /* If virtio port just stopped, no need to send RARP */
1273         if (virtio_dev_pause(dev) < 0) {
1274                 rte_pktmbuf_free(rarp_mbuf);
1275                 return;
1276         }
1277
1278         virtio_inject_pkts(dev, &rarp_mbuf, 1);
1279         virtio_dev_resume(dev);
1280 }
1281
1282 static void
1283 virtio_ack_link_announce(struct rte_eth_dev *dev)
1284 {
1285         struct virtio_hw *hw = dev->data->dev_private;
1286         struct virtio_pmd_ctrl ctrl;
1287
1288         ctrl.hdr.class = VIRTIO_NET_CTRL_ANNOUNCE;
1289         ctrl.hdr.cmd = VIRTIO_NET_CTRL_ANNOUNCE_ACK;
1290
1291         virtio_send_command(hw->cvq, &ctrl, NULL, 0);
1292 }
1293
1294 /*
1295  * Process virtio config changed interrupt. Call the callback
1296  * if link state changed, generate gratuitous RARP packet if
1297  * the status indicates an ANNOUNCE.
1298  */
1299 void
1300 virtio_interrupt_handler(void *param)
1301 {
1302         struct rte_eth_dev *dev = param;
1303         struct virtio_hw *hw = dev->data->dev_private;
1304         uint8_t isr;
1305         uint16_t status;
1306
1307         /* Read interrupt status which clears interrupt */
1308         isr = vtpci_isr(hw);
1309         PMD_DRV_LOG(INFO, "interrupt status = %#x", isr);
1310
1311         if (virtio_intr_enable(dev) < 0)
1312                 PMD_DRV_LOG(ERR, "interrupt enable failed");
1313
1314         if (isr & VIRTIO_PCI_ISR_CONFIG) {
1315                 if (virtio_dev_link_update(dev, 0) == 0)
1316                         _rte_eth_dev_callback_process(dev,
1317                                                       RTE_ETH_EVENT_INTR_LSC,
1318                                                       NULL);
1319
1320                 if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
1321                         vtpci_read_dev_config(hw,
1322                                 offsetof(struct virtio_net_config, status),
1323                                 &status, sizeof(status));
1324                         if (status & VIRTIO_NET_S_ANNOUNCE) {
1325                                 virtio_notify_peers(dev);
1326                                 if (hw->cvq)
1327                                         virtio_ack_link_announce(dev);
1328                         }
1329                 }
1330         }
1331 }
1332
1333 /* set rx and tx handlers according to what is supported */
1334 static void
1335 set_rxtx_funcs(struct rte_eth_dev *eth_dev)
1336 {
1337         struct virtio_hw *hw = eth_dev->data->dev_private;
1338
1339         if (hw->use_simple_rx) {
1340                 PMD_INIT_LOG(INFO, "virtio: using simple Rx path on port %u",
1341                         eth_dev->data->port_id);
1342                 eth_dev->rx_pkt_burst = virtio_recv_pkts_vec;
1343         } else if (hw->use_inorder_rx) {
1344                 PMD_INIT_LOG(INFO,
1345                         "virtio: using inorder mergeable buffer Rx path on port %u",
1346                         eth_dev->data->port_id);
1347                 eth_dev->rx_pkt_burst = &virtio_recv_mergeable_pkts_inorder;
1348         } else if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF)) {
1349                 PMD_INIT_LOG(INFO,
1350                         "virtio: using mergeable buffer Rx path on port %u",
1351                         eth_dev->data->port_id);
1352                 eth_dev->rx_pkt_burst = &virtio_recv_mergeable_pkts;
1353         } else {
1354                 PMD_INIT_LOG(INFO, "virtio: using standard Rx path on port %u",
1355                         eth_dev->data->port_id);
1356                 eth_dev->rx_pkt_burst = &virtio_recv_pkts;
1357         }
1358
1359         if (hw->use_inorder_tx) {
1360                 PMD_INIT_LOG(INFO, "virtio: using inorder Tx path on port %u",
1361                         eth_dev->data->port_id);
1362                 eth_dev->tx_pkt_burst = virtio_xmit_pkts_inorder;
1363         } else {
1364                 PMD_INIT_LOG(INFO, "virtio: using standard Tx path on port %u",
1365                         eth_dev->data->port_id);
1366                 eth_dev->tx_pkt_burst = virtio_xmit_pkts;
1367         }
1368 }
1369
1370 /* Only support 1:1 queue/interrupt mapping so far.
1371  * TODO: support n:1 queue/interrupt mapping when there are limited number of
1372  * interrupt vectors (<N+1).
1373  */
1374 static int
1375 virtio_queues_bind_intr(struct rte_eth_dev *dev)
1376 {
1377         uint32_t i;
1378         struct virtio_hw *hw = dev->data->dev_private;
1379
1380         PMD_INIT_LOG(INFO, "queue/interrupt binding");
1381         for (i = 0; i < dev->data->nb_rx_queues; ++i) {
1382                 dev->intr_handle->intr_vec[i] = i + 1;
1383                 if (VTPCI_OPS(hw)->set_queue_irq(hw, hw->vqs[i * 2], i + 1) ==
1384                                                  VIRTIO_MSI_NO_VECTOR) {
1385                         PMD_DRV_LOG(ERR, "failed to set queue vector");
1386                         return -EBUSY;
1387                 }
1388         }
1389
1390         return 0;
1391 }
1392
1393 static void
1394 virtio_queues_unbind_intr(struct rte_eth_dev *dev)
1395 {
1396         uint32_t i;
1397         struct virtio_hw *hw = dev->data->dev_private;
1398
1399         PMD_INIT_LOG(INFO, "queue/interrupt unbinding");
1400         for (i = 0; i < dev->data->nb_rx_queues; ++i)
1401                 VTPCI_OPS(hw)->set_queue_irq(hw,
1402                                              hw->vqs[i * VTNET_CQ],
1403                                              VIRTIO_MSI_NO_VECTOR);
1404 }
1405
1406 static int
1407 virtio_configure_intr(struct rte_eth_dev *dev)
1408 {
1409         struct virtio_hw *hw = dev->data->dev_private;
1410
1411         if (!rte_intr_cap_multiple(dev->intr_handle)) {
1412                 PMD_INIT_LOG(ERR, "Multiple intr vector not supported");
1413                 return -ENOTSUP;
1414         }
1415
1416         if (rte_intr_efd_enable(dev->intr_handle, dev->data->nb_rx_queues)) {
1417                 PMD_INIT_LOG(ERR, "Fail to create eventfd");
1418                 return -1;
1419         }
1420
1421         if (!dev->intr_handle->intr_vec) {
1422                 dev->intr_handle->intr_vec =
1423                         rte_zmalloc("intr_vec",
1424                                     hw->max_queue_pairs * sizeof(int), 0);
1425                 if (!dev->intr_handle->intr_vec) {
1426                         PMD_INIT_LOG(ERR, "Failed to allocate %u rxq vectors",
1427                                      hw->max_queue_pairs);
1428                         return -ENOMEM;
1429                 }
1430         }
1431
1432         /* Re-register callback to update max_intr */
1433         rte_intr_callback_unregister(dev->intr_handle,
1434                                      virtio_interrupt_handler,
1435                                      dev);
1436         rte_intr_callback_register(dev->intr_handle,
1437                                    virtio_interrupt_handler,
1438                                    dev);
1439
1440         /* DO NOT try to remove this! This function will enable msix, or QEMU
1441          * will encounter SIGSEGV when DRIVER_OK is sent.
1442          * And for legacy devices, this should be done before queue/vec binding
1443          * to change the config size from 20 to 24, or VIRTIO_MSI_QUEUE_VECTOR
1444          * (22) will be ignored.
1445          */
1446         if (virtio_intr_enable(dev) < 0) {
1447                 PMD_DRV_LOG(ERR, "interrupt enable failed");
1448                 return -1;
1449         }
1450
1451         if (virtio_queues_bind_intr(dev) < 0) {
1452                 PMD_INIT_LOG(ERR, "Failed to bind queue/interrupt");
1453                 return -1;
1454         }
1455
1456         return 0;
1457 }
1458
1459 /* reset device and renegotiate features if needed */
1460 static int
1461 virtio_init_device(struct rte_eth_dev *eth_dev, uint64_t req_features)
1462 {
1463         struct virtio_hw *hw = eth_dev->data->dev_private;
1464         struct virtio_net_config *config;
1465         struct virtio_net_config local_config;
1466         struct rte_pci_device *pci_dev = NULL;
1467         int ret;
1468
1469         /* Reset the device although not necessary at startup */
1470         vtpci_reset(hw);
1471
1472         if (hw->vqs) {
1473                 virtio_dev_free_mbufs(eth_dev);
1474                 virtio_free_queues(hw);
1475         }
1476
1477         /* Tell the host we've noticed this device. */
1478         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_ACK);
1479
1480         /* Tell the host we've known how to drive the device. */
1481         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_DRIVER);
1482         if (virtio_negotiate_features(hw, req_features) < 0)
1483                 return -1;
1484
1485         if (!hw->virtio_user_dev) {
1486                 pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
1487                 rte_eth_copy_pci_info(eth_dev, pci_dev);
1488         }
1489
1490         /* If host does not support both status and MSI-X then disable LSC */
1491         if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS) &&
1492             hw->use_msix != VIRTIO_MSIX_NONE)
1493                 eth_dev->data->dev_flags |= RTE_ETH_DEV_INTR_LSC;
1494         else
1495                 eth_dev->data->dev_flags &= ~RTE_ETH_DEV_INTR_LSC;
1496
1497         /* Setting up rx_header size for the device */
1498         if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF) ||
1499             vtpci_with_feature(hw, VIRTIO_F_VERSION_1) ||
1500             vtpci_with_feature(hw, VIRTIO_F_RING_PACKED))
1501                 hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr_mrg_rxbuf);
1502         else
1503                 hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr);
1504
1505         /* Copy the permanent MAC address to: virtio_hw */
1506         virtio_get_hwaddr(hw);
1507         ether_addr_copy((struct ether_addr *) hw->mac_addr,
1508                         &eth_dev->data->mac_addrs[0]);
1509         PMD_INIT_LOG(DEBUG,
1510                      "PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X",
1511                      hw->mac_addr[0], hw->mac_addr[1], hw->mac_addr[2],
1512                      hw->mac_addr[3], hw->mac_addr[4], hw->mac_addr[5]);
1513
1514         if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VQ)) {
1515                 config = &local_config;
1516
1517                 vtpci_read_dev_config(hw,
1518                         offsetof(struct virtio_net_config, mac),
1519                         &config->mac, sizeof(config->mac));
1520
1521                 if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
1522                         vtpci_read_dev_config(hw,
1523                                 offsetof(struct virtio_net_config, status),
1524                                 &config->status, sizeof(config->status));
1525                 } else {
1526                         PMD_INIT_LOG(DEBUG,
1527                                      "VIRTIO_NET_F_STATUS is not supported");
1528                         config->status = 0;
1529                 }
1530
1531                 if (vtpci_with_feature(hw, VIRTIO_NET_F_MQ)) {
1532                         vtpci_read_dev_config(hw,
1533                                 offsetof(struct virtio_net_config, max_virtqueue_pairs),
1534                                 &config->max_virtqueue_pairs,
1535                                 sizeof(config->max_virtqueue_pairs));
1536                 } else {
1537                         PMD_INIT_LOG(DEBUG,
1538                                      "VIRTIO_NET_F_MQ is not supported");
1539                         config->max_virtqueue_pairs = 1;
1540                 }
1541
1542                 hw->max_queue_pairs = config->max_virtqueue_pairs;
1543
1544                 if (vtpci_with_feature(hw, VIRTIO_NET_F_MTU)) {
1545                         vtpci_read_dev_config(hw,
1546                                 offsetof(struct virtio_net_config, mtu),
1547                                 &config->mtu,
1548                                 sizeof(config->mtu));
1549
1550                         /*
1551                          * MTU value has already been checked at negotiation
1552                          * time, but check again in case it has changed since
1553                          * then, which should not happen.
1554                          */
1555                         if (config->mtu < ETHER_MIN_MTU) {
1556                                 PMD_INIT_LOG(ERR, "invalid max MTU value (%u)",
1557                                                 config->mtu);
1558                                 return -1;
1559                         }
1560
1561                         hw->max_mtu = config->mtu;
1562                         /* Set initial MTU to maximum one supported by vhost */
1563                         eth_dev->data->mtu = config->mtu;
1564
1565                 } else {
1566                         hw->max_mtu = VIRTIO_MAX_RX_PKTLEN - ETHER_HDR_LEN -
1567                                 VLAN_TAG_LEN - hw->vtnet_hdr_size;
1568                 }
1569
1570                 PMD_INIT_LOG(DEBUG, "config->max_virtqueue_pairs=%d",
1571                                 config->max_virtqueue_pairs);
1572                 PMD_INIT_LOG(DEBUG, "config->status=%d", config->status);
1573                 PMD_INIT_LOG(DEBUG,
1574                                 "PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X",
1575                                 config->mac[0], config->mac[1],
1576                                 config->mac[2], config->mac[3],
1577                                 config->mac[4], config->mac[5]);
1578         } else {
1579                 PMD_INIT_LOG(DEBUG, "config->max_virtqueue_pairs=1");
1580                 hw->max_queue_pairs = 1;
1581                 hw->max_mtu = VIRTIO_MAX_RX_PKTLEN - ETHER_HDR_LEN -
1582                         VLAN_TAG_LEN - hw->vtnet_hdr_size;
1583         }
1584
1585         ret = virtio_alloc_queues(eth_dev);
1586         if (ret < 0)
1587                 return ret;
1588
1589         if (eth_dev->data->dev_conf.intr_conf.rxq) {
1590                 if (virtio_configure_intr(eth_dev) < 0) {
1591                         PMD_INIT_LOG(ERR, "failed to configure interrupt");
1592                         return -1;
1593                 }
1594         }
1595
1596         vtpci_reinit_complete(hw);
1597
1598         if (pci_dev)
1599                 PMD_INIT_LOG(DEBUG, "port %d vendorID=0x%x deviceID=0x%x",
1600                         eth_dev->data->port_id, pci_dev->id.vendor_id,
1601                         pci_dev->id.device_id);
1602
1603         return 0;
1604 }
1605
1606 /*
1607  * Remap the PCI device again (IO port map for legacy device and
1608  * memory map for modern device), so that the secondary process
1609  * could have the PCI initiated correctly.
1610  */
1611 static int
1612 virtio_remap_pci(struct rte_pci_device *pci_dev, struct virtio_hw *hw)
1613 {
1614         if (hw->modern) {
1615                 /*
1616                  * We don't have to re-parse the PCI config space, since
1617                  * rte_pci_map_device() makes sure the mapped address
1618                  * in secondary process would equal to the one mapped in
1619                  * the primary process: error will be returned if that
1620                  * requirement is not met.
1621                  *
1622                  * That said, we could simply reuse all cap pointers
1623                  * (such as dev_cfg, common_cfg, etc.) parsed from the
1624                  * primary process, which is stored in shared memory.
1625                  */
1626                 if (rte_pci_map_device(pci_dev)) {
1627                         PMD_INIT_LOG(DEBUG, "failed to map pci device!");
1628                         return -1;
1629                 }
1630         } else {
1631                 if (rte_pci_ioport_map(pci_dev, 0, VTPCI_IO(hw)) < 0)
1632                         return -1;
1633         }
1634
1635         return 0;
1636 }
1637
1638 static void
1639 virtio_set_vtpci_ops(struct virtio_hw *hw)
1640 {
1641 #ifdef RTE_VIRTIO_USER
1642         if (hw->virtio_user_dev)
1643                 VTPCI_OPS(hw) = &virtio_user_ops;
1644         else
1645 #endif
1646         if (hw->modern)
1647                 VTPCI_OPS(hw) = &modern_ops;
1648         else
1649                 VTPCI_OPS(hw) = &legacy_ops;
1650 }
1651
1652 /*
1653  * This function is based on probe() function in virtio_pci.c
1654  * It returns 0 on success.
1655  */
1656 int
1657 eth_virtio_dev_init(struct rte_eth_dev *eth_dev)
1658 {
1659         struct virtio_hw *hw = eth_dev->data->dev_private;
1660         int ret;
1661
1662         RTE_BUILD_BUG_ON(RTE_PKTMBUF_HEADROOM < sizeof(struct virtio_net_hdr_mrg_rxbuf));
1663
1664         eth_dev->dev_ops = &virtio_eth_dev_ops;
1665
1666         if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
1667                 if (!hw->virtio_user_dev) {
1668                         ret = virtio_remap_pci(RTE_ETH_DEV_TO_PCI(eth_dev), hw);
1669                         if (ret)
1670                                 return ret;
1671                 }
1672
1673                 virtio_set_vtpci_ops(hw);
1674                 set_rxtx_funcs(eth_dev);
1675
1676                 return 0;
1677         }
1678
1679         /* Allocate memory for storing MAC addresses */
1680         eth_dev->data->mac_addrs = rte_zmalloc("virtio", VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN, 0);
1681         if (eth_dev->data->mac_addrs == NULL) {
1682                 PMD_INIT_LOG(ERR,
1683                         "Failed to allocate %d bytes needed to store MAC addresses",
1684                         VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN);
1685                 return -ENOMEM;
1686         }
1687
1688         hw->port_id = eth_dev->data->port_id;
1689         /* For virtio_user case the hw->virtio_user_dev is populated by
1690          * virtio_user_eth_dev_alloc() before eth_virtio_dev_init() is called.
1691          */
1692         if (!hw->virtio_user_dev) {
1693                 ret = vtpci_init(RTE_ETH_DEV_TO_PCI(eth_dev), hw);
1694                 if (ret)
1695                         goto out;
1696         }
1697
1698         /* reset device and negotiate default features */
1699         ret = virtio_init_device(eth_dev, VIRTIO_PMD_DEFAULT_GUEST_FEATURES);
1700         if (ret < 0)
1701                 goto out;
1702
1703         return 0;
1704
1705 out:
1706         rte_free(eth_dev->data->mac_addrs);
1707         return ret;
1708 }
1709
1710 static int
1711 eth_virtio_dev_uninit(struct rte_eth_dev *eth_dev)
1712 {
1713         PMD_INIT_FUNC_TRACE();
1714
1715         if (rte_eal_process_type() == RTE_PROC_SECONDARY)
1716                 return 0;
1717
1718         virtio_dev_stop(eth_dev);
1719         virtio_dev_close(eth_dev);
1720
1721         eth_dev->dev_ops = NULL;
1722         eth_dev->tx_pkt_burst = NULL;
1723         eth_dev->rx_pkt_burst = NULL;
1724
1725         if (eth_dev->device)
1726                 rte_pci_unmap_device(RTE_ETH_DEV_TO_PCI(eth_dev));
1727
1728         PMD_INIT_LOG(DEBUG, "dev_uninit completed");
1729
1730         return 0;
1731 }
1732
1733 static int vdpa_check_handler(__rte_unused const char *key,
1734                 const char *value, __rte_unused void *opaque)
1735 {
1736         if (strcmp(value, "1"))
1737                 return -1;
1738
1739         return 0;
1740 }
1741
1742 static int
1743 vdpa_mode_selected(struct rte_devargs *devargs)
1744 {
1745         struct rte_kvargs *kvlist;
1746         const char *key = "vdpa";
1747         int ret = 0;
1748
1749         if (devargs == NULL)
1750                 return 0;
1751
1752         kvlist = rte_kvargs_parse(devargs->args, NULL);
1753         if (kvlist == NULL)
1754                 return 0;
1755
1756         if (!rte_kvargs_count(kvlist, key))
1757                 goto exit;
1758
1759         /* vdpa mode selected when there's a key-value pair: vdpa=1 */
1760         if (rte_kvargs_process(kvlist, key,
1761                                 vdpa_check_handler, NULL) < 0) {
1762                 goto exit;
1763         }
1764         ret = 1;
1765
1766 exit:
1767         rte_kvargs_free(kvlist);
1768         return ret;
1769 }
1770
1771 static int eth_virtio_pci_probe(struct rte_pci_driver *pci_drv __rte_unused,
1772         struct rte_pci_device *pci_dev)
1773 {
1774         if (rte_eal_iopl_init() != 0) {
1775                 PMD_INIT_LOG(ERR, "IOPL call failed - cannot use virtio PMD");
1776                 return 1;
1777         }
1778
1779         /* virtio pmd skips probe if device needs to work in vdpa mode */
1780         if (vdpa_mode_selected(pci_dev->device.devargs))
1781                 return 1;
1782
1783         return rte_eth_dev_pci_generic_probe(pci_dev, sizeof(struct virtio_hw),
1784                 eth_virtio_dev_init);
1785 }
1786
1787 static int eth_virtio_pci_remove(struct rte_pci_device *pci_dev)
1788 {
1789         return rte_eth_dev_pci_generic_remove(pci_dev, eth_virtio_dev_uninit);
1790 }
1791
1792 static struct rte_pci_driver rte_virtio_pmd = {
1793         .driver = {
1794                 .name = "net_virtio",
1795         },
1796         .id_table = pci_id_virtio_map,
1797         .drv_flags = 0,
1798         .probe = eth_virtio_pci_probe,
1799         .remove = eth_virtio_pci_remove,
1800 };
1801
1802 RTE_INIT(rte_virtio_pmd_init)
1803 {
1804         rte_eal_iopl_init();
1805         rte_pci_register(&rte_virtio_pmd);
1806 }
1807
1808 static bool
1809 rx_offload_enabled(struct virtio_hw *hw)
1810 {
1811         return vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_CSUM) ||
1812                 vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_TSO4) ||
1813                 vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_TSO6);
1814 }
1815
1816 static bool
1817 tx_offload_enabled(struct virtio_hw *hw)
1818 {
1819         return vtpci_with_feature(hw, VIRTIO_NET_F_CSUM) ||
1820                 vtpci_with_feature(hw, VIRTIO_NET_F_HOST_TSO4) ||
1821                 vtpci_with_feature(hw, VIRTIO_NET_F_HOST_TSO6);
1822 }
1823
1824 /*
1825  * Configure virtio device
1826  * It returns 0 on success.
1827  */
1828 static int
1829 virtio_dev_configure(struct rte_eth_dev *dev)
1830 {
1831         const struct rte_eth_rxmode *rxmode = &dev->data->dev_conf.rxmode;
1832         const struct rte_eth_txmode *txmode = &dev->data->dev_conf.txmode;
1833         struct virtio_hw *hw = dev->data->dev_private;
1834         uint64_t rx_offloads = rxmode->offloads;
1835         uint64_t tx_offloads = txmode->offloads;
1836         uint64_t req_features;
1837         int ret;
1838
1839         PMD_INIT_LOG(DEBUG, "configure");
1840         req_features = VIRTIO_PMD_DEFAULT_GUEST_FEATURES;
1841
1842         if (dev->data->dev_conf.intr_conf.rxq) {
1843                 ret = virtio_init_device(dev, hw->req_guest_features);
1844                 if (ret < 0)
1845                         return ret;
1846         }
1847
1848         if (rx_offloads & (DEV_RX_OFFLOAD_UDP_CKSUM |
1849                            DEV_RX_OFFLOAD_TCP_CKSUM))
1850                 req_features |= (1ULL << VIRTIO_NET_F_GUEST_CSUM);
1851
1852         if (rx_offloads & DEV_RX_OFFLOAD_TCP_LRO)
1853                 req_features |=
1854                         (1ULL << VIRTIO_NET_F_GUEST_TSO4) |
1855                         (1ULL << VIRTIO_NET_F_GUEST_TSO6);
1856
1857         if (tx_offloads & (DEV_TX_OFFLOAD_UDP_CKSUM |
1858                            DEV_TX_OFFLOAD_TCP_CKSUM))
1859                 req_features |= (1ULL << VIRTIO_NET_F_CSUM);
1860
1861         if (tx_offloads & DEV_TX_OFFLOAD_TCP_TSO)
1862                 req_features |=
1863                         (1ULL << VIRTIO_NET_F_HOST_TSO4) |
1864                         (1ULL << VIRTIO_NET_F_HOST_TSO6);
1865
1866         /* if request features changed, reinit the device */
1867         if (req_features != hw->req_guest_features) {
1868                 ret = virtio_init_device(dev, req_features);
1869                 if (ret < 0)
1870                         return ret;
1871         }
1872
1873         if ((rx_offloads & (DEV_RX_OFFLOAD_UDP_CKSUM |
1874                             DEV_RX_OFFLOAD_TCP_CKSUM)) &&
1875                 !vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_CSUM)) {
1876                 PMD_DRV_LOG(ERR,
1877                         "rx checksum not available on this host");
1878                 return -ENOTSUP;
1879         }
1880
1881         if ((rx_offloads & DEV_RX_OFFLOAD_TCP_LRO) &&
1882                 (!vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_TSO4) ||
1883                  !vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_TSO6))) {
1884                 PMD_DRV_LOG(ERR,
1885                         "Large Receive Offload not available on this host");
1886                 return -ENOTSUP;
1887         }
1888
1889         /* start control queue */
1890         if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VQ))
1891                 virtio_dev_cq_start(dev);
1892
1893         if (rx_offloads & DEV_RX_OFFLOAD_VLAN_STRIP)
1894                 hw->vlan_strip = 1;
1895
1896         if ((rx_offloads & DEV_RX_OFFLOAD_VLAN_FILTER)
1897             && !vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VLAN)) {
1898                 PMD_DRV_LOG(ERR,
1899                             "vlan filtering not available on this host");
1900                 return -ENOTSUP;
1901         }
1902
1903         hw->has_tx_offload = tx_offload_enabled(hw);
1904         hw->has_rx_offload = rx_offload_enabled(hw);
1905
1906         if (dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
1907                 /* Enable vector (0) for Link State Intrerrupt */
1908                 if (VTPCI_OPS(hw)->set_config_irq(hw, 0) ==
1909                                 VIRTIO_MSI_NO_VECTOR) {
1910                         PMD_DRV_LOG(ERR, "failed to set config vector");
1911                         return -EBUSY;
1912                 }
1913
1914         rte_spinlock_init(&hw->state_lock);
1915
1916         hw->use_simple_rx = 1;
1917
1918         if (vtpci_with_feature(hw, VIRTIO_F_IN_ORDER)) {
1919                 hw->use_inorder_tx = 1;
1920                 if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF) &&
1921                     !vtpci_packed_queue(hw)) {
1922                         hw->use_inorder_rx = 1;
1923                         hw->use_simple_rx = 0;
1924                 } else {
1925                         hw->use_inorder_rx = 0;
1926                 }
1927         }
1928
1929 #if defined RTE_ARCH_ARM64 || defined RTE_ARCH_ARM
1930         if (!rte_cpu_get_flag_enabled(RTE_CPUFLAG_NEON)) {
1931                 hw->use_simple_rx = 0;
1932         }
1933 #endif
1934         if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF)) {
1935                  hw->use_simple_rx = 0;
1936         }
1937
1938         if (rx_offloads & (DEV_RX_OFFLOAD_UDP_CKSUM |
1939                            DEV_RX_OFFLOAD_TCP_CKSUM |
1940                            DEV_RX_OFFLOAD_TCP_LRO |
1941                            DEV_RX_OFFLOAD_VLAN_STRIP))
1942                 hw->use_simple_rx = 0;
1943
1944         hw->opened = true;
1945
1946         return 0;
1947 }
1948
1949
1950 static int
1951 virtio_dev_start(struct rte_eth_dev *dev)
1952 {
1953         uint16_t nb_queues, i;
1954         struct virtnet_rx *rxvq;
1955         struct virtnet_tx *txvq __rte_unused;
1956         struct virtio_hw *hw = dev->data->dev_private;
1957         int ret;
1958
1959         /* Finish the initialization of the queues */
1960         for (i = 0; i < dev->data->nb_rx_queues; i++) {
1961                 ret = virtio_dev_rx_queue_setup_finish(dev, i);
1962                 if (ret < 0)
1963                         return ret;
1964         }
1965         for (i = 0; i < dev->data->nb_tx_queues; i++) {
1966                 ret = virtio_dev_tx_queue_setup_finish(dev, i);
1967                 if (ret < 0)
1968                         return ret;
1969         }
1970
1971         /* check if lsc interrupt feature is enabled */
1972         if (dev->data->dev_conf.intr_conf.lsc) {
1973                 if (!(dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)) {
1974                         PMD_DRV_LOG(ERR, "link status not supported by host");
1975                         return -ENOTSUP;
1976                 }
1977         }
1978
1979         /* Enable uio/vfio intr/eventfd mapping: althrough we already did that
1980          * in device configure, but it could be unmapped  when device is
1981          * stopped.
1982          */
1983         if (dev->data->dev_conf.intr_conf.lsc ||
1984             dev->data->dev_conf.intr_conf.rxq) {
1985                 virtio_intr_disable(dev);
1986
1987                 /* Setup interrupt callback  */
1988                 if (dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
1989                         rte_intr_callback_register(dev->intr_handle,
1990                                                    virtio_interrupt_handler,
1991                                                    dev);
1992
1993                 if (virtio_intr_enable(dev) < 0) {
1994                         PMD_DRV_LOG(ERR, "interrupt enable failed");
1995                         return -EIO;
1996                 }
1997         }
1998
1999         /*Notify the backend
2000          *Otherwise the tap backend might already stop its queue due to fullness.
2001          *vhost backend will have no chance to be waked up
2002          */
2003         nb_queues = RTE_MAX(dev->data->nb_rx_queues, dev->data->nb_tx_queues);
2004         if (hw->max_queue_pairs > 1) {
2005                 if (virtio_set_multiple_queues(dev, nb_queues) != 0)
2006                         return -EINVAL;
2007         }
2008
2009         PMD_INIT_LOG(DEBUG, "nb_queues=%d", nb_queues);
2010
2011         for (i = 0; i < dev->data->nb_rx_queues; i++) {
2012                 rxvq = dev->data->rx_queues[i];
2013                 /* Flush the old packets */
2014                 virtqueue_rxvq_flush(rxvq->vq);
2015                 virtqueue_notify(rxvq->vq);
2016         }
2017
2018         for (i = 0; i < dev->data->nb_tx_queues; i++) {
2019                 txvq = dev->data->tx_queues[i];
2020                 virtqueue_notify(txvq->vq);
2021         }
2022
2023         PMD_INIT_LOG(DEBUG, "Notified backend at initialization");
2024
2025         for (i = 0; i < dev->data->nb_rx_queues; i++) {
2026                 rxvq = dev->data->rx_queues[i];
2027                 VIRTQUEUE_DUMP(rxvq->vq);
2028         }
2029
2030         for (i = 0; i < dev->data->nb_tx_queues; i++) {
2031                 txvq = dev->data->tx_queues[i];
2032                 VIRTQUEUE_DUMP(txvq->vq);
2033         }
2034
2035         set_rxtx_funcs(dev);
2036         hw->started = true;
2037
2038         /* Initialize Link state */
2039         virtio_dev_link_update(dev, 0);
2040
2041         return 0;
2042 }
2043
2044 static void virtio_dev_free_mbufs(struct rte_eth_dev *dev)
2045 {
2046         struct virtio_hw *hw = dev->data->dev_private;
2047         uint16_t nr_vq = virtio_get_nr_vq(hw);
2048         const char *type __rte_unused;
2049         unsigned int i, mbuf_num = 0;
2050         struct virtqueue *vq;
2051         struct rte_mbuf *buf;
2052         int queue_type;
2053
2054         if (hw->vqs == NULL)
2055                 return;
2056
2057         for (i = 0; i < nr_vq; i++) {
2058                 vq = hw->vqs[i];
2059                 if (!vq)
2060                         continue;
2061
2062                 queue_type = virtio_get_queue_type(hw, i);
2063                 if (queue_type == VTNET_RQ)
2064                         type = "rxq";
2065                 else if (queue_type == VTNET_TQ)
2066                         type = "txq";
2067                 else
2068                         continue;
2069
2070                 PMD_INIT_LOG(DEBUG,
2071                         "Before freeing %s[%d] used and unused buf",
2072                         type, i);
2073                 VIRTQUEUE_DUMP(vq);
2074
2075                 while ((buf = virtqueue_detach_unused(vq)) != NULL) {
2076                         rte_pktmbuf_free(buf);
2077                         mbuf_num++;
2078                 }
2079
2080                 PMD_INIT_LOG(DEBUG,
2081                         "After freeing %s[%d] used and unused buf",
2082                         type, i);
2083                 VIRTQUEUE_DUMP(vq);
2084         }
2085
2086         PMD_INIT_LOG(DEBUG, "%d mbufs freed", mbuf_num);
2087 }
2088
2089 /*
2090  * Stop device: disable interrupt and mark link down
2091  */
2092 static void
2093 virtio_dev_stop(struct rte_eth_dev *dev)
2094 {
2095         struct virtio_hw *hw = dev->data->dev_private;
2096         struct rte_eth_link link;
2097         struct rte_intr_conf *intr_conf = &dev->data->dev_conf.intr_conf;
2098
2099         PMD_INIT_LOG(DEBUG, "stop");
2100
2101         rte_spinlock_lock(&hw->state_lock);
2102         if (!hw->started)
2103                 goto out_unlock;
2104         hw->started = false;
2105
2106         if (intr_conf->lsc || intr_conf->rxq) {
2107                 virtio_intr_disable(dev);
2108
2109                 /* Reset interrupt callback  */
2110                 if (dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC) {
2111                         rte_intr_callback_unregister(dev->intr_handle,
2112                                                      virtio_interrupt_handler,
2113                                                      dev);
2114                 }
2115         }
2116
2117         memset(&link, 0, sizeof(link));
2118         rte_eth_linkstatus_set(dev, &link);
2119 out_unlock:
2120         rte_spinlock_unlock(&hw->state_lock);
2121 }
2122
2123 static int
2124 virtio_dev_link_update(struct rte_eth_dev *dev, __rte_unused int wait_to_complete)
2125 {
2126         struct rte_eth_link link;
2127         uint16_t status;
2128         struct virtio_hw *hw = dev->data->dev_private;
2129
2130         memset(&link, 0, sizeof(link));
2131         link.link_duplex = ETH_LINK_FULL_DUPLEX;
2132         link.link_speed  = ETH_SPEED_NUM_10G;
2133         link.link_autoneg = ETH_LINK_FIXED;
2134
2135         if (!hw->started) {
2136                 link.link_status = ETH_LINK_DOWN;
2137         } else if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
2138                 PMD_INIT_LOG(DEBUG, "Get link status from hw");
2139                 vtpci_read_dev_config(hw,
2140                                 offsetof(struct virtio_net_config, status),
2141                                 &status, sizeof(status));
2142                 if ((status & VIRTIO_NET_S_LINK_UP) == 0) {
2143                         link.link_status = ETH_LINK_DOWN;
2144                         PMD_INIT_LOG(DEBUG, "Port %d is down",
2145                                      dev->data->port_id);
2146                 } else {
2147                         link.link_status = ETH_LINK_UP;
2148                         PMD_INIT_LOG(DEBUG, "Port %d is up",
2149                                      dev->data->port_id);
2150                 }
2151         } else {
2152                 link.link_status = ETH_LINK_UP;
2153         }
2154
2155         return rte_eth_linkstatus_set(dev, &link);
2156 }
2157
2158 static int
2159 virtio_dev_vlan_offload_set(struct rte_eth_dev *dev, int mask)
2160 {
2161         const struct rte_eth_rxmode *rxmode = &dev->data->dev_conf.rxmode;
2162         struct virtio_hw *hw = dev->data->dev_private;
2163         uint64_t offloads = rxmode->offloads;
2164
2165         if (mask & ETH_VLAN_FILTER_MASK) {
2166                 if ((offloads & DEV_RX_OFFLOAD_VLAN_FILTER) &&
2167                                 !vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VLAN)) {
2168
2169                         PMD_DRV_LOG(NOTICE,
2170                                 "vlan filtering not available on this host");
2171
2172                         return -ENOTSUP;
2173                 }
2174         }
2175
2176         if (mask & ETH_VLAN_STRIP_MASK)
2177                 hw->vlan_strip = !!(offloads & DEV_RX_OFFLOAD_VLAN_STRIP);
2178
2179         return 0;
2180 }
2181
2182 static void
2183 virtio_dev_info_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *dev_info)
2184 {
2185         uint64_t tso_mask, host_features;
2186         struct virtio_hw *hw = dev->data->dev_private;
2187
2188         dev_info->speed_capa = ETH_LINK_SPEED_10G; /* fake value */
2189
2190         dev_info->max_rx_queues =
2191                 RTE_MIN(hw->max_queue_pairs, VIRTIO_MAX_RX_QUEUES);
2192         dev_info->max_tx_queues =
2193                 RTE_MIN(hw->max_queue_pairs, VIRTIO_MAX_TX_QUEUES);
2194         dev_info->min_rx_bufsize = VIRTIO_MIN_RX_BUFSIZE;
2195         dev_info->max_rx_pktlen = VIRTIO_MAX_RX_PKTLEN;
2196         dev_info->max_mac_addrs = VIRTIO_MAX_MAC_ADDRS;
2197
2198         host_features = VTPCI_OPS(hw)->get_features(hw);
2199         dev_info->rx_offload_capa = DEV_RX_OFFLOAD_VLAN_STRIP;
2200         if (host_features & (1ULL << VIRTIO_NET_F_GUEST_CSUM)) {
2201                 dev_info->rx_offload_capa |=
2202                         DEV_RX_OFFLOAD_TCP_CKSUM |
2203                         DEV_RX_OFFLOAD_UDP_CKSUM;
2204         }
2205         if (host_features & (1ULL << VIRTIO_NET_F_CTRL_VLAN))
2206                 dev_info->rx_offload_capa |= DEV_RX_OFFLOAD_VLAN_FILTER;
2207         tso_mask = (1ULL << VIRTIO_NET_F_GUEST_TSO4) |
2208                 (1ULL << VIRTIO_NET_F_GUEST_TSO6);
2209         if ((host_features & tso_mask) == tso_mask)
2210                 dev_info->rx_offload_capa |= DEV_RX_OFFLOAD_TCP_LRO;
2211
2212         dev_info->tx_offload_capa = DEV_TX_OFFLOAD_MULTI_SEGS |
2213                                     DEV_TX_OFFLOAD_VLAN_INSERT;
2214         if (host_features & (1ULL << VIRTIO_NET_F_CSUM)) {
2215                 dev_info->tx_offload_capa |=
2216                         DEV_TX_OFFLOAD_UDP_CKSUM |
2217                         DEV_TX_OFFLOAD_TCP_CKSUM;
2218         }
2219         tso_mask = (1ULL << VIRTIO_NET_F_HOST_TSO4) |
2220                 (1ULL << VIRTIO_NET_F_HOST_TSO6);
2221         if ((host_features & tso_mask) == tso_mask)
2222                 dev_info->tx_offload_capa |= DEV_TX_OFFLOAD_TCP_TSO;
2223 }
2224
2225 /*
2226  * It enables testpmd to collect per queue stats.
2227  */
2228 static int
2229 virtio_dev_queue_stats_mapping_set(__rte_unused struct rte_eth_dev *eth_dev,
2230 __rte_unused uint16_t queue_id, __rte_unused uint8_t stat_idx,
2231 __rte_unused uint8_t is_rx)
2232 {
2233         return 0;
2234 }
2235
2236 RTE_PMD_EXPORT_NAME(net_virtio, __COUNTER__);
2237 RTE_PMD_REGISTER_PCI_TABLE(net_virtio, pci_id_virtio_map);
2238 RTE_PMD_REGISTER_KMOD_DEP(net_virtio, "* igb_uio | uio_pci_generic | vfio-pci");
2239
2240 RTE_INIT(virtio_init_log)
2241 {
2242         virtio_logtype_init = rte_log_register("pmd.net.virtio.init");
2243         if (virtio_logtype_init >= 0)
2244                 rte_log_set_level(virtio_logtype_init, RTE_LOG_NOTICE);
2245         virtio_logtype_driver = rte_log_register("pmd.net.virtio.driver");
2246         if (virtio_logtype_driver >= 0)
2247                 rte_log_set_level(virtio_logtype_driver, RTE_LOG_NOTICE);
2248 }