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