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