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