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