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