virtio: fix ring size negotiation
[dpdk.git] / drivers / net / virtio / virtio_ethdev.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include <stdint.h>
35 #include <string.h>
36 #include <stdio.h>
37 #include <errno.h>
38 #include <unistd.h>
39 #ifdef RTE_EXEC_ENV_LINUXAPP
40 #include <dirent.h>
41 #include <fcntl.h>
42 #endif
43
44 #include <rte_ethdev.h>
45 #include <rte_memcpy.h>
46 #include <rte_string_fns.h>
47 #include <rte_memzone.h>
48 #include <rte_malloc.h>
49 #include <rte_atomic.h>
50 #include <rte_branch_prediction.h>
51 #include <rte_pci.h>
52 #include <rte_ether.h>
53 #include <rte_common.h>
54
55 #include <rte_memory.h>
56 #include <rte_eal.h>
57 #include <rte_dev.h>
58
59 #include "virtio_ethdev.h"
60 #include "virtio_pci.h"
61 #include "virtio_logs.h"
62 #include "virtqueue.h"
63
64
65 static int eth_virtio_dev_init(struct rte_eth_dev *eth_dev);
66 static int  virtio_dev_configure(struct rte_eth_dev *dev);
67 static int  virtio_dev_start(struct rte_eth_dev *dev);
68 static void virtio_dev_stop(struct rte_eth_dev *dev);
69 static void virtio_dev_promiscuous_enable(struct rte_eth_dev *dev);
70 static void virtio_dev_promiscuous_disable(struct rte_eth_dev *dev);
71 static void virtio_dev_allmulticast_enable(struct rte_eth_dev *dev);
72 static void virtio_dev_allmulticast_disable(struct rte_eth_dev *dev);
73 static void virtio_dev_info_get(struct rte_eth_dev *dev,
74                                 struct rte_eth_dev_info *dev_info);
75 static int virtio_dev_link_update(struct rte_eth_dev *dev,
76         __rte_unused int wait_to_complete);
77
78 static void virtio_set_hwaddr(struct virtio_hw *hw);
79 static void virtio_get_hwaddr(struct virtio_hw *hw);
80
81 static void virtio_dev_rx_queue_release(__rte_unused void *rxq);
82 static void virtio_dev_tx_queue_release(__rte_unused void *txq);
83
84 static void virtio_dev_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats);
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
107 #define RTE_PCI_DEV_ID_DECL_VIRTIO(vend, dev) {RTE_PCI_DEVICE(vend, dev)},
108 #include "rte_pci_dev_ids.h"
109
110 { .vendor_id = 0, /* sentinel */ },
111 };
112
113 static int
114 virtio_send_command(struct virtqueue *vq, struct virtio_pmd_ctrl *ctrl,
115                 int *dlen, int pkt_num)
116 {
117         uint16_t head = vq->vq_desc_head_idx, i;
118         int k, sum = 0;
119         virtio_net_ctrl_ack status = ~0;
120         struct virtio_pmd_ctrl result;
121
122         ctrl->status = status;
123
124         if (!vq->hw->cvq) {
125                 PMD_INIT_LOG(ERR,
126                              "%s(): Control queue is not supported.",
127                              __func__);
128                 return -1;
129         }
130
131         PMD_INIT_LOG(DEBUG, "vq->vq_desc_head_idx = %d, status = %d, "
132                 "vq->hw->cvq = %p vq = %p",
133                 vq->vq_desc_head_idx, status, vq->hw->cvq, vq);
134
135         if ((vq->vq_free_cnt < ((uint32_t)pkt_num + 2)) || (pkt_num < 1))
136                 return -1;
137
138         memcpy(vq->virtio_net_hdr_mz->addr, ctrl,
139                 sizeof(struct virtio_pmd_ctrl));
140
141         /*
142          * Format is enforced in qemu code:
143          * One TX packet for header;
144          * At least one TX packet per argument;
145          * One RX packet for ACK.
146          */
147         vq->vq_ring.desc[head].flags = VRING_DESC_F_NEXT;
148         vq->vq_ring.desc[head].addr = vq->virtio_net_hdr_mz->phys_addr;
149         vq->vq_ring.desc[head].len = sizeof(struct virtio_net_ctrl_hdr);
150         vq->vq_free_cnt--;
151         i = vq->vq_ring.desc[head].next;
152
153         for (k = 0; k < pkt_num; k++) {
154                 vq->vq_ring.desc[i].flags = VRING_DESC_F_NEXT;
155                 vq->vq_ring.desc[i].addr = vq->virtio_net_hdr_mz->phys_addr
156                         + sizeof(struct virtio_net_ctrl_hdr)
157                         + sizeof(ctrl->status) + sizeof(uint8_t)*sum;
158                 vq->vq_ring.desc[i].len = dlen[k];
159                 sum += dlen[k];
160                 vq->vq_free_cnt--;
161                 i = vq->vq_ring.desc[i].next;
162         }
163
164         vq->vq_ring.desc[i].flags = VRING_DESC_F_WRITE;
165         vq->vq_ring.desc[i].addr = vq->virtio_net_hdr_mz->phys_addr
166                         + sizeof(struct virtio_net_ctrl_hdr);
167         vq->vq_ring.desc[i].len = sizeof(ctrl->status);
168         vq->vq_free_cnt--;
169
170         vq->vq_desc_head_idx = vq->vq_ring.desc[i].next;
171
172         vq_update_avail_ring(vq, head);
173         vq_update_avail_idx(vq);
174
175         PMD_INIT_LOG(DEBUG, "vq->vq_queue_index = %d", vq->vq_queue_index);
176
177         virtqueue_notify(vq);
178
179         rte_rmb();
180         while (vq->vq_used_cons_idx == vq->vq_ring.used->idx) {
181                 rte_rmb();
182                 usleep(100);
183         }
184
185         while (vq->vq_used_cons_idx != vq->vq_ring.used->idx) {
186                 uint32_t idx, desc_idx, used_idx;
187                 struct vring_used_elem *uep;
188
189                 used_idx = (uint32_t)(vq->vq_used_cons_idx
190                                 & (vq->vq_nentries - 1));
191                 uep = &vq->vq_ring.used->ring[used_idx];
192                 idx = (uint32_t) uep->id;
193                 desc_idx = idx;
194
195                 while (vq->vq_ring.desc[desc_idx].flags & VRING_DESC_F_NEXT) {
196                         desc_idx = vq->vq_ring.desc[desc_idx].next;
197                         vq->vq_free_cnt++;
198                 }
199
200                 vq->vq_ring.desc[desc_idx].next = vq->vq_desc_head_idx;
201                 vq->vq_desc_head_idx = idx;
202
203                 vq->vq_used_cons_idx++;
204                 vq->vq_free_cnt++;
205         }
206
207         PMD_INIT_LOG(DEBUG, "vq->vq_free_cnt=%d\nvq->vq_desc_head_idx=%d",
208                         vq->vq_free_cnt, vq->vq_desc_head_idx);
209
210         memcpy(&result, vq->virtio_net_hdr_mz->addr,
211                         sizeof(struct virtio_pmd_ctrl));
212
213         return result.status;
214 }
215
216 static int
217 virtio_set_multiple_queues(struct rte_eth_dev *dev, uint16_t nb_queues)
218 {
219         struct virtio_hw *hw = dev->data->dev_private;
220         struct virtio_pmd_ctrl ctrl;
221         int dlen[1];
222         int ret;
223
224         ctrl.hdr.class = VIRTIO_NET_CTRL_MQ;
225         ctrl.hdr.cmd = VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET;
226         memcpy(ctrl.data, &nb_queues, sizeof(uint16_t));
227
228         dlen[0] = sizeof(uint16_t);
229
230         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
231         if (ret) {
232                 PMD_INIT_LOG(ERR, "Multiqueue configured but send command "
233                           "failed, this is too late now...");
234                 return -EINVAL;
235         }
236
237         return 0;
238 }
239
240 int virtio_dev_queue_setup(struct rte_eth_dev *dev,
241                         int queue_type,
242                         uint16_t queue_idx,
243                         uint16_t  vtpci_queue_idx,
244                         uint16_t nb_desc,
245                         unsigned int socket_id,
246                         struct virtqueue **pvq)
247 {
248         char vq_name[VIRTQUEUE_MAX_NAME_SZ];
249         const struct rte_memzone *mz;
250         uint16_t vq_size;
251         int size;
252         struct virtio_hw *hw = dev->data->dev_private;
253         struct virtqueue  *vq = NULL;
254
255         /* Write the virtqueue index to the Queue Select Field */
256         VIRTIO_WRITE_REG_2(hw, VIRTIO_PCI_QUEUE_SEL, vtpci_queue_idx);
257         PMD_INIT_LOG(DEBUG, "selecting queue: %d", vtpci_queue_idx);
258
259         /*
260          * Read the virtqueue size from the Queue Size field
261          * Always power of 2 and if 0 virtqueue does not exist
262          */
263         vq_size = VIRTIO_READ_REG_2(hw, VIRTIO_PCI_QUEUE_NUM);
264         PMD_INIT_LOG(DEBUG, "vq_size: %d nb_desc:%d", vq_size, nb_desc);
265         if (nb_desc == 0)
266                 nb_desc = vq_size;
267         if (vq_size == 0) {
268                 PMD_INIT_LOG(ERR, "%s: virtqueue does not exist", __func__);
269                 return -EINVAL;
270         }
271
272         if (!rte_is_power_of_2(vq_size)) {
273                 PMD_INIT_LOG(ERR, "%s: virtqueue size is not powerof 2", __func__);
274                 return -EINVAL;
275         }
276
277         if (nb_desc < vq_size) {
278                 if (!rte_is_power_of_2(nb_desc)) {
279                         PMD_INIT_LOG(ERR,
280                                      "nb_desc(%u) size is not powerof 2",
281                                      nb_desc);
282                         return -EINVAL;
283                 }
284                 vq_size = nb_desc;
285         }
286
287         if (queue_type == VTNET_RQ) {
288                 snprintf(vq_name, sizeof(vq_name), "port%d_rvq%d",
289                         dev->data->port_id, queue_idx);
290                 vq = rte_zmalloc(vq_name, sizeof(struct virtqueue) +
291                         vq_size * sizeof(struct vq_desc_extra), RTE_CACHE_LINE_SIZE);
292         } else if (queue_type == VTNET_TQ) {
293                 snprintf(vq_name, sizeof(vq_name), "port%d_tvq%d",
294                         dev->data->port_id, queue_idx);
295                 vq = rte_zmalloc(vq_name, sizeof(struct virtqueue) +
296                         vq_size * sizeof(struct vq_desc_extra), RTE_CACHE_LINE_SIZE);
297         } else if (queue_type == VTNET_CQ) {
298                 snprintf(vq_name, sizeof(vq_name), "port%d_cvq",
299                         dev->data->port_id);
300                 vq = rte_zmalloc(vq_name, sizeof(struct virtqueue) +
301                         vq_size * sizeof(struct vq_desc_extra),
302                         RTE_CACHE_LINE_SIZE);
303         }
304         if (vq == NULL) {
305                 PMD_INIT_LOG(ERR, "%s: Can not allocate virtqueue", __func__);
306                 return (-ENOMEM);
307         }
308
309         vq->hw = hw;
310         vq->port_id = dev->data->port_id;
311         vq->queue_id = queue_idx;
312         vq->vq_queue_index = vtpci_queue_idx;
313         vq->vq_nentries = vq_size;
314         vq->vq_free_cnt = vq_size;
315
316         /*
317          * Reserve a memzone for vring elements
318          */
319         size = vring_size(vq_size, VIRTIO_PCI_VRING_ALIGN);
320         vq->vq_ring_size = RTE_ALIGN_CEIL(size, VIRTIO_PCI_VRING_ALIGN);
321         PMD_INIT_LOG(DEBUG, "vring_size: %d, rounded_vring_size: %d", size, vq->vq_ring_size);
322
323         mz = rte_memzone_reserve_aligned(vq_name, vq->vq_ring_size,
324                 socket_id, 0, VIRTIO_PCI_VRING_ALIGN);
325         if (mz == NULL) {
326                 rte_free(vq);
327                 return -ENOMEM;
328         }
329
330         /*
331          * Virtio PCI device VIRTIO_PCI_QUEUE_PF register is 32bit,
332          * and only accepts 32 bit page frame number.
333          * Check if the allocated physical memory exceeds 16TB.
334          */
335         if ((mz->phys_addr + vq->vq_ring_size - 1) >> (VIRTIO_PCI_QUEUE_ADDR_SHIFT + 32)) {
336                 PMD_INIT_LOG(ERR, "vring address shouldn't be above 16TB!");
337                 rte_free(vq);
338                 return -ENOMEM;
339         }
340
341         memset(mz->addr, 0, sizeof(mz->len));
342         vq->mz = mz;
343         vq->vq_ring_mem = mz->phys_addr;
344         vq->vq_ring_virt_mem = mz->addr;
345         PMD_INIT_LOG(DEBUG, "vq->vq_ring_mem:      0x%"PRIx64, (uint64_t)mz->phys_addr);
346         PMD_INIT_LOG(DEBUG, "vq->vq_ring_virt_mem: 0x%"PRIx64, (uint64_t)(uintptr_t)mz->addr);
347         vq->virtio_net_hdr_mz  = NULL;
348         vq->virtio_net_hdr_mem = 0;
349
350         if (queue_type == VTNET_TQ) {
351                 /*
352                  * For each xmit packet, allocate a virtio_net_hdr
353                  */
354                 snprintf(vq_name, sizeof(vq_name), "port%d_tvq%d_hdrzone",
355                         dev->data->port_id, queue_idx);
356                 vq->virtio_net_hdr_mz = rte_memzone_reserve_aligned(vq_name,
357                         vq_size * hw->vtnet_hdr_size,
358                         socket_id, 0, RTE_CACHE_LINE_SIZE);
359                 if (vq->virtio_net_hdr_mz == NULL) {
360                         rte_free(vq);
361                         return -ENOMEM;
362                 }
363                 vq->virtio_net_hdr_mem =
364                         vq->virtio_net_hdr_mz->phys_addr;
365                 memset(vq->virtio_net_hdr_mz->addr, 0,
366                         vq_size * hw->vtnet_hdr_size);
367         } else if (queue_type == VTNET_CQ) {
368                 /* Allocate a page for control vq command, data and status */
369                 snprintf(vq_name, sizeof(vq_name), "port%d_cvq_hdrzone",
370                         dev->data->port_id);
371                 vq->virtio_net_hdr_mz = rte_memzone_reserve_aligned(vq_name,
372                         PAGE_SIZE, socket_id, 0, RTE_CACHE_LINE_SIZE);
373                 if (vq->virtio_net_hdr_mz == NULL) {
374                         rte_free(vq);
375                         return -ENOMEM;
376                 }
377                 vq->virtio_net_hdr_mem =
378                         vq->virtio_net_hdr_mz->phys_addr;
379                 memset(vq->virtio_net_hdr_mz->addr, 0, PAGE_SIZE);
380         }
381
382         /*
383          * Set guest physical address of the virtqueue
384          * in VIRTIO_PCI_QUEUE_PFN config register of device
385          */
386         VIRTIO_WRITE_REG_4(hw, VIRTIO_PCI_QUEUE_PFN,
387                         mz->phys_addr >> VIRTIO_PCI_QUEUE_ADDR_SHIFT);
388         *pvq = vq;
389         return 0;
390 }
391
392 static int
393 virtio_dev_cq_queue_setup(struct rte_eth_dev *dev, uint16_t vtpci_queue_idx,
394                 uint32_t socket_id)
395 {
396         struct virtqueue *vq;
397         uint16_t nb_desc = 0;
398         int ret;
399         struct virtio_hw *hw = dev->data->dev_private;
400
401         PMD_INIT_FUNC_TRACE();
402         ret = virtio_dev_queue_setup(dev, VTNET_CQ, VTNET_SQ_CQ_QUEUE_IDX,
403                         vtpci_queue_idx, nb_desc, socket_id, &vq);
404         if (ret < 0) {
405                 PMD_INIT_LOG(ERR, "control vq initialization failed");
406                 return ret;
407         }
408
409         hw->cvq = vq;
410         return 0;
411 }
412
413 static void
414 virtio_dev_close(struct rte_eth_dev *dev)
415 {
416         struct virtio_hw *hw = dev->data->dev_private;
417         struct rte_pci_device *pci_dev = dev->pci_dev;
418
419         PMD_INIT_LOG(DEBUG, "virtio_dev_close");
420
421         /* reset the NIC */
422         if (pci_dev->driver->drv_flags & RTE_PCI_DRV_INTR_LSC)
423                 vtpci_irq_config(hw, VIRTIO_MSI_NO_VECTOR);
424         vtpci_reset(hw);
425         hw->started = 0;
426         virtio_dev_free_mbufs(dev);
427 }
428
429 static void
430 virtio_dev_promiscuous_enable(struct rte_eth_dev *dev)
431 {
432         struct virtio_hw *hw = dev->data->dev_private;
433         struct virtio_pmd_ctrl ctrl;
434         int dlen[1];
435         int ret;
436
437         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
438                 PMD_INIT_LOG(INFO, "host does not support rx control\n");
439                 return;
440         }
441
442         ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
443         ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_PROMISC;
444         ctrl.data[0] = 1;
445         dlen[0] = 1;
446
447         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
448         if (ret)
449                 PMD_INIT_LOG(ERR, "Failed to enable promisc");
450 }
451
452 static void
453 virtio_dev_promiscuous_disable(struct rte_eth_dev *dev)
454 {
455         struct virtio_hw *hw = dev->data->dev_private;
456         struct virtio_pmd_ctrl ctrl;
457         int dlen[1];
458         int ret;
459
460         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
461                 PMD_INIT_LOG(INFO, "host does not support rx control\n");
462                 return;
463         }
464
465         ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
466         ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_PROMISC;
467         ctrl.data[0] = 0;
468         dlen[0] = 1;
469
470         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
471         if (ret)
472                 PMD_INIT_LOG(ERR, "Failed to disable promisc");
473 }
474
475 static void
476 virtio_dev_allmulticast_enable(struct rte_eth_dev *dev)
477 {
478         struct virtio_hw *hw = dev->data->dev_private;
479         struct virtio_pmd_ctrl ctrl;
480         int dlen[1];
481         int ret;
482
483         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
484                 PMD_INIT_LOG(INFO, "host does not support rx control\n");
485                 return;
486         }
487
488         ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
489         ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_ALLMULTI;
490         ctrl.data[0] = 1;
491         dlen[0] = 1;
492
493         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
494         if (ret)
495                 PMD_INIT_LOG(ERR, "Failed to enable allmulticast");
496 }
497
498 static void
499 virtio_dev_allmulticast_disable(struct rte_eth_dev *dev)
500 {
501         struct virtio_hw *hw = dev->data->dev_private;
502         struct virtio_pmd_ctrl ctrl;
503         int dlen[1];
504         int ret;
505
506         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
507                 PMD_INIT_LOG(INFO, "host does not support rx control\n");
508                 return;
509         }
510
511         ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
512         ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_ALLMULTI;
513         ctrl.data[0] = 0;
514         dlen[0] = 1;
515
516         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
517         if (ret)
518                 PMD_INIT_LOG(ERR, "Failed to disable allmulticast");
519 }
520
521 /*
522  * dev_ops for virtio, bare necessities for basic operation
523  */
524 static const struct eth_dev_ops virtio_eth_dev_ops = {
525         .dev_configure           = virtio_dev_configure,
526         .dev_start               = virtio_dev_start,
527         .dev_stop                = virtio_dev_stop,
528         .dev_close               = virtio_dev_close,
529         .promiscuous_enable      = virtio_dev_promiscuous_enable,
530         .promiscuous_disable     = virtio_dev_promiscuous_disable,
531         .allmulticast_enable     = virtio_dev_allmulticast_enable,
532         .allmulticast_disable    = virtio_dev_allmulticast_disable,
533
534         .dev_infos_get           = virtio_dev_info_get,
535         .stats_get               = virtio_dev_stats_get,
536         .stats_reset             = virtio_dev_stats_reset,
537         .link_update             = virtio_dev_link_update,
538         .rx_queue_setup          = virtio_dev_rx_queue_setup,
539         /* meaningfull only to multiple queue */
540         .rx_queue_release        = virtio_dev_rx_queue_release,
541         .tx_queue_setup          = virtio_dev_tx_queue_setup,
542         /* meaningfull only to multiple queue */
543         .tx_queue_release        = virtio_dev_tx_queue_release,
544         /* collect stats per queue */
545         .queue_stats_mapping_set = virtio_dev_queue_stats_mapping_set,
546         .vlan_filter_set         = virtio_vlan_filter_set,
547         .mac_addr_add            = virtio_mac_addr_add,
548         .mac_addr_remove         = virtio_mac_addr_remove,
549         .mac_addr_set            = virtio_mac_addr_set,
550 };
551
552 static inline int
553 virtio_dev_atomic_read_link_status(struct rte_eth_dev *dev,
554                                 struct rte_eth_link *link)
555 {
556         struct rte_eth_link *dst = link;
557         struct rte_eth_link *src = &(dev->data->dev_link);
558
559         if (rte_atomic64_cmpset((uint64_t *)dst, *(uint64_t *)dst,
560                         *(uint64_t *)src) == 0)
561                 return -1;
562
563         return 0;
564 }
565
566 /**
567  * Atomically writes the link status information into global
568  * structure rte_eth_dev.
569  *
570  * @param dev
571  *   - Pointer to the structure rte_eth_dev to read from.
572  *   - Pointer to the buffer to be saved with the link status.
573  *
574  * @return
575  *   - On success, zero.
576  *   - On failure, negative value.
577  */
578 static inline int
579 virtio_dev_atomic_write_link_status(struct rte_eth_dev *dev,
580                 struct rte_eth_link *link)
581 {
582         struct rte_eth_link *dst = &(dev->data->dev_link);
583         struct rte_eth_link *src = link;
584
585         if (rte_atomic64_cmpset((uint64_t *)dst, *(uint64_t *)dst,
586                                         *(uint64_t *)src) == 0)
587                 return -1;
588
589         return 0;
590 }
591
592 static void
593 virtio_dev_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
594 {
595         unsigned i;
596
597         for (i = 0; i < dev->data->nb_tx_queues; i++) {
598                 const struct virtqueue *txvq = dev->data->tx_queues[i];
599                 if (txvq == NULL)
600                         continue;
601
602                 stats->opackets += txvq->packets;
603                 stats->obytes += txvq->bytes;
604                 stats->oerrors += txvq->errors;
605
606                 if (i < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
607                         stats->q_opackets[i] = txvq->packets;
608                         stats->q_obytes[i] = txvq->bytes;
609                 }
610         }
611
612         for (i = 0; i < dev->data->nb_rx_queues; i++) {
613                 const struct virtqueue *rxvq = dev->data->rx_queues[i];
614                 if (rxvq == NULL)
615                         continue;
616
617                 stats->ipackets += rxvq->packets;
618                 stats->ibytes += rxvq->bytes;
619                 stats->ierrors += rxvq->errors;
620
621                 if (i < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
622                         stats->q_ipackets[i] = rxvq->packets;
623                         stats->q_ibytes[i] = rxvq->bytes;
624                 }
625         }
626
627         stats->rx_nombuf = dev->data->rx_mbuf_alloc_failed;
628 }
629
630 static void
631 virtio_dev_stats_reset(struct rte_eth_dev *dev)
632 {
633         unsigned int i;
634
635         for (i = 0; i < dev->data->nb_tx_queues; i++) {
636                 struct virtqueue *txvq = dev->data->tx_queues[i];
637                 if (txvq == NULL)
638                         continue;
639
640                 txvq->packets = 0;
641                 txvq->bytes = 0;
642                 txvq->errors = 0;
643         }
644
645         for (i = 0; i < dev->data->nb_rx_queues; i++) {
646                 struct virtqueue *rxvq = dev->data->rx_queues[i];
647                 if (rxvq == NULL)
648                         continue;
649
650                 rxvq->packets = 0;
651                 rxvq->bytes = 0;
652                 rxvq->errors = 0;
653         }
654
655         dev->data->rx_mbuf_alloc_failed = 0;
656 }
657
658 static void
659 virtio_set_hwaddr(struct virtio_hw *hw)
660 {
661         vtpci_write_dev_config(hw,
662                         offsetof(struct virtio_net_config, mac),
663                         &hw->mac_addr, ETHER_ADDR_LEN);
664 }
665
666 static void
667 virtio_get_hwaddr(struct virtio_hw *hw)
668 {
669         if (vtpci_with_feature(hw, VIRTIO_NET_F_MAC)) {
670                 vtpci_read_dev_config(hw,
671                         offsetof(struct virtio_net_config, mac),
672                         &hw->mac_addr, ETHER_ADDR_LEN);
673         } else {
674                 eth_random_addr(&hw->mac_addr[0]);
675                 virtio_set_hwaddr(hw);
676         }
677 }
678
679 static void
680 virtio_mac_table_set(struct virtio_hw *hw,
681                      const struct virtio_net_ctrl_mac *uc,
682                      const struct virtio_net_ctrl_mac *mc)
683 {
684         struct virtio_pmd_ctrl ctrl;
685         int err, len[2];
686
687         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
688                 PMD_DRV_LOG(INFO, "host does not support mac table\n");
689                 return;
690         }
691
692         ctrl.hdr.class = VIRTIO_NET_CTRL_MAC;
693         ctrl.hdr.cmd = VIRTIO_NET_CTRL_MAC_TABLE_SET;
694
695         len[0] = uc->entries * ETHER_ADDR_LEN + sizeof(uc->entries);
696         memcpy(ctrl.data, uc, len[0]);
697
698         len[1] = mc->entries * ETHER_ADDR_LEN + sizeof(mc->entries);
699         memcpy(ctrl.data + len[0], mc, len[1]);
700
701         err = virtio_send_command(hw->cvq, &ctrl, len, 2);
702         if (err != 0)
703                 PMD_DRV_LOG(NOTICE, "mac table set failed: %d", err);
704 }
705
706 static void
707 virtio_mac_addr_add(struct rte_eth_dev *dev, struct ether_addr *mac_addr,
708                     uint32_t index, uint32_t vmdq __rte_unused)
709 {
710         struct virtio_hw *hw = dev->data->dev_private;
711         const struct ether_addr *addrs = dev->data->mac_addrs;
712         unsigned int i;
713         struct virtio_net_ctrl_mac *uc, *mc;
714
715         if (index >= VIRTIO_MAX_MAC_ADDRS) {
716                 PMD_DRV_LOG(ERR, "mac address index %u out of range", index);
717                 return;
718         }
719
720         uc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(uc->entries));
721         uc->entries = 0;
722         mc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(mc->entries));
723         mc->entries = 0;
724
725         for (i = 0; i < VIRTIO_MAX_MAC_ADDRS; i++) {
726                 const struct ether_addr *addr
727                         = (i == index) ? mac_addr : addrs + i;
728                 struct virtio_net_ctrl_mac *tbl
729                         = is_multicast_ether_addr(addr) ? mc : uc;
730
731                 memcpy(&tbl->macs[tbl->entries++], addr, ETHER_ADDR_LEN);
732         }
733
734         virtio_mac_table_set(hw, uc, mc);
735 }
736
737 static void
738 virtio_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
739 {
740         struct virtio_hw *hw = dev->data->dev_private;
741         struct ether_addr *addrs = dev->data->mac_addrs;
742         struct virtio_net_ctrl_mac *uc, *mc;
743         unsigned int i;
744
745         if (index >= VIRTIO_MAX_MAC_ADDRS) {
746                 PMD_DRV_LOG(ERR, "mac address index %u out of range", index);
747                 return;
748         }
749
750         uc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(uc->entries));
751         uc->entries = 0;
752         mc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(mc->entries));
753         mc->entries = 0;
754
755         for (i = 0; i < VIRTIO_MAX_MAC_ADDRS; i++) {
756                 struct virtio_net_ctrl_mac *tbl;
757
758                 if (i == index || is_zero_ether_addr(addrs + i))
759                         continue;
760
761                 tbl = is_multicast_ether_addr(addrs + i) ? mc : uc;
762                 memcpy(&tbl->macs[tbl->entries++], addrs + i, ETHER_ADDR_LEN);
763         }
764
765         virtio_mac_table_set(hw, uc, mc);
766 }
767
768 static void
769 virtio_mac_addr_set(struct rte_eth_dev *dev, struct ether_addr *mac_addr)
770 {
771         struct virtio_hw *hw = dev->data->dev_private;
772
773         memcpy(hw->mac_addr, mac_addr, ETHER_ADDR_LEN);
774
775         /* Use atomic update if available */
776         if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
777                 struct virtio_pmd_ctrl ctrl;
778                 int len = ETHER_ADDR_LEN;
779
780                 ctrl.hdr.class = VIRTIO_NET_CTRL_MAC;
781                 ctrl.hdr.cmd = VIRTIO_NET_CTRL_MAC_ADDR_SET;
782
783                 memcpy(ctrl.data, mac_addr, ETHER_ADDR_LEN);
784                 virtio_send_command(hw->cvq, &ctrl, &len, 1);
785         } else if (vtpci_with_feature(hw, VIRTIO_NET_F_MAC))
786                 virtio_set_hwaddr(hw);
787 }
788
789 static int
790 virtio_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
791 {
792         struct virtio_hw *hw = dev->data->dev_private;
793         struct virtio_pmd_ctrl ctrl;
794         int len;
795
796         if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VLAN))
797                 return -ENOTSUP;
798
799         ctrl.hdr.class = VIRTIO_NET_CTRL_VLAN;
800         ctrl.hdr.cmd = on ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL;
801         memcpy(ctrl.data, &vlan_id, sizeof(vlan_id));
802         len = sizeof(vlan_id);
803
804         return virtio_send_command(hw->cvq, &ctrl, &len, 1);
805 }
806
807 static void
808 virtio_negotiate_features(struct virtio_hw *hw)
809 {
810         uint32_t host_features;
811
812         /* Prepare guest_features: feature that driver wants to support */
813         hw->guest_features = VIRTIO_PMD_GUEST_FEATURES;
814         PMD_INIT_LOG(DEBUG, "guest_features before negotiate = %x",
815                 hw->guest_features);
816
817         /* Read device(host) feature bits */
818         host_features = VIRTIO_READ_REG_4(hw, VIRTIO_PCI_HOST_FEATURES);
819         PMD_INIT_LOG(DEBUG, "host_features before negotiate = %x",
820                 host_features);
821
822         /*
823          * Negotiate features: Subset of device feature bits are written back
824          * guest feature bits.
825          */
826         hw->guest_features = vtpci_negotiate_features(hw, host_features);
827         PMD_INIT_LOG(DEBUG, "features after negotiate = %x",
828                 hw->guest_features);
829 }
830
831 #ifdef RTE_EXEC_ENV_LINUXAPP
832 static int
833 parse_sysfs_value(const char *filename, unsigned long *val)
834 {
835         FILE *f;
836         char buf[BUFSIZ];
837         char *end = NULL;
838
839         f = fopen(filename, "r");
840         if (f == NULL) {
841                 PMD_INIT_LOG(ERR, "%s(): cannot open sysfs value %s",
842                              __func__, filename);
843                 return -1;
844         }
845
846         if (fgets(buf, sizeof(buf), f) == NULL) {
847                 PMD_INIT_LOG(ERR, "%s(): cannot read sysfs value %s",
848                              __func__, filename);
849                 fclose(f);
850                 return -1;
851         }
852         *val = strtoul(buf, &end, 0);
853         if ((buf[0] == '\0') || (end == NULL) || (*end != '\n')) {
854                 PMD_INIT_LOG(ERR, "%s(): cannot parse sysfs value %s",
855                              __func__, filename);
856                 fclose(f);
857                 return -1;
858         }
859         fclose(f);
860         return 0;
861 }
862
863 static int get_uio_dev(struct rte_pci_addr *loc, char *buf, unsigned int buflen,
864                         unsigned int *uio_num)
865 {
866         struct dirent *e;
867         DIR *dir;
868         char dirname[PATH_MAX];
869
870         /* depending on kernel version, uio can be located in uio/uioX
871          * or uio:uioX */
872         snprintf(dirname, sizeof(dirname),
873                      SYSFS_PCI_DEVICES "/" PCI_PRI_FMT "/uio",
874                      loc->domain, loc->bus, loc->devid, loc->function);
875         dir = opendir(dirname);
876         if (dir == NULL) {
877                 /* retry with the parent directory */
878                 snprintf(dirname, sizeof(dirname),
879                              SYSFS_PCI_DEVICES "/" PCI_PRI_FMT,
880                              loc->domain, loc->bus, loc->devid, loc->function);
881                 dir = opendir(dirname);
882
883                 if (dir == NULL) {
884                         PMD_INIT_LOG(ERR, "Cannot opendir %s", dirname);
885                         return -1;
886                 }
887         }
888
889         /* take the first file starting with "uio" */
890         while ((e = readdir(dir)) != NULL) {
891                 /* format could be uio%d ...*/
892                 int shortprefix_len = sizeof("uio") - 1;
893                 /* ... or uio:uio%d */
894                 int longprefix_len = sizeof("uio:uio") - 1;
895                 char *endptr;
896
897                 if (strncmp(e->d_name, "uio", 3) != 0)
898                         continue;
899
900                 /* first try uio%d */
901                 errno = 0;
902                 *uio_num = strtoull(e->d_name + shortprefix_len, &endptr, 10);
903                 if (errno == 0 && endptr != (e->d_name + shortprefix_len)) {
904                         snprintf(buf, buflen, "%s/uio%u", dirname, *uio_num);
905                         break;
906                 }
907
908                 /* then try uio:uio%d */
909                 errno = 0;
910                 *uio_num = strtoull(e->d_name + longprefix_len, &endptr, 10);
911                 if (errno == 0 && endptr != (e->d_name + longprefix_len)) {
912                         snprintf(buf, buflen, "%s/uio:uio%u", dirname,
913                                      *uio_num);
914                         break;
915                 }
916         }
917         closedir(dir);
918
919         /* No uio resource found */
920         if (e == NULL) {
921                 PMD_INIT_LOG(ERR, "Could not find uio resource");
922                 return -1;
923         }
924
925         return 0;
926 }
927
928 static int
929 virtio_has_msix(const struct rte_pci_addr *loc)
930 {
931         DIR *d;
932         char dirname[PATH_MAX];
933
934         snprintf(dirname, sizeof(dirname),
935                      SYSFS_PCI_DEVICES "/" PCI_PRI_FMT "/msi_irqs",
936                      loc->domain, loc->bus, loc->devid, loc->function);
937
938         d = opendir(dirname);
939         if (d)
940                 closedir(d);
941
942         return (d != NULL);
943 }
944
945 /* Extract I/O port numbers from sysfs */
946 static int virtio_resource_init_by_uio(struct rte_pci_device *pci_dev)
947 {
948         char dirname[PATH_MAX];
949         char filename[PATH_MAX];
950         unsigned long start, size;
951         unsigned int uio_num;
952
953         if (get_uio_dev(&pci_dev->addr, dirname, sizeof(dirname), &uio_num) < 0)
954                 return -1;
955
956         /* get portio size */
957         snprintf(filename, sizeof(filename),
958                      "%s/portio/port0/size", dirname);
959         if (parse_sysfs_value(filename, &size) < 0) {
960                 PMD_INIT_LOG(ERR, "%s(): cannot parse size",
961                              __func__);
962                 return -1;
963         }
964
965         /* get portio start */
966         snprintf(filename, sizeof(filename),
967                  "%s/portio/port0/start", dirname);
968         if (parse_sysfs_value(filename, &start) < 0) {
969                 PMD_INIT_LOG(ERR, "%s(): cannot parse portio start",
970                              __func__);
971                 return -1;
972         }
973         pci_dev->mem_resource[0].addr = (void *)(uintptr_t)start;
974         pci_dev->mem_resource[0].len =  (uint64_t)size;
975         PMD_INIT_LOG(DEBUG,
976                      "PCI Port IO found start=0x%lx with size=0x%lx",
977                      start, size);
978
979         /* save fd */
980         memset(dirname, 0, sizeof(dirname));
981         snprintf(dirname, sizeof(dirname), "/dev/uio%u", uio_num);
982         pci_dev->intr_handle.fd = open(dirname, O_RDWR);
983         if (pci_dev->intr_handle.fd < 0) {
984                 PMD_INIT_LOG(ERR, "Cannot open %s: %s\n",
985                         dirname, strerror(errno));
986                 return -1;
987         }
988
989         pci_dev->intr_handle.type = RTE_INTR_HANDLE_UIO;
990         pci_dev->driver->drv_flags |= RTE_PCI_DRV_INTR_LSC;
991
992         return 0;
993 }
994
995 /* Extract port I/O numbers from proc/ioports */
996 static int virtio_resource_init_by_ioports(struct rte_pci_device *pci_dev)
997 {
998         uint16_t start, end;
999         int size;
1000         FILE *fp;
1001         char *line = NULL;
1002         char pci_id[16];
1003         int found = 0;
1004         size_t linesz;
1005
1006         snprintf(pci_id, sizeof(pci_id), PCI_PRI_FMT,
1007                  pci_dev->addr.domain,
1008                  pci_dev->addr.bus,
1009                  pci_dev->addr.devid,
1010                  pci_dev->addr.function);
1011
1012         fp = fopen("/proc/ioports", "r");
1013         if (fp == NULL) {
1014                 PMD_INIT_LOG(ERR, "%s(): can't open ioports", __func__);
1015                 return -1;
1016         }
1017
1018         while (getdelim(&line, &linesz, '\n', fp) > 0) {
1019                 char *ptr = line;
1020                 char *left;
1021                 int n;
1022
1023                 n = strcspn(ptr, ":");
1024                 ptr[n] = 0;
1025                 left = &ptr[n+1];
1026
1027                 while (*left && isspace(*left))
1028                         left++;
1029
1030                 if (!strncmp(left, pci_id, strlen(pci_id))) {
1031                         found = 1;
1032
1033                         while (*ptr && isspace(*ptr))
1034                                 ptr++;
1035
1036                         sscanf(ptr, "%04hx-%04hx", &start, &end);
1037                         size = end - start + 1;
1038
1039                         break;
1040                 }
1041         }
1042
1043         free(line);
1044         fclose(fp);
1045
1046         if (!found)
1047                 return -1;
1048
1049         pci_dev->mem_resource[0].addr = (void *)(uintptr_t)(uint32_t)start;
1050         pci_dev->mem_resource[0].len =  (uint64_t)size;
1051         PMD_INIT_LOG(DEBUG,
1052                 "PCI Port IO found start=0x%x with size=0x%x",
1053                 start, size);
1054
1055         /* can't support lsc interrupt without uio */
1056         pci_dev->driver->drv_flags &= ~RTE_PCI_DRV_INTR_LSC;
1057
1058         return 0;
1059 }
1060
1061 /* Extract I/O port numbers from sysfs */
1062 static int virtio_resource_init(struct rte_pci_device *pci_dev)
1063 {
1064         if (virtio_resource_init_by_uio(pci_dev) == 0)
1065                 return 0;
1066         else
1067                 return virtio_resource_init_by_ioports(pci_dev);
1068 }
1069
1070 #else
1071 static int
1072 virtio_has_msix(const struct rte_pci_addr *loc __rte_unused)
1073 {
1074         /* nic_uio does not enable interrupts, return 0 (false). */
1075         return 0;
1076 }
1077
1078 static int virtio_resource_init(struct rte_pci_device *pci_dev __rte_unused)
1079 {
1080         /* no setup required */
1081         return 0;
1082 }
1083 #endif
1084
1085 /*
1086  * Process Virtio Config changed interrupt and call the callback
1087  * if link state changed.
1088  */
1089 static void
1090 virtio_interrupt_handler(__rte_unused struct rte_intr_handle *handle,
1091                          void *param)
1092 {
1093         struct rte_eth_dev *dev = param;
1094         struct virtio_hw *hw = dev->data->dev_private;
1095         uint8_t isr;
1096
1097         /* Read interrupt status which clears interrupt */
1098         isr = vtpci_isr(hw);
1099         PMD_DRV_LOG(INFO, "interrupt status = %#x", isr);
1100
1101         if (rte_intr_enable(&dev->pci_dev->intr_handle) < 0)
1102                 PMD_DRV_LOG(ERR, "interrupt enable failed");
1103
1104         if (isr & VIRTIO_PCI_ISR_CONFIG) {
1105                 if (virtio_dev_link_update(dev, 0) == 0)
1106                         _rte_eth_dev_callback_process(dev,
1107                                                       RTE_ETH_EVENT_INTR_LSC);
1108         }
1109
1110 }
1111
1112 static void
1113 rx_func_get(struct rte_eth_dev *eth_dev)
1114 {
1115         struct virtio_hw *hw = eth_dev->data->dev_private;
1116         if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF))
1117                 eth_dev->rx_pkt_burst = &virtio_recv_mergeable_pkts;
1118         else
1119                 eth_dev->rx_pkt_burst = &virtio_recv_pkts;
1120 }
1121
1122 /*
1123  * This function is based on probe() function in virtio_pci.c
1124  * It returns 0 on success.
1125  */
1126 static int
1127 eth_virtio_dev_init(struct rte_eth_dev *eth_dev)
1128 {
1129         struct virtio_hw *hw = eth_dev->data->dev_private;
1130         struct virtio_net_config *config;
1131         struct virtio_net_config local_config;
1132         uint32_t offset_conf = sizeof(config->mac);
1133         struct rte_pci_device *pci_dev;
1134
1135         RTE_BUILD_BUG_ON(RTE_PKTMBUF_HEADROOM < sizeof(struct virtio_net_hdr));
1136
1137         eth_dev->dev_ops = &virtio_eth_dev_ops;
1138         eth_dev->tx_pkt_burst = &virtio_xmit_pkts;
1139
1140         if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
1141                 rx_func_get(eth_dev);
1142                 return 0;
1143         }
1144
1145         /* Allocate memory for storing MAC addresses */
1146         eth_dev->data->mac_addrs = rte_zmalloc("virtio", ETHER_ADDR_LEN, 0);
1147         if (eth_dev->data->mac_addrs == NULL) {
1148                 PMD_INIT_LOG(ERR,
1149                         "Failed to allocate %d bytes needed to store MAC addresses",
1150                         ETHER_ADDR_LEN);
1151                 return -ENOMEM;
1152         }
1153
1154         pci_dev = eth_dev->pci_dev;
1155         if (virtio_resource_init(pci_dev) < 0)
1156                 return -1;
1157
1158         hw->use_msix = virtio_has_msix(&pci_dev->addr);
1159         hw->io_base = (uint32_t)(uintptr_t)pci_dev->mem_resource[0].addr;
1160
1161         /* Reset the device although not necessary at startup */
1162         vtpci_reset(hw);
1163
1164         /* Tell the host we've noticed this device. */
1165         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_ACK);
1166
1167         /* Tell the host we've known how to drive the device. */
1168         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_DRIVER);
1169         virtio_negotiate_features(hw);
1170
1171         rx_func_get(eth_dev);
1172
1173         /* Setting up rx_header size for the device */
1174         if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF))
1175                 hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr_mrg_rxbuf);
1176         else
1177                 hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr);
1178
1179         /* Copy the permanent MAC address to: virtio_hw */
1180         virtio_get_hwaddr(hw);
1181         ether_addr_copy((struct ether_addr *) hw->mac_addr,
1182                         &eth_dev->data->mac_addrs[0]);
1183         PMD_INIT_LOG(DEBUG,
1184                      "PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X",
1185                      hw->mac_addr[0], hw->mac_addr[1], hw->mac_addr[2],
1186                      hw->mac_addr[3], hw->mac_addr[4], hw->mac_addr[5]);
1187
1188         if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VQ)) {
1189                 config = &local_config;
1190
1191                 if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
1192                         offset_conf += sizeof(config->status);
1193                 } else {
1194                         PMD_INIT_LOG(DEBUG,
1195                                      "VIRTIO_NET_F_STATUS is not supported");
1196                         config->status = 0;
1197                 }
1198
1199                 if (vtpci_with_feature(hw, VIRTIO_NET_F_MQ)) {
1200                         offset_conf += sizeof(config->max_virtqueue_pairs);
1201                 } else {
1202                         PMD_INIT_LOG(DEBUG,
1203                                      "VIRTIO_NET_F_MQ is not supported");
1204                         config->max_virtqueue_pairs = 1;
1205                 }
1206
1207                 vtpci_read_dev_config(hw, 0, (uint8_t *)config, offset_conf);
1208
1209                 hw->max_rx_queues =
1210                         (VIRTIO_MAX_RX_QUEUES < config->max_virtqueue_pairs) ?
1211                         VIRTIO_MAX_RX_QUEUES : config->max_virtqueue_pairs;
1212                 hw->max_tx_queues =
1213                         (VIRTIO_MAX_TX_QUEUES < config->max_virtqueue_pairs) ?
1214                         VIRTIO_MAX_TX_QUEUES : config->max_virtqueue_pairs;
1215
1216                 virtio_dev_cq_queue_setup(eth_dev,
1217                                         config->max_virtqueue_pairs * 2,
1218                                         SOCKET_ID_ANY);
1219
1220                 PMD_INIT_LOG(DEBUG, "config->max_virtqueue_pairs=%d",
1221                                 config->max_virtqueue_pairs);
1222                 PMD_INIT_LOG(DEBUG, "config->status=%d", config->status);
1223                 PMD_INIT_LOG(DEBUG,
1224                                 "PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X",
1225                                 config->mac[0], config->mac[1],
1226                                 config->mac[2], config->mac[3],
1227                                 config->mac[4], config->mac[5]);
1228         } else {
1229                 hw->max_rx_queues = 1;
1230                 hw->max_tx_queues = 1;
1231         }
1232
1233         eth_dev->data->nb_rx_queues = hw->max_rx_queues;
1234         eth_dev->data->nb_tx_queues = hw->max_tx_queues;
1235
1236         PMD_INIT_LOG(DEBUG, "hw->max_rx_queues=%d   hw->max_tx_queues=%d",
1237                         hw->max_rx_queues, hw->max_tx_queues);
1238         PMD_INIT_LOG(DEBUG, "port %d vendorID=0x%x deviceID=0x%x",
1239                         eth_dev->data->port_id, pci_dev->id.vendor_id,
1240                         pci_dev->id.device_id);
1241
1242         /* Setup interrupt callback  */
1243         if (pci_dev->driver->drv_flags & RTE_PCI_DRV_INTR_LSC)
1244                 rte_intr_callback_register(&pci_dev->intr_handle,
1245                                    virtio_interrupt_handler, eth_dev);
1246
1247         virtio_dev_cq_start(eth_dev);
1248
1249         return 0;
1250 }
1251
1252 static struct eth_driver rte_virtio_pmd = {
1253         .pci_drv = {
1254                 .name = "rte_virtio_pmd",
1255                 .id_table = pci_id_virtio_map,
1256         },
1257         .eth_dev_init = eth_virtio_dev_init,
1258         .dev_private_size = sizeof(struct virtio_hw),
1259 };
1260
1261 /*
1262  * Driver initialization routine.
1263  * Invoked once at EAL init time.
1264  * Register itself as the [Poll Mode] Driver of PCI virtio devices.
1265  * Returns 0 on success.
1266  */
1267 static int
1268 rte_virtio_pmd_init(const char *name __rte_unused,
1269                     const char *param __rte_unused)
1270 {
1271         if (rte_eal_iopl_init() != 0) {
1272                 PMD_INIT_LOG(ERR, "IOPL call failed - cannot use virtio PMD");
1273                 return -1;
1274         }
1275
1276         rte_eth_driver_register(&rte_virtio_pmd);
1277         return 0;
1278 }
1279
1280 /*
1281  * Only 1 queue is supported, no queue release related operation
1282  */
1283 static void
1284 virtio_dev_rx_queue_release(__rte_unused void *rxq)
1285 {
1286 }
1287
1288 static void
1289 virtio_dev_tx_queue_release(__rte_unused void *txq)
1290 {
1291 }
1292
1293 /*
1294  * Configure virtio device
1295  * It returns 0 on success.
1296  */
1297 static int
1298 virtio_dev_configure(struct rte_eth_dev *dev)
1299 {
1300         const struct rte_eth_rxmode *rxmode = &dev->data->dev_conf.rxmode;
1301         struct virtio_hw *hw = dev->data->dev_private;
1302         struct rte_pci_device *pci_dev = dev->pci_dev;
1303
1304         PMD_INIT_LOG(DEBUG, "configure");
1305
1306         if (rxmode->hw_ip_checksum) {
1307                 PMD_DRV_LOG(ERR, "HW IP checksum not supported");
1308                 return (-EINVAL);
1309         }
1310
1311         hw->vlan_strip = rxmode->hw_vlan_strip;
1312
1313         if (rxmode->hw_vlan_filter
1314             && !vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VLAN)) {
1315                 PMD_DRV_LOG(NOTICE,
1316                             "vlan filtering not available on this host");
1317                 return -ENOTSUP;
1318         }
1319
1320         if (pci_dev->driver->drv_flags & RTE_PCI_DRV_INTR_LSC)
1321                 if (vtpci_irq_config(hw, 0) == VIRTIO_MSI_NO_VECTOR) {
1322                         PMD_DRV_LOG(ERR, "failed to set config vector");
1323                         return -EBUSY;
1324                 }
1325
1326         return 0;
1327 }
1328
1329
1330 static int
1331 virtio_dev_start(struct rte_eth_dev *dev)
1332 {
1333         uint16_t nb_queues, i;
1334         struct virtio_hw *hw = dev->data->dev_private;
1335         struct rte_pci_device *pci_dev = dev->pci_dev;
1336
1337         /* check if lsc interrupt feature is enabled */
1338         if ((dev->data->dev_conf.intr_conf.lsc) &&
1339                 (pci_dev->driver->drv_flags & RTE_PCI_DRV_INTR_LSC)) {
1340                 if (!vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
1341                         PMD_DRV_LOG(ERR, "link status not supported by host");
1342                         return -ENOTSUP;
1343                 }
1344
1345                 if (rte_intr_enable(&dev->pci_dev->intr_handle) < 0) {
1346                         PMD_DRV_LOG(ERR, "interrupt enable failed");
1347                         return -EIO;
1348                 }
1349         }
1350
1351         /* Initialize Link state */
1352         virtio_dev_link_update(dev, 0);
1353
1354         /* On restart after stop do not touch queues */
1355         if (hw->started)
1356                 return 0;
1357
1358         /* Do final configuration before rx/tx engine starts */
1359         virtio_dev_rxtx_start(dev);
1360         vtpci_reinit_complete(hw);
1361
1362         hw->started = 1;
1363
1364         /*Notify the backend
1365          *Otherwise the tap backend might already stop its queue due to fullness.
1366          *vhost backend will have no chance to be waked up
1367          */
1368         nb_queues = dev->data->nb_rx_queues;
1369         if (nb_queues > 1) {
1370                 if (virtio_set_multiple_queues(dev, nb_queues) != 0)
1371                         return -EINVAL;
1372         }
1373
1374         PMD_INIT_LOG(DEBUG, "nb_queues=%d", nb_queues);
1375
1376         for (i = 0; i < nb_queues; i++)
1377                 virtqueue_notify(dev->data->rx_queues[i]);
1378
1379         PMD_INIT_LOG(DEBUG, "Notified backend at initialization");
1380
1381         for (i = 0; i < dev->data->nb_rx_queues; i++)
1382                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->rx_queues[i]);
1383
1384         for (i = 0; i < dev->data->nb_tx_queues; i++)
1385                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->tx_queues[i]);
1386
1387         return 0;
1388 }
1389
1390 static void virtio_dev_free_mbufs(struct rte_eth_dev *dev)
1391 {
1392         struct rte_mbuf *buf;
1393         int i, mbuf_num = 0;
1394
1395         for (i = 0; i < dev->data->nb_rx_queues; i++) {
1396                 PMD_INIT_LOG(DEBUG,
1397                              "Before freeing rxq[%d] used and unused buf", i);
1398                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->rx_queues[i]);
1399
1400                 while ((buf = (struct rte_mbuf *)virtqueue_detatch_unused(
1401                                         dev->data->rx_queues[i])) != NULL) {
1402                         rte_pktmbuf_free(buf);
1403                         mbuf_num++;
1404                 }
1405
1406                 PMD_INIT_LOG(DEBUG, "free %d mbufs", mbuf_num);
1407                 PMD_INIT_LOG(DEBUG,
1408                              "After freeing rxq[%d] used and unused buf", i);
1409                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->rx_queues[i]);
1410         }
1411
1412         for (i = 0; i < dev->data->nb_tx_queues; i++) {
1413                 PMD_INIT_LOG(DEBUG,
1414                              "Before freeing txq[%d] used and unused bufs",
1415                              i);
1416                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->tx_queues[i]);
1417
1418                 mbuf_num = 0;
1419                 while ((buf = (struct rte_mbuf *)virtqueue_detatch_unused(
1420                                         dev->data->tx_queues[i])) != NULL) {
1421                         rte_pktmbuf_free(buf);
1422
1423                         mbuf_num++;
1424                 }
1425
1426                 PMD_INIT_LOG(DEBUG, "free %d mbufs", mbuf_num);
1427                 PMD_INIT_LOG(DEBUG,
1428                              "After freeing txq[%d] used and unused buf", i);
1429                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->tx_queues[i]);
1430         }
1431 }
1432
1433 /*
1434  * Stop device: disable interrupt and mark link down
1435  */
1436 static void
1437 virtio_dev_stop(struct rte_eth_dev *dev)
1438 {
1439         struct rte_eth_link link;
1440
1441         PMD_INIT_LOG(DEBUG, "stop");
1442
1443         if (dev->data->dev_conf.intr_conf.lsc)
1444                 rte_intr_disable(&dev->pci_dev->intr_handle);
1445
1446         memset(&link, 0, sizeof(link));
1447         virtio_dev_atomic_write_link_status(dev, &link);
1448 }
1449
1450 static int
1451 virtio_dev_link_update(struct rte_eth_dev *dev, __rte_unused int wait_to_complete)
1452 {
1453         struct rte_eth_link link, old;
1454         uint16_t status;
1455         struct virtio_hw *hw = dev->data->dev_private;
1456         memset(&link, 0, sizeof(link));
1457         virtio_dev_atomic_read_link_status(dev, &link);
1458         old = link;
1459         link.link_duplex = FULL_DUPLEX;
1460         link.link_speed  = SPEED_10G;
1461
1462         if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
1463                 PMD_INIT_LOG(DEBUG, "Get link status from hw");
1464                 vtpci_read_dev_config(hw,
1465                                 offsetof(struct virtio_net_config, status),
1466                                 &status, sizeof(status));
1467                 if ((status & VIRTIO_NET_S_LINK_UP) == 0) {
1468                         link.link_status = 0;
1469                         PMD_INIT_LOG(DEBUG, "Port %d is down",
1470                                      dev->data->port_id);
1471                 } else {
1472                         link.link_status = 1;
1473                         PMD_INIT_LOG(DEBUG, "Port %d is up",
1474                                      dev->data->port_id);
1475                 }
1476         } else {
1477                 link.link_status = 1;   /* Link up */
1478         }
1479         virtio_dev_atomic_write_link_status(dev, &link);
1480
1481         return (old.link_status == link.link_status) ? -1 : 0;
1482 }
1483
1484 static void
1485 virtio_dev_info_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *dev_info)
1486 {
1487         struct virtio_hw *hw = dev->data->dev_private;
1488
1489         dev_info->driver_name = dev->driver->pci_drv.name;
1490         dev_info->max_rx_queues = (uint16_t)hw->max_rx_queues;
1491         dev_info->max_tx_queues = (uint16_t)hw->max_tx_queues;
1492         dev_info->min_rx_bufsize = VIRTIO_MIN_RX_BUFSIZE;
1493         dev_info->max_rx_pktlen = VIRTIO_MAX_RX_PKTLEN;
1494         dev_info->max_mac_addrs = VIRTIO_MAX_MAC_ADDRS;
1495         dev_info->default_txconf = (struct rte_eth_txconf) {
1496                 .txq_flags = ETH_TXQ_FLAGS_NOOFFLOADS
1497         };
1498 }
1499
1500 /*
1501  * It enables testpmd to collect per queue stats.
1502  */
1503 static int
1504 virtio_dev_queue_stats_mapping_set(__rte_unused struct rte_eth_dev *eth_dev,
1505 __rte_unused uint16_t queue_id, __rte_unused uint8_t stat_idx,
1506 __rte_unused uint8_t is_rx)
1507 {
1508         return 0;
1509 }
1510
1511 static struct rte_driver rte_virtio_driver = {
1512         .type = PMD_PDEV,
1513         .init = rte_virtio_pmd_init,
1514 };
1515
1516 PMD_REGISTER_DRIVER(rte_virtio_driver);