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