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