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