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