net/virtio: complete init stage at the right place
[dpdk.git] / drivers / net / virtio / virtio_ethdev.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2016 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include <stdint.h>
35 #include <string.h>
36 #include <stdio.h>
37 #include <errno.h>
38 #include <unistd.h>
39
40 #include <rte_ethdev.h>
41 #include <rte_memcpy.h>
42 #include <rte_string_fns.h>
43 #include <rte_memzone.h>
44 #include <rte_malloc.h>
45 #include <rte_atomic.h>
46 #include <rte_branch_prediction.h>
47 #include <rte_pci.h>
48 #include <rte_ether.h>
49 #include <rte_common.h>
50 #include <rte_errno.h>
51
52 #include <rte_memory.h>
53 #include <rte_eal.h>
54 #include <rte_dev.h>
55
56 #include "virtio_ethdev.h"
57 #include "virtio_pci.h"
58 #include "virtio_logs.h"
59 #include "virtqueue.h"
60 #include "virtio_rxtx.h"
61
62 static int eth_virtio_dev_uninit(struct rte_eth_dev *eth_dev);
63 static int  virtio_dev_configure(struct rte_eth_dev *dev);
64 static int  virtio_dev_start(struct rte_eth_dev *dev);
65 static void virtio_dev_stop(struct rte_eth_dev *dev);
66 static void virtio_dev_promiscuous_enable(struct rte_eth_dev *dev);
67 static void virtio_dev_promiscuous_disable(struct rte_eth_dev *dev);
68 static void virtio_dev_allmulticast_enable(struct rte_eth_dev *dev);
69 static void virtio_dev_allmulticast_disable(struct rte_eth_dev *dev);
70 static void virtio_dev_info_get(struct rte_eth_dev *dev,
71                                 struct rte_eth_dev_info *dev_info);
72 static int virtio_dev_link_update(struct rte_eth_dev *dev,
73         __rte_unused int wait_to_complete);
74
75 static void virtio_set_hwaddr(struct virtio_hw *hw);
76 static void virtio_get_hwaddr(struct virtio_hw *hw);
77
78 static void virtio_dev_stats_get(struct rte_eth_dev *dev,
79                                  struct rte_eth_stats *stats);
80 static int virtio_dev_xstats_get(struct rte_eth_dev *dev,
81                                  struct rte_eth_xstat *xstats, unsigned n);
82 static int virtio_dev_xstats_get_names(struct rte_eth_dev *dev,
83                                        struct rte_eth_xstat_name *xstats_names,
84                                        unsigned limit);
85 static void virtio_dev_stats_reset(struct rte_eth_dev *dev);
86 static void virtio_dev_free_mbufs(struct rte_eth_dev *dev);
87 static int virtio_vlan_filter_set(struct rte_eth_dev *dev,
88                                 uint16_t vlan_id, int on);
89 static void virtio_mac_addr_add(struct rte_eth_dev *dev,
90                                 struct ether_addr *mac_addr,
91                                 uint32_t index, uint32_t vmdq __rte_unused);
92 static void virtio_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index);
93 static void virtio_mac_addr_set(struct rte_eth_dev *dev,
94                                 struct ether_addr *mac_addr);
95
96 static int virtio_dev_queue_stats_mapping_set(
97         __rte_unused struct rte_eth_dev *eth_dev,
98         __rte_unused uint16_t queue_id,
99         __rte_unused uint8_t stat_idx,
100         __rte_unused uint8_t is_rx);
101
102 /*
103  * The set of PCI devices this driver supports
104  */
105 static const struct rte_pci_id pci_id_virtio_map[] = {
106         { RTE_PCI_DEVICE(VIRTIO_PCI_VENDORID, VIRTIO_PCI_LEGACY_DEVICEID_NET) },
107         { RTE_PCI_DEVICE(VIRTIO_PCI_VENDORID, VIRTIO_PCI_MODERN_DEVICEID_NET) },
108         { .vendor_id = 0, /* sentinel */ },
109 };
110
111 struct rte_virtio_xstats_name_off {
112         char name[RTE_ETH_XSTATS_NAME_SIZE];
113         unsigned offset;
114 };
115
116 /* [rt]x_qX_ is prepended to the name string here */
117 static const struct rte_virtio_xstats_name_off rte_virtio_rxq_stat_strings[] = {
118         {"good_packets",           offsetof(struct virtnet_rx, stats.packets)},
119         {"good_bytes",             offsetof(struct virtnet_rx, stats.bytes)},
120         {"errors",                 offsetof(struct virtnet_rx, stats.errors)},
121         {"multicast_packets",      offsetof(struct virtnet_rx, stats.multicast)},
122         {"broadcast_packets",      offsetof(struct virtnet_rx, stats.broadcast)},
123         {"undersize_packets",      offsetof(struct virtnet_rx, stats.size_bins[0])},
124         {"size_64_packets",        offsetof(struct virtnet_rx, stats.size_bins[1])},
125         {"size_65_127_packets",    offsetof(struct virtnet_rx, stats.size_bins[2])},
126         {"size_128_255_packets",   offsetof(struct virtnet_rx, stats.size_bins[3])},
127         {"size_256_511_packets",   offsetof(struct virtnet_rx, stats.size_bins[4])},
128         {"size_512_1023_packets",  offsetof(struct virtnet_rx, stats.size_bins[5])},
129         {"size_1024_1518_packets", offsetof(struct virtnet_rx, stats.size_bins[6])},
130         {"size_1519_max_packets",  offsetof(struct virtnet_rx, stats.size_bins[7])},
131 };
132
133 /* [rt]x_qX_ is prepended to the name string here */
134 static const struct rte_virtio_xstats_name_off rte_virtio_txq_stat_strings[] = {
135         {"good_packets",           offsetof(struct virtnet_tx, stats.packets)},
136         {"good_bytes",             offsetof(struct virtnet_tx, stats.bytes)},
137         {"errors",                 offsetof(struct virtnet_tx, stats.errors)},
138         {"multicast_packets",      offsetof(struct virtnet_tx, stats.multicast)},
139         {"broadcast_packets",      offsetof(struct virtnet_tx, stats.broadcast)},
140         {"undersize_packets",      offsetof(struct virtnet_tx, stats.size_bins[0])},
141         {"size_64_packets",        offsetof(struct virtnet_tx, stats.size_bins[1])},
142         {"size_65_127_packets",    offsetof(struct virtnet_tx, stats.size_bins[2])},
143         {"size_128_255_packets",   offsetof(struct virtnet_tx, stats.size_bins[3])},
144         {"size_256_511_packets",   offsetof(struct virtnet_tx, stats.size_bins[4])},
145         {"size_512_1023_packets",  offsetof(struct virtnet_tx, stats.size_bins[5])},
146         {"size_1024_1518_packets", offsetof(struct virtnet_tx, stats.size_bins[6])},
147         {"size_1519_max_packets",  offsetof(struct virtnet_tx, stats.size_bins[7])},
148 };
149
150 #define VIRTIO_NB_RXQ_XSTATS (sizeof(rte_virtio_rxq_stat_strings) / \
151                             sizeof(rte_virtio_rxq_stat_strings[0]))
152 #define VIRTIO_NB_TXQ_XSTATS (sizeof(rte_virtio_txq_stat_strings) / \
153                             sizeof(rte_virtio_txq_stat_strings[0]))
154
155 static int
156 virtio_send_command(struct virtnet_ctl *cvq, struct virtio_pmd_ctrl *ctrl,
157                 int *dlen, int pkt_num)
158 {
159         uint32_t head, i;
160         int k, sum = 0;
161         virtio_net_ctrl_ack status = ~0;
162         struct virtio_pmd_ctrl result;
163         struct virtqueue *vq;
164
165         ctrl->status = status;
166
167         if (!cvq || !cvq->vq) {
168                 PMD_INIT_LOG(ERR, "Control queue is not supported.");
169                 return -1;
170         }
171         vq = cvq->vq;
172         head = vq->vq_desc_head_idx;
173
174         PMD_INIT_LOG(DEBUG, "vq->vq_desc_head_idx = %d, status = %d, "
175                 "vq->hw->cvq = %p vq = %p",
176                 vq->vq_desc_head_idx, status, vq->hw->cvq, vq);
177
178         if ((vq->vq_free_cnt < ((uint32_t)pkt_num + 2)) || (pkt_num < 1))
179                 return -1;
180
181         memcpy(cvq->virtio_net_hdr_mz->addr, ctrl,
182                 sizeof(struct virtio_pmd_ctrl));
183
184         /*
185          * Format is enforced in qemu code:
186          * One TX packet for header;
187          * At least one TX packet per argument;
188          * One RX packet for ACK.
189          */
190         vq->vq_ring.desc[head].flags = VRING_DESC_F_NEXT;
191         vq->vq_ring.desc[head].addr = cvq->virtio_net_hdr_mem;
192         vq->vq_ring.desc[head].len = sizeof(struct virtio_net_ctrl_hdr);
193         vq->vq_free_cnt--;
194         i = vq->vq_ring.desc[head].next;
195
196         for (k = 0; k < pkt_num; k++) {
197                 vq->vq_ring.desc[i].flags = VRING_DESC_F_NEXT;
198                 vq->vq_ring.desc[i].addr = cvq->virtio_net_hdr_mem
199                         + sizeof(struct virtio_net_ctrl_hdr)
200                         + sizeof(ctrl->status) + sizeof(uint8_t)*sum;
201                 vq->vq_ring.desc[i].len = dlen[k];
202                 sum += dlen[k];
203                 vq->vq_free_cnt--;
204                 i = vq->vq_ring.desc[i].next;
205         }
206
207         vq->vq_ring.desc[i].flags = VRING_DESC_F_WRITE;
208         vq->vq_ring.desc[i].addr = cvq->virtio_net_hdr_mem
209                         + sizeof(struct virtio_net_ctrl_hdr);
210         vq->vq_ring.desc[i].len = sizeof(ctrl->status);
211         vq->vq_free_cnt--;
212
213         vq->vq_desc_head_idx = vq->vq_ring.desc[i].next;
214
215         vq_update_avail_ring(vq, head);
216         vq_update_avail_idx(vq);
217
218         PMD_INIT_LOG(DEBUG, "vq->vq_queue_index = %d", vq->vq_queue_index);
219
220         virtqueue_notify(vq);
221
222         rte_rmb();
223         while (VIRTQUEUE_NUSED(vq) == 0) {
224                 rte_rmb();
225                 usleep(100);
226         }
227
228         while (VIRTQUEUE_NUSED(vq)) {
229                 uint32_t idx, desc_idx, used_idx;
230                 struct vring_used_elem *uep;
231
232                 used_idx = (uint32_t)(vq->vq_used_cons_idx
233                                 & (vq->vq_nentries - 1));
234                 uep = &vq->vq_ring.used->ring[used_idx];
235                 idx = (uint32_t) uep->id;
236                 desc_idx = idx;
237
238                 while (vq->vq_ring.desc[desc_idx].flags & VRING_DESC_F_NEXT) {
239                         desc_idx = vq->vq_ring.desc[desc_idx].next;
240                         vq->vq_free_cnt++;
241                 }
242
243                 vq->vq_ring.desc[desc_idx].next = vq->vq_desc_head_idx;
244                 vq->vq_desc_head_idx = idx;
245
246                 vq->vq_used_cons_idx++;
247                 vq->vq_free_cnt++;
248         }
249
250         PMD_INIT_LOG(DEBUG, "vq->vq_free_cnt=%d\nvq->vq_desc_head_idx=%d",
251                         vq->vq_free_cnt, vq->vq_desc_head_idx);
252
253         memcpy(&result, cvq->virtio_net_hdr_mz->addr,
254                         sizeof(struct virtio_pmd_ctrl));
255
256         return result.status;
257 }
258
259 static int
260 virtio_set_multiple_queues(struct rte_eth_dev *dev, uint16_t nb_queues)
261 {
262         struct virtio_hw *hw = dev->data->dev_private;
263         struct virtio_pmd_ctrl ctrl;
264         int dlen[1];
265         int ret;
266
267         ctrl.hdr.class = VIRTIO_NET_CTRL_MQ;
268         ctrl.hdr.cmd = VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET;
269         memcpy(ctrl.data, &nb_queues, sizeof(uint16_t));
270
271         dlen[0] = sizeof(uint16_t);
272
273         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
274         if (ret) {
275                 PMD_INIT_LOG(ERR, "Multiqueue configured but send command "
276                           "failed, this is too late now...");
277                 return -EINVAL;
278         }
279
280         return 0;
281 }
282
283 static void
284 virtio_dev_queue_release(void *queue __rte_unused)
285 {
286         /* do nothing */
287 }
288
289 static int
290 virtio_get_queue_type(struct virtio_hw *hw, uint16_t vtpci_queue_idx)
291 {
292         if (vtpci_queue_idx == hw->max_queue_pairs * 2)
293                 return VTNET_CQ;
294         else if (vtpci_queue_idx % 2 == 0)
295                 return VTNET_RQ;
296         else
297                 return VTNET_TQ;
298 }
299
300 static uint16_t
301 virtio_get_nr_vq(struct virtio_hw *hw)
302 {
303         uint16_t nr_vq = hw->max_queue_pairs * 2;
304
305         if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VQ))
306                 nr_vq += 1;
307
308         return nr_vq;
309 }
310
311 static void
312 virtio_init_vring(struct virtqueue *vq)
313 {
314         int size = vq->vq_nentries;
315         struct vring *vr = &vq->vq_ring;
316         uint8_t *ring_mem = vq->vq_ring_virt_mem;
317
318         PMD_INIT_FUNC_TRACE();
319
320         /*
321          * Reinitialise since virtio port might have been stopped and restarted
322          */
323         memset(ring_mem, 0, vq->vq_ring_size);
324         vring_init(vr, size, ring_mem, VIRTIO_PCI_VRING_ALIGN);
325         vq->vq_used_cons_idx = 0;
326         vq->vq_desc_head_idx = 0;
327         vq->vq_avail_idx = 0;
328         vq->vq_desc_tail_idx = (uint16_t)(vq->vq_nentries - 1);
329         vq->vq_free_cnt = vq->vq_nentries;
330         memset(vq->vq_descx, 0, sizeof(struct vq_desc_extra) * vq->vq_nentries);
331
332         vring_desc_init(vr->desc, size);
333
334         /*
335          * Disable device(host) interrupting guest
336          */
337         virtqueue_disable_intr(vq);
338 }
339
340 static int
341 virtio_init_queue(struct rte_eth_dev *dev, uint16_t vtpci_queue_idx)
342 {
343         char vq_name[VIRTQUEUE_MAX_NAME_SZ];
344         char vq_hdr_name[VIRTQUEUE_MAX_NAME_SZ];
345         const struct rte_memzone *mz = NULL, *hdr_mz = NULL;
346         unsigned int vq_size, size;
347         struct virtio_hw *hw = dev->data->dev_private;
348         struct virtnet_rx *rxvq = NULL;
349         struct virtnet_tx *txvq = NULL;
350         struct virtnet_ctl *cvq = NULL;
351         struct virtqueue *vq;
352         size_t sz_hdr_mz = 0;
353         void *sw_ring = NULL;
354         int queue_type = virtio_get_queue_type(hw, vtpci_queue_idx);
355         int ret;
356
357         PMD_INIT_LOG(DEBUG, "setting up queue: %u", vtpci_queue_idx);
358
359         /*
360          * Read the virtqueue size from the Queue Size field
361          * Always power of 2 and if 0 virtqueue does not exist
362          */
363         vq_size = hw->vtpci_ops->get_queue_num(hw, vtpci_queue_idx);
364         PMD_INIT_LOG(DEBUG, "vq_size: %u", vq_size);
365         if (vq_size == 0) {
366                 PMD_INIT_LOG(ERR, "virtqueue does not exist");
367                 return -EINVAL;
368         }
369
370         if (!rte_is_power_of_2(vq_size)) {
371                 PMD_INIT_LOG(ERR, "virtqueue size is not powerof 2");
372                 return -EINVAL;
373         }
374
375         snprintf(vq_name, sizeof(vq_name), "port%d_vq%d",
376                  dev->data->port_id, vtpci_queue_idx);
377
378         size = RTE_ALIGN_CEIL(sizeof(*vq) +
379                                 vq_size * sizeof(struct vq_desc_extra),
380                                 RTE_CACHE_LINE_SIZE);
381         if (queue_type == VTNET_TQ) {
382                 /*
383                  * For each xmit packet, allocate a virtio_net_hdr
384                  * and indirect ring elements
385                  */
386                 sz_hdr_mz = vq_size * sizeof(struct virtio_tx_region);
387         } else if (queue_type == VTNET_CQ) {
388                 /* Allocate a page for control vq command, data and status */
389                 sz_hdr_mz = PAGE_SIZE;
390         }
391
392         vq = rte_zmalloc_socket(vq_name, size, RTE_CACHE_LINE_SIZE,
393                                 SOCKET_ID_ANY);
394         if (vq == NULL) {
395                 PMD_INIT_LOG(ERR, "can not allocate vq");
396                 return -ENOMEM;
397         }
398         hw->vqs[vtpci_queue_idx] = vq;
399
400         vq->hw = hw;
401         vq->vq_queue_index = vtpci_queue_idx;
402         vq->vq_nentries = vq_size;
403
404         /*
405          * Reserve a memzone for vring elements
406          */
407         size = vring_size(vq_size, VIRTIO_PCI_VRING_ALIGN);
408         vq->vq_ring_size = RTE_ALIGN_CEIL(size, VIRTIO_PCI_VRING_ALIGN);
409         PMD_INIT_LOG(DEBUG, "vring_size: %d, rounded_vring_size: %d",
410                      size, vq->vq_ring_size);
411
412         mz = rte_memzone_reserve_aligned(vq_name, vq->vq_ring_size,
413                                          SOCKET_ID_ANY,
414                                          0, VIRTIO_PCI_VRING_ALIGN);
415         if (mz == NULL) {
416                 if (rte_errno == EEXIST)
417                         mz = rte_memzone_lookup(vq_name);
418                 if (mz == NULL) {
419                         ret = -ENOMEM;
420                         goto fail_q_alloc;
421                 }
422         }
423
424         memset(mz->addr, 0, sizeof(mz->len));
425
426         vq->vq_ring_mem = mz->phys_addr;
427         vq->vq_ring_virt_mem = mz->addr;
428         PMD_INIT_LOG(DEBUG, "vq->vq_ring_mem:      0x%" PRIx64,
429                      (uint64_t)mz->phys_addr);
430         PMD_INIT_LOG(DEBUG, "vq->vq_ring_virt_mem: 0x%" PRIx64,
431                      (uint64_t)(uintptr_t)mz->addr);
432
433         virtio_init_vring(vq);
434
435         if (sz_hdr_mz) {
436                 snprintf(vq_hdr_name, sizeof(vq_hdr_name), "port%d_vq%d_hdr",
437                          dev->data->port_id, vtpci_queue_idx);
438                 hdr_mz = rte_memzone_reserve_aligned(vq_hdr_name, sz_hdr_mz,
439                                                      SOCKET_ID_ANY, 0,
440                                                      RTE_CACHE_LINE_SIZE);
441                 if (hdr_mz == NULL) {
442                         if (rte_errno == EEXIST)
443                                 hdr_mz = rte_memzone_lookup(vq_hdr_name);
444                         if (hdr_mz == NULL) {
445                                 ret = -ENOMEM;
446                                 goto fail_q_alloc;
447                         }
448                 }
449         }
450
451         if (queue_type == VTNET_RQ) {
452                 size_t sz_sw = (RTE_PMD_VIRTIO_RX_MAX_BURST + vq_size) *
453                                sizeof(vq->sw_ring[0]);
454
455                 sw_ring = rte_zmalloc_socket("sw_ring", sz_sw,
456                                 RTE_CACHE_LINE_SIZE, SOCKET_ID_ANY);
457                 if (!sw_ring) {
458                         PMD_INIT_LOG(ERR, "can not allocate RX soft ring");
459                         ret = -ENOMEM;
460                         goto fail_q_alloc;
461                 }
462
463                 vq->sw_ring = sw_ring;
464                 rxvq = &vq->rxq;
465                 rxvq->vq = vq;
466                 rxvq->port_id = dev->data->port_id;
467                 rxvq->mz = mz;
468         } else if (queue_type == VTNET_TQ) {
469                 txvq = &vq->txq;
470                 txvq->vq = vq;
471                 txvq->port_id = dev->data->port_id;
472                 txvq->mz = mz;
473                 txvq->virtio_net_hdr_mz = hdr_mz;
474                 txvq->virtio_net_hdr_mem = hdr_mz->phys_addr;
475         } else if (queue_type == VTNET_CQ) {
476                 cvq = &vq->cq;
477                 cvq->vq = vq;
478                 cvq->mz = mz;
479                 cvq->virtio_net_hdr_mz = hdr_mz;
480                 cvq->virtio_net_hdr_mem = hdr_mz->phys_addr;
481                 memset(cvq->virtio_net_hdr_mz->addr, 0, PAGE_SIZE);
482
483                 hw->cvq = cvq;
484         }
485
486         /* For virtio_user case (that is when dev->pci_dev is NULL), we use
487          * virtual address. And we need properly set _offset_, please see
488          * VIRTIO_MBUF_DATA_DMA_ADDR in virtqueue.h for more information.
489          */
490         if (dev->pci_dev)
491                 vq->offset = offsetof(struct rte_mbuf, buf_physaddr);
492         else {
493                 vq->vq_ring_mem = (uintptr_t)mz->addr;
494                 vq->offset = offsetof(struct rte_mbuf, buf_addr);
495                 if (queue_type == VTNET_TQ)
496                         txvq->virtio_net_hdr_mem = (uintptr_t)hdr_mz->addr;
497                 else if (queue_type == VTNET_CQ)
498                         cvq->virtio_net_hdr_mem = (uintptr_t)hdr_mz->addr;
499         }
500
501         if (queue_type == VTNET_TQ) {
502                 struct virtio_tx_region *txr;
503                 unsigned int i;
504
505                 txr = hdr_mz->addr;
506                 memset(txr, 0, vq_size * sizeof(*txr));
507                 for (i = 0; i < vq_size; i++) {
508                         struct vring_desc *start_dp = txr[i].tx_indir;
509
510                         vring_desc_init(start_dp, RTE_DIM(txr[i].tx_indir));
511
512                         /* first indirect descriptor is always the tx header */
513                         start_dp->addr = txvq->virtio_net_hdr_mem
514                                 + i * sizeof(*txr)
515                                 + offsetof(struct virtio_tx_region, tx_hdr);
516
517                         start_dp->len = hw->vtnet_hdr_size;
518                         start_dp->flags = VRING_DESC_F_NEXT;
519                 }
520         }
521
522         if (hw->vtpci_ops->setup_queue(hw, vq) < 0) {
523                 PMD_INIT_LOG(ERR, "setup_queue failed");
524                 return -EINVAL;
525         }
526
527         return 0;
528
529 fail_q_alloc:
530         rte_free(sw_ring);
531         rte_memzone_free(hdr_mz);
532         rte_memzone_free(mz);
533         rte_free(vq);
534
535         return ret;
536 }
537
538 static void
539 virtio_free_queues(struct virtio_hw *hw)
540 {
541         uint16_t nr_vq = virtio_get_nr_vq(hw);
542         struct virtqueue *vq;
543         int queue_type;
544         uint16_t i;
545
546         for (i = 0; i < nr_vq; i++) {
547                 vq = hw->vqs[i];
548                 if (!vq)
549                         continue;
550
551                 queue_type = virtio_get_queue_type(hw, i);
552                 if (queue_type == VTNET_RQ) {
553                         rte_free(vq->sw_ring);
554                         rte_memzone_free(vq->rxq.mz);
555                 } else if (queue_type == VTNET_TQ) {
556                         rte_memzone_free(vq->txq.mz);
557                         rte_memzone_free(vq->txq.virtio_net_hdr_mz);
558                 } else {
559                         rte_memzone_free(vq->cq.mz);
560                         rte_memzone_free(vq->cq.virtio_net_hdr_mz);
561                 }
562
563                 rte_free(vq);
564         }
565
566         rte_free(hw->vqs);
567 }
568
569 static int
570 virtio_alloc_queues(struct rte_eth_dev *dev)
571 {
572         struct virtio_hw *hw = dev->data->dev_private;
573         uint16_t nr_vq = virtio_get_nr_vq(hw);
574         uint16_t i;
575         int ret;
576
577         hw->vqs = rte_zmalloc(NULL, sizeof(struct virtqueue *) * nr_vq, 0);
578         if (!hw->vqs) {
579                 PMD_INIT_LOG(ERR, "failed to allocate vqs");
580                 return -ENOMEM;
581         }
582
583         for (i = 0; i < nr_vq; i++) {
584                 ret = virtio_init_queue(dev, i);
585                 if (ret < 0) {
586                         virtio_free_queues(hw);
587                         return ret;
588                 }
589         }
590
591         return 0;
592 }
593
594 static void
595 virtio_dev_close(struct rte_eth_dev *dev)
596 {
597         struct virtio_hw *hw = dev->data->dev_private;
598
599         PMD_INIT_LOG(DEBUG, "virtio_dev_close");
600
601         /* reset the NIC */
602         if (dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
603                 vtpci_irq_config(hw, VIRTIO_MSI_NO_VECTOR);
604         vtpci_reset(hw);
605         hw->started = 0;
606         virtio_dev_free_mbufs(dev);
607         virtio_free_queues(hw);
608 }
609
610 static void
611 virtio_dev_promiscuous_enable(struct rte_eth_dev *dev)
612 {
613         struct virtio_hw *hw = dev->data->dev_private;
614         struct virtio_pmd_ctrl ctrl;
615         int dlen[1];
616         int ret;
617
618         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
619                 PMD_INIT_LOG(INFO, "host does not support rx control\n");
620                 return;
621         }
622
623         ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
624         ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_PROMISC;
625         ctrl.data[0] = 1;
626         dlen[0] = 1;
627
628         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
629         if (ret)
630                 PMD_INIT_LOG(ERR, "Failed to enable promisc");
631 }
632
633 static void
634 virtio_dev_promiscuous_disable(struct rte_eth_dev *dev)
635 {
636         struct virtio_hw *hw = dev->data->dev_private;
637         struct virtio_pmd_ctrl ctrl;
638         int dlen[1];
639         int ret;
640
641         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
642                 PMD_INIT_LOG(INFO, "host does not support rx control\n");
643                 return;
644         }
645
646         ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
647         ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_PROMISC;
648         ctrl.data[0] = 0;
649         dlen[0] = 1;
650
651         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
652         if (ret)
653                 PMD_INIT_LOG(ERR, "Failed to disable promisc");
654 }
655
656 static void
657 virtio_dev_allmulticast_enable(struct rte_eth_dev *dev)
658 {
659         struct virtio_hw *hw = dev->data->dev_private;
660         struct virtio_pmd_ctrl ctrl;
661         int dlen[1];
662         int ret;
663
664         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
665                 PMD_INIT_LOG(INFO, "host does not support rx control\n");
666                 return;
667         }
668
669         ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
670         ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_ALLMULTI;
671         ctrl.data[0] = 1;
672         dlen[0] = 1;
673
674         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
675         if (ret)
676                 PMD_INIT_LOG(ERR, "Failed to enable allmulticast");
677 }
678
679 static void
680 virtio_dev_allmulticast_disable(struct rte_eth_dev *dev)
681 {
682         struct virtio_hw *hw = dev->data->dev_private;
683         struct virtio_pmd_ctrl ctrl;
684         int dlen[1];
685         int ret;
686
687         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
688                 PMD_INIT_LOG(INFO, "host does not support rx control\n");
689                 return;
690         }
691
692         ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
693         ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_ALLMULTI;
694         ctrl.data[0] = 0;
695         dlen[0] = 1;
696
697         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
698         if (ret)
699                 PMD_INIT_LOG(ERR, "Failed to disable allmulticast");
700 }
701
702 #define VLAN_TAG_LEN           4    /* 802.3ac tag (not DMA'd) */
703 static int
704 virtio_mtu_set(struct rte_eth_dev *dev, uint16_t mtu)
705 {
706         struct virtio_hw *hw = dev->data->dev_private;
707         uint32_t ether_hdr_len = ETHER_HDR_LEN + VLAN_TAG_LEN +
708                                  hw->vtnet_hdr_size;
709         uint32_t frame_size = mtu + ether_hdr_len;
710
711         if (mtu < ETHER_MIN_MTU || frame_size > VIRTIO_MAX_RX_PKTLEN) {
712                 PMD_INIT_LOG(ERR, "MTU should be between %d and %d\n",
713                         ETHER_MIN_MTU, VIRTIO_MAX_RX_PKTLEN - ether_hdr_len);
714                 return -EINVAL;
715         }
716         return 0;
717 }
718
719 /*
720  * dev_ops for virtio, bare necessities for basic operation
721  */
722 static const struct eth_dev_ops virtio_eth_dev_ops = {
723         .dev_configure           = virtio_dev_configure,
724         .dev_start               = virtio_dev_start,
725         .dev_stop                = virtio_dev_stop,
726         .dev_close               = virtio_dev_close,
727         .promiscuous_enable      = virtio_dev_promiscuous_enable,
728         .promiscuous_disable     = virtio_dev_promiscuous_disable,
729         .allmulticast_enable     = virtio_dev_allmulticast_enable,
730         .allmulticast_disable    = virtio_dev_allmulticast_disable,
731         .mtu_set                 = virtio_mtu_set,
732         .dev_infos_get           = virtio_dev_info_get,
733         .stats_get               = virtio_dev_stats_get,
734         .xstats_get              = virtio_dev_xstats_get,
735         .xstats_get_names        = virtio_dev_xstats_get_names,
736         .stats_reset             = virtio_dev_stats_reset,
737         .xstats_reset            = virtio_dev_stats_reset,
738         .link_update             = virtio_dev_link_update,
739         .rx_queue_setup          = virtio_dev_rx_queue_setup,
740         .rx_queue_release        = virtio_dev_queue_release,
741         .tx_queue_setup          = virtio_dev_tx_queue_setup,
742         .tx_queue_release        = virtio_dev_queue_release,
743         /* collect stats per queue */
744         .queue_stats_mapping_set = virtio_dev_queue_stats_mapping_set,
745         .vlan_filter_set         = virtio_vlan_filter_set,
746         .mac_addr_add            = virtio_mac_addr_add,
747         .mac_addr_remove         = virtio_mac_addr_remove,
748         .mac_addr_set            = virtio_mac_addr_set,
749 };
750
751 static inline int
752 virtio_dev_atomic_read_link_status(struct rte_eth_dev *dev,
753                                 struct rte_eth_link *link)
754 {
755         struct rte_eth_link *dst = link;
756         struct rte_eth_link *src = &(dev->data->dev_link);
757
758         if (rte_atomic64_cmpset((uint64_t *)dst, *(uint64_t *)dst,
759                         *(uint64_t *)src) == 0)
760                 return -1;
761
762         return 0;
763 }
764
765 /**
766  * Atomically writes the link status information into global
767  * structure rte_eth_dev.
768  *
769  * @param dev
770  *   - Pointer to the structure rte_eth_dev to read from.
771  *   - Pointer to the buffer to be saved with the link status.
772  *
773  * @return
774  *   - On success, zero.
775  *   - On failure, negative value.
776  */
777 static inline int
778 virtio_dev_atomic_write_link_status(struct rte_eth_dev *dev,
779                 struct rte_eth_link *link)
780 {
781         struct rte_eth_link *dst = &(dev->data->dev_link);
782         struct rte_eth_link *src = link;
783
784         if (rte_atomic64_cmpset((uint64_t *)dst, *(uint64_t *)dst,
785                                         *(uint64_t *)src) == 0)
786                 return -1;
787
788         return 0;
789 }
790
791 static void
792 virtio_update_stats(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
793 {
794         unsigned i;
795
796         for (i = 0; i < dev->data->nb_tx_queues; i++) {
797                 const struct virtnet_tx *txvq = dev->data->tx_queues[i];
798                 if (txvq == NULL)
799                         continue;
800
801                 stats->opackets += txvq->stats.packets;
802                 stats->obytes += txvq->stats.bytes;
803                 stats->oerrors += txvq->stats.errors;
804
805                 if (i < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
806                         stats->q_opackets[i] = txvq->stats.packets;
807                         stats->q_obytes[i] = txvq->stats.bytes;
808                 }
809         }
810
811         for (i = 0; i < dev->data->nb_rx_queues; i++) {
812                 const struct virtnet_rx *rxvq = dev->data->rx_queues[i];
813                 if (rxvq == NULL)
814                         continue;
815
816                 stats->ipackets += rxvq->stats.packets;
817                 stats->ibytes += rxvq->stats.bytes;
818                 stats->ierrors += rxvq->stats.errors;
819
820                 if (i < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
821                         stats->q_ipackets[i] = rxvq->stats.packets;
822                         stats->q_ibytes[i] = rxvq->stats.bytes;
823                 }
824         }
825
826         stats->rx_nombuf = dev->data->rx_mbuf_alloc_failed;
827 }
828
829 static int virtio_dev_xstats_get_names(struct rte_eth_dev *dev,
830                                        struct rte_eth_xstat_name *xstats_names,
831                                        __rte_unused unsigned limit)
832 {
833         unsigned i;
834         unsigned count = 0;
835         unsigned t;
836
837         unsigned nstats = dev->data->nb_tx_queues * VIRTIO_NB_TXQ_XSTATS +
838                 dev->data->nb_rx_queues * VIRTIO_NB_RXQ_XSTATS;
839
840         if (xstats_names != NULL) {
841                 /* Note: limit checked in rte_eth_xstats_names() */
842
843                 for (i = 0; i < dev->data->nb_rx_queues; i++) {
844                         struct virtqueue *rxvq = dev->data->rx_queues[i];
845                         if (rxvq == NULL)
846                                 continue;
847                         for (t = 0; t < VIRTIO_NB_RXQ_XSTATS; t++) {
848                                 snprintf(xstats_names[count].name,
849                                         sizeof(xstats_names[count].name),
850                                         "rx_q%u_%s", i,
851                                         rte_virtio_rxq_stat_strings[t].name);
852                                 count++;
853                         }
854                 }
855
856                 for (i = 0; i < dev->data->nb_tx_queues; i++) {
857                         struct virtqueue *txvq = dev->data->tx_queues[i];
858                         if (txvq == NULL)
859                                 continue;
860                         for (t = 0; t < VIRTIO_NB_TXQ_XSTATS; t++) {
861                                 snprintf(xstats_names[count].name,
862                                         sizeof(xstats_names[count].name),
863                                         "tx_q%u_%s", i,
864                                         rte_virtio_txq_stat_strings[t].name);
865                                 count++;
866                         }
867                 }
868                 return count;
869         }
870         return nstats;
871 }
872
873 static int
874 virtio_dev_xstats_get(struct rte_eth_dev *dev, struct rte_eth_xstat *xstats,
875                       unsigned n)
876 {
877         unsigned i;
878         unsigned count = 0;
879
880         unsigned nstats = dev->data->nb_tx_queues * VIRTIO_NB_TXQ_XSTATS +
881                 dev->data->nb_rx_queues * VIRTIO_NB_RXQ_XSTATS;
882
883         if (n < nstats)
884                 return nstats;
885
886         for (i = 0; i < dev->data->nb_rx_queues; i++) {
887                 struct virtnet_rx *rxvq = dev->data->rx_queues[i];
888
889                 if (rxvq == NULL)
890                         continue;
891
892                 unsigned t;
893
894                 for (t = 0; t < VIRTIO_NB_RXQ_XSTATS; t++) {
895                         xstats[count].value = *(uint64_t *)(((char *)rxvq) +
896                                 rte_virtio_rxq_stat_strings[t].offset);
897                         count++;
898                 }
899         }
900
901         for (i = 0; i < dev->data->nb_tx_queues; i++) {
902                 struct virtnet_tx *txvq = dev->data->tx_queues[i];
903
904                 if (txvq == NULL)
905                         continue;
906
907                 unsigned t;
908
909                 for (t = 0; t < VIRTIO_NB_TXQ_XSTATS; t++) {
910                         xstats[count].value = *(uint64_t *)(((char *)txvq) +
911                                 rte_virtio_txq_stat_strings[t].offset);
912                         count++;
913                 }
914         }
915
916         return count;
917 }
918
919 static void
920 virtio_dev_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
921 {
922         virtio_update_stats(dev, stats);
923 }
924
925 static void
926 virtio_dev_stats_reset(struct rte_eth_dev *dev)
927 {
928         unsigned int i;
929
930         for (i = 0; i < dev->data->nb_tx_queues; i++) {
931                 struct virtnet_tx *txvq = dev->data->tx_queues[i];
932                 if (txvq == NULL)
933                         continue;
934
935                 txvq->stats.packets = 0;
936                 txvq->stats.bytes = 0;
937                 txvq->stats.errors = 0;
938                 txvq->stats.multicast = 0;
939                 txvq->stats.broadcast = 0;
940                 memset(txvq->stats.size_bins, 0,
941                        sizeof(txvq->stats.size_bins[0]) * 8);
942         }
943
944         for (i = 0; i < dev->data->nb_rx_queues; i++) {
945                 struct virtnet_rx *rxvq = dev->data->rx_queues[i];
946                 if (rxvq == NULL)
947                         continue;
948
949                 rxvq->stats.packets = 0;
950                 rxvq->stats.bytes = 0;
951                 rxvq->stats.errors = 0;
952                 rxvq->stats.multicast = 0;
953                 rxvq->stats.broadcast = 0;
954                 memset(rxvq->stats.size_bins, 0,
955                        sizeof(rxvq->stats.size_bins[0]) * 8);
956         }
957 }
958
959 static void
960 virtio_set_hwaddr(struct virtio_hw *hw)
961 {
962         vtpci_write_dev_config(hw,
963                         offsetof(struct virtio_net_config, mac),
964                         &hw->mac_addr, ETHER_ADDR_LEN);
965 }
966
967 static void
968 virtio_get_hwaddr(struct virtio_hw *hw)
969 {
970         if (vtpci_with_feature(hw, VIRTIO_NET_F_MAC)) {
971                 vtpci_read_dev_config(hw,
972                         offsetof(struct virtio_net_config, mac),
973                         &hw->mac_addr, ETHER_ADDR_LEN);
974         } else {
975                 eth_random_addr(&hw->mac_addr[0]);
976                 virtio_set_hwaddr(hw);
977         }
978 }
979
980 static void
981 virtio_mac_table_set(struct virtio_hw *hw,
982                      const struct virtio_net_ctrl_mac *uc,
983                      const struct virtio_net_ctrl_mac *mc)
984 {
985         struct virtio_pmd_ctrl ctrl;
986         int err, len[2];
987
988         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
989                 PMD_DRV_LOG(INFO, "host does not support mac table");
990                 return;
991         }
992
993         ctrl.hdr.class = VIRTIO_NET_CTRL_MAC;
994         ctrl.hdr.cmd = VIRTIO_NET_CTRL_MAC_TABLE_SET;
995
996         len[0] = uc->entries * ETHER_ADDR_LEN + sizeof(uc->entries);
997         memcpy(ctrl.data, uc, len[0]);
998
999         len[1] = mc->entries * ETHER_ADDR_LEN + sizeof(mc->entries);
1000         memcpy(ctrl.data + len[0], mc, len[1]);
1001
1002         err = virtio_send_command(hw->cvq, &ctrl, len, 2);
1003         if (err != 0)
1004                 PMD_DRV_LOG(NOTICE, "mac table set failed: %d", err);
1005 }
1006
1007 static void
1008 virtio_mac_addr_add(struct rte_eth_dev *dev, struct ether_addr *mac_addr,
1009                     uint32_t index, uint32_t vmdq __rte_unused)
1010 {
1011         struct virtio_hw *hw = dev->data->dev_private;
1012         const struct ether_addr *addrs = dev->data->mac_addrs;
1013         unsigned int i;
1014         struct virtio_net_ctrl_mac *uc, *mc;
1015
1016         if (index >= VIRTIO_MAX_MAC_ADDRS) {
1017                 PMD_DRV_LOG(ERR, "mac address index %u out of range", index);
1018                 return;
1019         }
1020
1021         uc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(uc->entries));
1022         uc->entries = 0;
1023         mc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(mc->entries));
1024         mc->entries = 0;
1025
1026         for (i = 0; i < VIRTIO_MAX_MAC_ADDRS; i++) {
1027                 const struct ether_addr *addr
1028                         = (i == index) ? mac_addr : addrs + i;
1029                 struct virtio_net_ctrl_mac *tbl
1030                         = is_multicast_ether_addr(addr) ? mc : uc;
1031
1032                 memcpy(&tbl->macs[tbl->entries++], addr, ETHER_ADDR_LEN);
1033         }
1034
1035         virtio_mac_table_set(hw, uc, mc);
1036 }
1037
1038 static void
1039 virtio_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
1040 {
1041         struct virtio_hw *hw = dev->data->dev_private;
1042         struct ether_addr *addrs = dev->data->mac_addrs;
1043         struct virtio_net_ctrl_mac *uc, *mc;
1044         unsigned int i;
1045
1046         if (index >= VIRTIO_MAX_MAC_ADDRS) {
1047                 PMD_DRV_LOG(ERR, "mac address index %u out of range", index);
1048                 return;
1049         }
1050
1051         uc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(uc->entries));
1052         uc->entries = 0;
1053         mc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(mc->entries));
1054         mc->entries = 0;
1055
1056         for (i = 0; i < VIRTIO_MAX_MAC_ADDRS; i++) {
1057                 struct virtio_net_ctrl_mac *tbl;
1058
1059                 if (i == index || is_zero_ether_addr(addrs + i))
1060                         continue;
1061
1062                 tbl = is_multicast_ether_addr(addrs + i) ? mc : uc;
1063                 memcpy(&tbl->macs[tbl->entries++], addrs + i, ETHER_ADDR_LEN);
1064         }
1065
1066         virtio_mac_table_set(hw, uc, mc);
1067 }
1068
1069 static void
1070 virtio_mac_addr_set(struct rte_eth_dev *dev, struct ether_addr *mac_addr)
1071 {
1072         struct virtio_hw *hw = dev->data->dev_private;
1073
1074         memcpy(hw->mac_addr, mac_addr, ETHER_ADDR_LEN);
1075
1076         /* Use atomic update if available */
1077         if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
1078                 struct virtio_pmd_ctrl ctrl;
1079                 int len = ETHER_ADDR_LEN;
1080
1081                 ctrl.hdr.class = VIRTIO_NET_CTRL_MAC;
1082                 ctrl.hdr.cmd = VIRTIO_NET_CTRL_MAC_ADDR_SET;
1083
1084                 memcpy(ctrl.data, mac_addr, ETHER_ADDR_LEN);
1085                 virtio_send_command(hw->cvq, &ctrl, &len, 1);
1086         } else if (vtpci_with_feature(hw, VIRTIO_NET_F_MAC))
1087                 virtio_set_hwaddr(hw);
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_negotiate_features(struct virtio_hw *hw, uint64_t req_features)
1110 {
1111         uint64_t host_features;
1112
1113         /* Prepare guest_features: feature that driver wants to support */
1114         PMD_INIT_LOG(DEBUG, "guest_features before negotiate = %" PRIx64,
1115                 req_features);
1116
1117         /* Read device(host) feature bits */
1118         host_features = hw->vtpci_ops->get_features(hw);
1119         PMD_INIT_LOG(DEBUG, "host_features before negotiate = %" PRIx64,
1120                 host_features);
1121
1122         /*
1123          * Negotiate features: Subset of device feature bits are written back
1124          * guest feature bits.
1125          */
1126         hw->guest_features = req_features;
1127         hw->guest_features = vtpci_negotiate_features(hw, host_features);
1128         PMD_INIT_LOG(DEBUG, "features after negotiate = %" PRIx64,
1129                 hw->guest_features);
1130
1131         if (hw->modern) {
1132                 if (!vtpci_with_feature(hw, VIRTIO_F_VERSION_1)) {
1133                         PMD_INIT_LOG(ERR,
1134                                 "VIRTIO_F_VERSION_1 features is not enabled.");
1135                         return -1;
1136                 }
1137                 vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_FEATURES_OK);
1138                 if (!(vtpci_get_status(hw) & VIRTIO_CONFIG_STATUS_FEATURES_OK)) {
1139                         PMD_INIT_LOG(ERR,
1140                                 "failed to set FEATURES_OK status!");
1141                         return -1;
1142                 }
1143         }
1144
1145         hw->req_guest_features = req_features;
1146
1147         return 0;
1148 }
1149
1150 /*
1151  * Process Virtio Config changed interrupt and call the callback
1152  * if link state changed.
1153  */
1154 static void
1155 virtio_interrupt_handler(__rte_unused struct rte_intr_handle *handle,
1156                          void *param)
1157 {
1158         struct rte_eth_dev *dev = param;
1159         struct virtio_hw *hw = dev->data->dev_private;
1160         uint8_t isr;
1161
1162         /* Read interrupt status which clears interrupt */
1163         isr = vtpci_isr(hw);
1164         PMD_DRV_LOG(INFO, "interrupt status = %#x", isr);
1165
1166         if (rte_intr_enable(&dev->pci_dev->intr_handle) < 0)
1167                 PMD_DRV_LOG(ERR, "interrupt enable failed");
1168
1169         if (isr & VIRTIO_PCI_ISR_CONFIG) {
1170                 if (virtio_dev_link_update(dev, 0) == 0)
1171                         _rte_eth_dev_callback_process(dev,
1172                                                       RTE_ETH_EVENT_INTR_LSC, NULL);
1173         }
1174
1175 }
1176
1177 static void
1178 rx_func_get(struct rte_eth_dev *eth_dev)
1179 {
1180         struct virtio_hw *hw = eth_dev->data->dev_private;
1181         if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF))
1182                 eth_dev->rx_pkt_burst = &virtio_recv_mergeable_pkts;
1183         else
1184                 eth_dev->rx_pkt_burst = &virtio_recv_pkts;
1185 }
1186
1187 /* reset device and renegotiate features if needed */
1188 static int
1189 virtio_init_device(struct rte_eth_dev *eth_dev, uint64_t req_features)
1190 {
1191         struct virtio_hw *hw = eth_dev->data->dev_private;
1192         struct virtio_net_config *config;
1193         struct virtio_net_config local_config;
1194         struct rte_pci_device *pci_dev = eth_dev->pci_dev;
1195         int ret;
1196
1197         /* Reset the device although not necessary at startup */
1198         vtpci_reset(hw);
1199
1200         /* Tell the host we've noticed this device. */
1201         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_ACK);
1202
1203         /* Tell the host we've known how to drive the device. */
1204         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_DRIVER);
1205         if (virtio_negotiate_features(hw, req_features) < 0)
1206                 return -1;
1207
1208         /* If host does not support status then disable LSC */
1209         if (!vtpci_with_feature(hw, VIRTIO_NET_F_STATUS))
1210                 eth_dev->data->dev_flags &= ~RTE_ETH_DEV_INTR_LSC;
1211         else
1212                 eth_dev->data->dev_flags |= RTE_ETH_DEV_INTR_LSC;
1213
1214         rte_eth_copy_pci_info(eth_dev, pci_dev);
1215
1216         rx_func_get(eth_dev);
1217
1218         /* Setting up rx_header size for the device */
1219         if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF) ||
1220             vtpci_with_feature(hw, VIRTIO_F_VERSION_1))
1221                 hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr_mrg_rxbuf);
1222         else
1223                 hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr);
1224
1225         /* Copy the permanent MAC address to: virtio_hw */
1226         virtio_get_hwaddr(hw);
1227         ether_addr_copy((struct ether_addr *) hw->mac_addr,
1228                         &eth_dev->data->mac_addrs[0]);
1229         PMD_INIT_LOG(DEBUG,
1230                      "PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X",
1231                      hw->mac_addr[0], hw->mac_addr[1], hw->mac_addr[2],
1232                      hw->mac_addr[3], hw->mac_addr[4], hw->mac_addr[5]);
1233
1234         if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VQ)) {
1235                 config = &local_config;
1236
1237                 vtpci_read_dev_config(hw,
1238                         offsetof(struct virtio_net_config, mac),
1239                         &config->mac, sizeof(config->mac));
1240
1241                 if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
1242                         vtpci_read_dev_config(hw,
1243                                 offsetof(struct virtio_net_config, status),
1244                                 &config->status, sizeof(config->status));
1245                 } else {
1246                         PMD_INIT_LOG(DEBUG,
1247                                      "VIRTIO_NET_F_STATUS is not supported");
1248                         config->status = 0;
1249                 }
1250
1251                 if (vtpci_with_feature(hw, VIRTIO_NET_F_MQ)) {
1252                         vtpci_read_dev_config(hw,
1253                                 offsetof(struct virtio_net_config, max_virtqueue_pairs),
1254                                 &config->max_virtqueue_pairs,
1255                                 sizeof(config->max_virtqueue_pairs));
1256                 } else {
1257                         PMD_INIT_LOG(DEBUG,
1258                                      "VIRTIO_NET_F_MQ is not supported");
1259                         config->max_virtqueue_pairs = 1;
1260                 }
1261
1262                 hw->max_queue_pairs = config->max_virtqueue_pairs;
1263
1264                 PMD_INIT_LOG(DEBUG, "config->max_virtqueue_pairs=%d",
1265                                 config->max_virtqueue_pairs);
1266                 PMD_INIT_LOG(DEBUG, "config->status=%d", config->status);
1267                 PMD_INIT_LOG(DEBUG,
1268                                 "PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X",
1269                                 config->mac[0], config->mac[1],
1270                                 config->mac[2], config->mac[3],
1271                                 config->mac[4], config->mac[5]);
1272         } else {
1273                 PMD_INIT_LOG(DEBUG, "config->max_virtqueue_pairs=1");
1274                 hw->max_queue_pairs = 1;
1275         }
1276
1277         ret = virtio_alloc_queues(eth_dev);
1278         if (ret < 0)
1279                 return ret;
1280         vtpci_reinit_complete(hw);
1281
1282         if (pci_dev)
1283                 PMD_INIT_LOG(DEBUG, "port %d vendorID=0x%x deviceID=0x%x",
1284                         eth_dev->data->port_id, pci_dev->id.vendor_id,
1285                         pci_dev->id.device_id);
1286
1287         return 0;
1288 }
1289
1290 /*
1291  * This function is based on probe() function in virtio_pci.c
1292  * It returns 0 on success.
1293  */
1294 int
1295 eth_virtio_dev_init(struct rte_eth_dev *eth_dev)
1296 {
1297         struct virtio_hw *hw = eth_dev->data->dev_private;
1298         struct rte_pci_device *pci_dev;
1299         uint32_t dev_flags = RTE_ETH_DEV_DETACHABLE;
1300         int ret;
1301
1302         RTE_BUILD_BUG_ON(RTE_PKTMBUF_HEADROOM < sizeof(struct virtio_net_hdr_mrg_rxbuf));
1303
1304         eth_dev->dev_ops = &virtio_eth_dev_ops;
1305         eth_dev->tx_pkt_burst = &virtio_xmit_pkts;
1306
1307         if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
1308                 rx_func_get(eth_dev);
1309                 return 0;
1310         }
1311
1312         /* Allocate memory for storing MAC addresses */
1313         eth_dev->data->mac_addrs = rte_zmalloc("virtio", VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN, 0);
1314         if (eth_dev->data->mac_addrs == NULL) {
1315                 PMD_INIT_LOG(ERR,
1316                         "Failed to allocate %d bytes needed to store MAC addresses",
1317                         VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN);
1318                 return -ENOMEM;
1319         }
1320
1321         pci_dev = eth_dev->pci_dev;
1322
1323         if (pci_dev) {
1324                 ret = vtpci_init(pci_dev, hw, &dev_flags);
1325                 if (ret)
1326                         return ret;
1327         }
1328
1329         eth_dev->data->dev_flags = dev_flags;
1330
1331         /* reset device and negotiate default features */
1332         ret = virtio_init_device(eth_dev, VIRTIO_PMD_DEFAULT_GUEST_FEATURES);
1333         if (ret < 0)
1334                 return ret;
1335
1336         /* Setup interrupt callback  */
1337         if (eth_dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
1338                 rte_intr_callback_register(&pci_dev->intr_handle,
1339                         virtio_interrupt_handler, eth_dev);
1340
1341         return 0;
1342 }
1343
1344 static int
1345 eth_virtio_dev_uninit(struct rte_eth_dev *eth_dev)
1346 {
1347         struct rte_pci_device *pci_dev;
1348         struct virtio_hw *hw = eth_dev->data->dev_private;
1349
1350         PMD_INIT_FUNC_TRACE();
1351
1352         if (rte_eal_process_type() == RTE_PROC_SECONDARY)
1353                 return -EPERM;
1354
1355         if (hw->started == 1) {
1356                 virtio_dev_stop(eth_dev);
1357                 virtio_dev_close(eth_dev);
1358         }
1359         pci_dev = eth_dev->pci_dev;
1360
1361         eth_dev->dev_ops = NULL;
1362         eth_dev->tx_pkt_burst = NULL;
1363         eth_dev->rx_pkt_burst = NULL;
1364
1365         rte_free(eth_dev->data->mac_addrs);
1366         eth_dev->data->mac_addrs = NULL;
1367
1368         /* reset interrupt callback  */
1369         if (eth_dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
1370                 rte_intr_callback_unregister(&pci_dev->intr_handle,
1371                                                 virtio_interrupt_handler,
1372                                                 eth_dev);
1373         rte_eal_pci_unmap_device(pci_dev);
1374
1375         PMD_INIT_LOG(DEBUG, "dev_uninit completed");
1376
1377         return 0;
1378 }
1379
1380 static struct eth_driver rte_virtio_pmd = {
1381         .pci_drv = {
1382                 .driver = {
1383                         .name = "net_virtio",
1384                 },
1385                 .id_table = pci_id_virtio_map,
1386                 .drv_flags = RTE_PCI_DRV_DETACHABLE,
1387                 .probe = rte_eth_dev_pci_probe,
1388                 .remove = rte_eth_dev_pci_remove,
1389         },
1390         .eth_dev_init = eth_virtio_dev_init,
1391         .eth_dev_uninit = eth_virtio_dev_uninit,
1392         .dev_private_size = sizeof(struct virtio_hw),
1393 };
1394
1395 RTE_INIT(rte_virtio_pmd_init);
1396 static void
1397 rte_virtio_pmd_init(void)
1398 {
1399         if (rte_eal_iopl_init() != 0) {
1400                 PMD_INIT_LOG(ERR, "IOPL call failed - cannot use virtio PMD");
1401                 return;
1402         }
1403
1404         rte_eal_pci_register(&rte_virtio_pmd.pci_drv);
1405 }
1406
1407 /*
1408  * Configure virtio device
1409  * It returns 0 on success.
1410  */
1411 static int
1412 virtio_dev_configure(struct rte_eth_dev *dev)
1413 {
1414         const struct rte_eth_rxmode *rxmode = &dev->data->dev_conf.rxmode;
1415         struct virtio_hw *hw = dev->data->dev_private;
1416         uint64_t req_features;
1417         int ret;
1418
1419         PMD_INIT_LOG(DEBUG, "configure");
1420         req_features = VIRTIO_PMD_DEFAULT_GUEST_FEATURES;
1421         if (rxmode->hw_ip_checksum)
1422                 req_features |= (1ULL << VIRTIO_NET_F_GUEST_CSUM);
1423         if (rxmode->enable_lro)
1424                 req_features |=
1425                         (1ULL << VIRTIO_NET_F_GUEST_TSO4) |
1426                         (1ULL << VIRTIO_NET_F_GUEST_TSO6);
1427
1428         /* if request features changed, reinit the device */
1429         if (req_features != hw->req_guest_features) {
1430                 ret = virtio_init_device(dev, req_features);
1431                 if (ret < 0)
1432                         return ret;
1433         }
1434
1435         if (rxmode->hw_ip_checksum &&
1436                 !vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_CSUM)) {
1437                 PMD_DRV_LOG(NOTICE,
1438                         "rx ip checksum not available on this host");
1439                 return -ENOTSUP;
1440         }
1441
1442         if (rxmode->enable_lro &&
1443                 (!vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_TSO4) ||
1444                         !vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_TSO4))) {
1445                 PMD_DRV_LOG(NOTICE,
1446                         "lro not available on this host");
1447                 return -ENOTSUP;
1448         }
1449
1450         /* start control queue */
1451         if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VQ))
1452                 virtio_dev_cq_start(dev);
1453
1454         hw->vlan_strip = rxmode->hw_vlan_strip;
1455
1456         if (rxmode->hw_vlan_filter
1457             && !vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VLAN)) {
1458                 PMD_DRV_LOG(NOTICE,
1459                             "vlan filtering not available on this host");
1460                 return -ENOTSUP;
1461         }
1462
1463         if (dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
1464                 if (vtpci_irq_config(hw, 0) == VIRTIO_MSI_NO_VECTOR) {
1465                         PMD_DRV_LOG(ERR, "failed to set config vector");
1466                         return -EBUSY;
1467                 }
1468
1469         return 0;
1470 }
1471
1472
1473 static int
1474 virtio_dev_start(struct rte_eth_dev *dev)
1475 {
1476         uint16_t nb_queues, i;
1477         struct virtio_hw *hw = dev->data->dev_private;
1478         struct virtnet_rx *rxvq;
1479         struct virtnet_tx *txvq __rte_unused;
1480
1481         /* check if lsc interrupt feature is enabled */
1482         if (dev->data->dev_conf.intr_conf.lsc) {
1483                 if (!(dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)) {
1484                         PMD_DRV_LOG(ERR, "link status not supported by host");
1485                         return -ENOTSUP;
1486                 }
1487
1488                 if (rte_intr_enable(&dev->pci_dev->intr_handle) < 0) {
1489                         PMD_DRV_LOG(ERR, "interrupt enable failed");
1490                         return -EIO;
1491                 }
1492         }
1493
1494         /* Initialize Link state */
1495         virtio_dev_link_update(dev, 0);
1496
1497         /* On restart after stop do not touch queues */
1498         if (hw->started)
1499                 return 0;
1500
1501         hw->started = 1;
1502
1503         /*Notify the backend
1504          *Otherwise the tap backend might already stop its queue due to fullness.
1505          *vhost backend will have no chance to be waked up
1506          */
1507         nb_queues = dev->data->nb_rx_queues;
1508         if (nb_queues > 1) {
1509                 if (virtio_set_multiple_queues(dev, nb_queues) != 0)
1510                         return -EINVAL;
1511         }
1512
1513         PMD_INIT_LOG(DEBUG, "nb_queues=%d", nb_queues);
1514
1515         for (i = 0; i < nb_queues; i++) {
1516                 rxvq = dev->data->rx_queues[i];
1517                 virtqueue_notify(rxvq->vq);
1518         }
1519
1520         PMD_INIT_LOG(DEBUG, "Notified backend at initialization");
1521
1522         for (i = 0; i < dev->data->nb_rx_queues; i++) {
1523                 rxvq = dev->data->rx_queues[i];
1524                 VIRTQUEUE_DUMP(rxvq->vq);
1525         }
1526
1527         for (i = 0; i < dev->data->nb_tx_queues; i++) {
1528                 txvq = dev->data->tx_queues[i];
1529                 VIRTQUEUE_DUMP(txvq->vq);
1530         }
1531
1532         return 0;
1533 }
1534
1535 static void virtio_dev_free_mbufs(struct rte_eth_dev *dev)
1536 {
1537         struct rte_mbuf *buf;
1538         int i, mbuf_num = 0;
1539
1540         for (i = 0; i < dev->data->nb_rx_queues; i++) {
1541                 struct virtnet_rx *rxvq = dev->data->rx_queues[i];
1542
1543                 PMD_INIT_LOG(DEBUG,
1544                              "Before freeing rxq[%d] used and unused buf", i);
1545                 VIRTQUEUE_DUMP(rxvq->vq);
1546
1547                 PMD_INIT_LOG(DEBUG, "rx_queues[%d]=%p", i, rxvq);
1548                 while ((buf = virtqueue_detatch_unused(rxvq->vq)) != NULL) {
1549                         rte_pktmbuf_free(buf);
1550                         mbuf_num++;
1551                 }
1552
1553                 PMD_INIT_LOG(DEBUG, "free %d mbufs", mbuf_num);
1554                 PMD_INIT_LOG(DEBUG,
1555                              "After freeing rxq[%d] used and unused buf", i);
1556                 VIRTQUEUE_DUMP(rxvq->vq);
1557         }
1558
1559         for (i = 0; i < dev->data->nb_tx_queues; i++) {
1560                 struct virtnet_tx *txvq = dev->data->tx_queues[i];
1561
1562                 PMD_INIT_LOG(DEBUG,
1563                              "Before freeing txq[%d] used and unused bufs",
1564                              i);
1565                 VIRTQUEUE_DUMP(txvq->vq);
1566
1567                 mbuf_num = 0;
1568                 while ((buf = virtqueue_detatch_unused(txvq->vq)) != NULL) {
1569                         rte_pktmbuf_free(buf);
1570                         mbuf_num++;
1571                 }
1572
1573                 PMD_INIT_LOG(DEBUG, "free %d mbufs", mbuf_num);
1574                 PMD_INIT_LOG(DEBUG,
1575                              "After freeing txq[%d] used and unused buf", i);
1576                 VIRTQUEUE_DUMP(txvq->vq);
1577         }
1578 }
1579
1580 /*
1581  * Stop device: disable interrupt and mark link down
1582  */
1583 static void
1584 virtio_dev_stop(struct rte_eth_dev *dev)
1585 {
1586         struct rte_eth_link link;
1587
1588         PMD_INIT_LOG(DEBUG, "stop");
1589
1590         if (dev->data->dev_conf.intr_conf.lsc)
1591                 rte_intr_disable(&dev->pci_dev->intr_handle);
1592
1593         memset(&link, 0, sizeof(link));
1594         virtio_dev_atomic_write_link_status(dev, &link);
1595 }
1596
1597 static int
1598 virtio_dev_link_update(struct rte_eth_dev *dev, __rte_unused int wait_to_complete)
1599 {
1600         struct rte_eth_link link, old;
1601         uint16_t status;
1602         struct virtio_hw *hw = dev->data->dev_private;
1603         memset(&link, 0, sizeof(link));
1604         virtio_dev_atomic_read_link_status(dev, &link);
1605         old = link;
1606         link.link_duplex = ETH_LINK_FULL_DUPLEX;
1607         link.link_speed  = SPEED_10G;
1608
1609         if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
1610                 PMD_INIT_LOG(DEBUG, "Get link status from hw");
1611                 vtpci_read_dev_config(hw,
1612                                 offsetof(struct virtio_net_config, status),
1613                                 &status, sizeof(status));
1614                 if ((status & VIRTIO_NET_S_LINK_UP) == 0) {
1615                         link.link_status = ETH_LINK_DOWN;
1616                         PMD_INIT_LOG(DEBUG, "Port %d is down",
1617                                      dev->data->port_id);
1618                 } else {
1619                         link.link_status = ETH_LINK_UP;
1620                         PMD_INIT_LOG(DEBUG, "Port %d is up",
1621                                      dev->data->port_id);
1622                 }
1623         } else {
1624                 link.link_status = ETH_LINK_UP;
1625         }
1626         virtio_dev_atomic_write_link_status(dev, &link);
1627
1628         return (old.link_status == link.link_status) ? -1 : 0;
1629 }
1630
1631 static void
1632 virtio_dev_info_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *dev_info)
1633 {
1634         uint64_t tso_mask;
1635         struct virtio_hw *hw = dev->data->dev_private;
1636
1637         if (dev->pci_dev)
1638                 dev_info->driver_name = dev->driver->pci_drv.driver.name;
1639         else
1640                 dev_info->driver_name = "virtio_user PMD";
1641         dev_info->max_rx_queues =
1642                 RTE_MIN(hw->max_queue_pairs, VIRTIO_MAX_RX_QUEUES);
1643         dev_info->max_tx_queues =
1644                 RTE_MIN(hw->max_queue_pairs, VIRTIO_MAX_TX_QUEUES);
1645         dev_info->min_rx_bufsize = VIRTIO_MIN_RX_BUFSIZE;
1646         dev_info->max_rx_pktlen = VIRTIO_MAX_RX_PKTLEN;
1647         dev_info->max_mac_addrs = VIRTIO_MAX_MAC_ADDRS;
1648         dev_info->default_txconf = (struct rte_eth_txconf) {
1649                 .txq_flags = ETH_TXQ_FLAGS_NOOFFLOADS
1650         };
1651         dev_info->rx_offload_capa =
1652                 DEV_RX_OFFLOAD_TCP_CKSUM |
1653                 DEV_RX_OFFLOAD_UDP_CKSUM |
1654                 DEV_RX_OFFLOAD_TCP_LRO;
1655         dev_info->tx_offload_capa = 0;
1656
1657         if (hw->guest_features & (1ULL << VIRTIO_NET_F_CSUM)) {
1658                 dev_info->tx_offload_capa |=
1659                         DEV_TX_OFFLOAD_UDP_CKSUM |
1660                         DEV_TX_OFFLOAD_TCP_CKSUM;
1661         }
1662
1663         tso_mask = (1ULL << VIRTIO_NET_F_HOST_TSO4) |
1664                 (1ULL << VIRTIO_NET_F_HOST_TSO6);
1665         if ((hw->guest_features & tso_mask) == tso_mask)
1666                 dev_info->tx_offload_capa |= DEV_TX_OFFLOAD_TCP_TSO;
1667 }
1668
1669 /*
1670  * It enables testpmd to collect per queue stats.
1671  */
1672 static int
1673 virtio_dev_queue_stats_mapping_set(__rte_unused struct rte_eth_dev *eth_dev,
1674 __rte_unused uint16_t queue_id, __rte_unused uint8_t stat_idx,
1675 __rte_unused uint8_t is_rx)
1676 {
1677         return 0;
1678 }
1679
1680 RTE_PMD_EXPORT_NAME(net_virtio, __COUNTER__);
1681 RTE_PMD_REGISTER_PCI_TABLE(net_virtio, pci_id_virtio_map);