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