virtio: simplify the hardware structure
[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_info_get(struct rte_eth_dev *dev,
70                                 struct rte_eth_dev_info *dev_info);
71 static int virtio_dev_link_update(struct rte_eth_dev *dev,
72         __rte_unused int wait_to_complete);
73
74 static void virtio_set_hwaddr(struct virtio_hw *hw);
75 static void virtio_get_hwaddr(struct virtio_hw *hw);
76
77 static void virtio_dev_rx_queue_release(__rte_unused void *rxq);
78 static void virtio_dev_tx_queue_release(__rte_unused void *txq);
79
80 static void virtio_dev_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats);
81 static void virtio_dev_stats_reset(struct rte_eth_dev *dev);
82 static void virtio_dev_free_mbufs(struct rte_eth_dev *dev);
83
84 static int virtio_dev_queue_stats_mapping_set(
85         __rte_unused struct rte_eth_dev *eth_dev,
86         __rte_unused uint16_t queue_id,
87         __rte_unused uint8_t stat_idx,
88         __rte_unused uint8_t is_rx);
89
90 /*
91  * The set of PCI devices this driver supports
92  */
93 static struct rte_pci_id pci_id_virtio_map[] = {
94
95 #define RTE_PCI_DEV_ID_DECL_VIRTIO(vend, dev) {RTE_PCI_DEVICE(vend, dev)},
96 #include "rte_pci_dev_ids.h"
97
98 { .vendor_id = 0, /* sentinel */ },
99 };
100
101 static int
102 virtio_send_command(struct virtqueue *vq, struct virtio_pmd_ctrl *ctrl,
103                 int *dlen, int pkt_num)
104 {
105         uint32_t head = vq->vq_desc_head_idx, i;
106         int k, sum = 0;
107         virtio_net_ctrl_ack status = ~0;
108         struct virtio_pmd_ctrl result;
109
110         ctrl->status = status;
111
112         if (!vq->hw->cvq) {
113                 PMD_INIT_LOG(ERR,
114                              "%s(): Control queue is not supported.",
115                              __func__);
116                 return -1;
117         }
118
119         PMD_INIT_LOG(DEBUG, "vq->vq_desc_head_idx = %d, status = %d, "
120                 "vq->hw->cvq = %p vq = %p",
121                 vq->vq_desc_head_idx, status, vq->hw->cvq, vq);
122
123         if ((vq->vq_free_cnt < ((uint32_t)pkt_num + 2)) || (pkt_num < 1))
124                 return -1;
125
126         memcpy(vq->virtio_net_hdr_mz->addr, ctrl,
127                 sizeof(struct virtio_pmd_ctrl));
128
129         /*
130          * Format is enforced in qemu code:
131          * One TX packet for header;
132          * At least one TX packet per argument;
133          * One RX packet for ACK.
134          */
135         vq->vq_ring.desc[head].flags = VRING_DESC_F_NEXT;
136         vq->vq_ring.desc[head].addr = vq->virtio_net_hdr_mz->phys_addr;
137         vq->vq_ring.desc[head].len = sizeof(struct virtio_net_ctrl_hdr);
138         vq->vq_free_cnt--;
139         i = vq->vq_ring.desc[head].next;
140
141         for (k = 0; k < pkt_num; k++) {
142                 vq->vq_ring.desc[i].flags = VRING_DESC_F_NEXT;
143                 vq->vq_ring.desc[i].addr = vq->virtio_net_hdr_mz->phys_addr
144                         + sizeof(struct virtio_net_ctrl_hdr)
145                         + sizeof(ctrl->status) + sizeof(uint8_t)*sum;
146                 vq->vq_ring.desc[i].len = dlen[k];
147                 sum += dlen[k];
148                 vq->vq_free_cnt--;
149                 i = vq->vq_ring.desc[i].next;
150         }
151
152         vq->vq_ring.desc[i].flags = VRING_DESC_F_WRITE;
153         vq->vq_ring.desc[i].addr = vq->virtio_net_hdr_mz->phys_addr
154                         + sizeof(struct virtio_net_ctrl_hdr);
155         vq->vq_ring.desc[i].len = sizeof(ctrl->status);
156         vq->vq_free_cnt--;
157
158         vq->vq_desc_head_idx = vq->vq_ring.desc[i].next;
159
160         vq_update_avail_ring(vq, head);
161         vq_update_avail_idx(vq);
162
163         PMD_INIT_LOG(DEBUG, "vq->vq_queue_index = %d", vq->vq_queue_index);
164
165         virtqueue_notify(vq);
166
167         while (vq->vq_used_cons_idx == vq->vq_ring.used->idx)
168                 usleep(100);
169
170         while (vq->vq_used_cons_idx != vq->vq_ring.used->idx) {
171                 uint32_t idx, desc_idx, used_idx;
172                 struct vring_used_elem *uep;
173
174                 rmb();
175
176                 used_idx = (uint32_t)(vq->vq_used_cons_idx
177                                 & (vq->vq_nentries - 1));
178                 uep = &vq->vq_ring.used->ring[used_idx];
179                 idx = (uint32_t) uep->id;
180                 desc_idx = idx;
181
182                 while (vq->vq_ring.desc[desc_idx].flags & VRING_DESC_F_NEXT) {
183                         desc_idx = vq->vq_ring.desc[desc_idx].next;
184                         vq->vq_free_cnt++;
185                 }
186
187                 vq->vq_ring.desc[desc_idx].next = vq->vq_desc_head_idx;
188                 vq->vq_desc_head_idx = idx;
189
190                 vq->vq_used_cons_idx++;
191                 vq->vq_free_cnt++;
192         }
193
194         PMD_INIT_LOG(DEBUG, "vq->vq_free_cnt=%d\nvq->vq_desc_head_idx=%d",
195                         vq->vq_free_cnt, vq->vq_desc_head_idx);
196
197         memcpy(&result, vq->virtio_net_hdr_mz->addr,
198                         sizeof(struct virtio_pmd_ctrl));
199
200         return result.status;
201 }
202
203 static int
204 virtio_set_multiple_queues(struct rte_eth_dev *dev, uint16_t nb_queues)
205 {
206         struct virtio_hw *hw
207                 = VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
208         struct virtio_pmd_ctrl ctrl;
209         int dlen[1];
210         int ret;
211
212         ctrl.hdr.class = VIRTIO_NET_CTRL_MQ;
213         ctrl.hdr.cmd = VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET;
214         memcpy(ctrl.data, &nb_queues, sizeof(uint16_t));
215
216         dlen[0] = sizeof(uint16_t);
217
218         ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
219
220         if (ret) {
221                 PMD_INIT_LOG(ERR, "Multiqueue configured but send command "
222                           "failed, this is too late now...");
223                 return -EINVAL;
224         }
225
226         return 0;
227 }
228
229 int virtio_dev_queue_setup(struct rte_eth_dev *dev,
230                         int queue_type,
231                         uint16_t queue_idx,
232                         uint8_t  vtpci_queue_idx,
233                         uint16_t nb_desc,
234                         unsigned int socket_id,
235                         struct virtqueue **pvq)
236 {
237         char vq_name[VIRTQUEUE_MAX_NAME_SZ];
238         const struct rte_memzone *mz;
239         uint16_t vq_size;
240         int size;
241         struct virtio_hw *hw =
242                 VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
243         struct virtqueue  *vq = NULL;
244
245         /* Write the virtqueue index to the Queue Select Field */
246         VIRTIO_WRITE_REG_2(hw, VIRTIO_PCI_QUEUE_SEL, vtpci_queue_idx);
247         PMD_INIT_LOG(DEBUG, "selecting queue: %d", vtpci_queue_idx);
248
249         /*
250          * Read the virtqueue size from the Queue Size field
251          * Always power of 2 and if 0 virtqueue does not exist
252          */
253         vq_size = VIRTIO_READ_REG_2(hw, VIRTIO_PCI_QUEUE_NUM);
254         PMD_INIT_LOG(DEBUG, "vq_size: %d nb_desc:%d", vq_size, nb_desc);
255         if (nb_desc == 0)
256                 nb_desc = vq_size;
257         if (vq_size == 0) {
258                 PMD_INIT_LOG(ERR, "%s: virtqueue does not exist", __func__);
259                 return -EINVAL;
260         } else if (!rte_is_power_of_2(vq_size)) {
261                 PMD_INIT_LOG(ERR, "%s: virtqueue size is not powerof 2", __func__);
262                 return -EINVAL;
263         } else if (nb_desc != vq_size) {
264                 PMD_INIT_LOG(ERR, "Warning: nb_desc(%d) is not equal to vq size (%d), fall to vq size",
265                         nb_desc, vq_size);
266                 nb_desc = vq_size;
267         }
268
269         if (queue_type == VTNET_RQ) {
270                 snprintf(vq_name, sizeof(vq_name), "port%d_rvq%d",
271                         dev->data->port_id, queue_idx);
272                 vq = rte_zmalloc(vq_name, sizeof(struct virtqueue) +
273                         vq_size * sizeof(struct vq_desc_extra), CACHE_LINE_SIZE);
274         } else if (queue_type == VTNET_TQ) {
275                 snprintf(vq_name, sizeof(vq_name), "port%d_tvq%d",
276                         dev->data->port_id, queue_idx);
277                 vq = rte_zmalloc(vq_name, sizeof(struct virtqueue) +
278                         vq_size * sizeof(struct vq_desc_extra), CACHE_LINE_SIZE);
279         } else if (queue_type == VTNET_CQ) {
280                 snprintf(vq_name, sizeof(vq_name), "port%d_cvq",
281                         dev->data->port_id);
282                 vq = rte_zmalloc(vq_name, sizeof(struct virtqueue) +
283                         vq_size * sizeof(struct vq_desc_extra),
284                         CACHE_LINE_SIZE);
285         }
286         if (vq == NULL) {
287                 PMD_INIT_LOG(ERR, "%s: Can not allocate virtqueue", __func__);
288                 return (-ENOMEM);
289         }
290
291         vq->hw = hw;
292         vq->port_id = dev->data->port_id;
293         vq->queue_id = queue_idx;
294         vq->vq_queue_index = vtpci_queue_idx;
295         vq->vq_alignment = VIRTIO_PCI_VRING_ALIGN;
296         vq->vq_nentries = vq_size;
297         vq->vq_free_cnt = vq_size;
298
299         /*
300          * Reserve a memzone for vring elements
301          */
302         size = vring_size(vq_size, VIRTIO_PCI_VRING_ALIGN);
303         vq->vq_ring_size = RTE_ALIGN_CEIL(size, VIRTIO_PCI_VRING_ALIGN);
304         PMD_INIT_LOG(DEBUG, "vring_size: %d, rounded_vring_size: %d", size, vq->vq_ring_size);
305
306         mz = rte_memzone_reserve_aligned(vq_name, vq->vq_ring_size,
307                 socket_id, 0, VIRTIO_PCI_VRING_ALIGN);
308         if (mz == NULL) {
309                 rte_free(vq);
310                 return -ENOMEM;
311         }
312
313         /*
314          * Virtio PCI device VIRTIO_PCI_QUEUE_PF register is 32bit,
315          * and only accepts 32 bit page frame number.
316          * Check if the allocated physical memory exceeds 16TB.
317          */
318         if ((mz->phys_addr + vq->vq_ring_size - 1) >> (VIRTIO_PCI_QUEUE_ADDR_SHIFT + 32)) {
319                 PMD_INIT_LOG(ERR, "vring address shouldn't be above 16TB!");
320                 rte_free(vq);
321                 return -ENOMEM;
322         }
323
324         memset(mz->addr, 0, sizeof(mz->len));
325         vq->mz = mz;
326         vq->vq_ring_mem = mz->phys_addr;
327         vq->vq_ring_virt_mem = mz->addr;
328         PMD_INIT_LOG(DEBUG, "vq->vq_ring_mem:      0x%"PRIx64, (uint64_t)mz->phys_addr);
329         PMD_INIT_LOG(DEBUG, "vq->vq_ring_virt_mem: 0x%"PRIx64, (uint64_t)mz->addr);
330         vq->virtio_net_hdr_mz  = NULL;
331         vq->virtio_net_hdr_mem = 0;
332
333         if (queue_type == VTNET_TQ) {
334                 /*
335                  * For each xmit packet, allocate a virtio_net_hdr
336                  */
337                 snprintf(vq_name, sizeof(vq_name), "port%d_tvq%d_hdrzone",
338                         dev->data->port_id, queue_idx);
339                 vq->virtio_net_hdr_mz = rte_memzone_reserve_aligned(vq_name,
340                         vq_size * sizeof(struct virtio_net_hdr),
341                         socket_id, 0, CACHE_LINE_SIZE);
342                 if (vq->virtio_net_hdr_mz == NULL) {
343                         rte_free(vq);
344                         return -ENOMEM;
345                 }
346                 vq->virtio_net_hdr_mem =
347                         vq->virtio_net_hdr_mz->phys_addr;
348                 memset(vq->virtio_net_hdr_mz->addr, 0,
349                         vq_size * sizeof(struct virtio_net_hdr));
350         } else if (queue_type == VTNET_CQ) {
351                 /* Allocate a page for control vq command, data and status */
352                 snprintf(vq_name, sizeof(vq_name), "port%d_cvq_hdrzone",
353                         dev->data->port_id);
354                 vq->virtio_net_hdr_mz = rte_memzone_reserve_aligned(vq_name,
355                         PAGE_SIZE, socket_id, 0, CACHE_LINE_SIZE);
356                 if (vq->virtio_net_hdr_mz == NULL) {
357                         rte_free(vq);
358                         return -ENOMEM;
359                 }
360                 vq->virtio_net_hdr_mem =
361                         vq->virtio_net_hdr_mz->phys_addr;
362                 memset(vq->virtio_net_hdr_mz->addr, 0, PAGE_SIZE);
363         }
364
365         /*
366          * Set guest physical address of the virtqueue
367          * in VIRTIO_PCI_QUEUE_PFN config register of device
368          */
369         VIRTIO_WRITE_REG_4(hw, VIRTIO_PCI_QUEUE_PFN,
370                         mz->phys_addr >> VIRTIO_PCI_QUEUE_ADDR_SHIFT);
371         *pvq = vq;
372         return 0;
373 }
374
375 static int
376 virtio_dev_cq_queue_setup(struct rte_eth_dev *dev, uint16_t vtpci_queue_idx,
377                 uint32_t socket_id)
378 {
379         struct virtqueue *vq;
380         uint16_t nb_desc = 0;
381         int ret;
382         struct virtio_hw *hw =
383                 VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
384
385         PMD_INIT_FUNC_TRACE();
386         ret = virtio_dev_queue_setup(dev, VTNET_CQ, VTNET_SQ_CQ_QUEUE_IDX,
387                         vtpci_queue_idx, nb_desc, socket_id, &vq);
388
389         if (ret < 0) {
390                 PMD_INIT_LOG(ERR, "control vq initialization failed");
391                 return ret;
392         }
393
394         hw->cvq = vq;
395         return 0;
396 }
397
398 static void
399 virtio_dev_close(struct rte_eth_dev *dev)
400 {
401         PMD_INIT_LOG(DEBUG, "virtio_dev_close");
402
403         virtio_dev_stop(dev);
404 }
405
406 /*
407  * dev_ops for virtio, bare necessities for basic operation
408  */
409 static struct eth_dev_ops virtio_eth_dev_ops = {
410         .dev_configure           = virtio_dev_configure,
411         .dev_start               = virtio_dev_start,
412         .dev_stop                = virtio_dev_stop,
413         .dev_close               = virtio_dev_close,
414
415         .dev_infos_get           = virtio_dev_info_get,
416         .stats_get               = virtio_dev_stats_get,
417         .stats_reset             = virtio_dev_stats_reset,
418         .link_update             = virtio_dev_link_update,
419         .mac_addr_add            = NULL,
420         .mac_addr_remove         = NULL,
421         .rx_queue_setup          = virtio_dev_rx_queue_setup,
422         /* meaningfull only to multiple queue */
423         .rx_queue_release        = virtio_dev_rx_queue_release,
424         .tx_queue_setup          = virtio_dev_tx_queue_setup,
425         /* meaningfull only to multiple queue */
426         .tx_queue_release        = virtio_dev_tx_queue_release,
427         /* collect stats per queue */
428         .queue_stats_mapping_set = virtio_dev_queue_stats_mapping_set,
429 };
430
431 static inline int
432 virtio_dev_atomic_read_link_status(struct rte_eth_dev *dev,
433                                 struct rte_eth_link *link)
434 {
435         struct rte_eth_link *dst = link;
436         struct rte_eth_link *src = &(dev->data->dev_link);
437
438         if (rte_atomic64_cmpset((uint64_t *)dst, *(uint64_t *)dst,
439                         *(uint64_t *)src) == 0)
440                 return -1;
441
442         return 0;
443 }
444
445 /**
446  * Atomically writes the link status information into global
447  * structure rte_eth_dev.
448  *
449  * @param dev
450  *   - Pointer to the structure rte_eth_dev to read from.
451  *   - Pointer to the buffer to be saved with the link status.
452  *
453  * @return
454  *   - On success, zero.
455  *   - On failure, negative value.
456  */
457 static inline int
458 virtio_dev_atomic_write_link_status(struct rte_eth_dev *dev,
459                 struct rte_eth_link *link)
460 {
461         struct rte_eth_link *dst = &(dev->data->dev_link);
462         struct rte_eth_link *src = link;
463
464         if (rte_atomic64_cmpset((uint64_t *)dst, *(uint64_t *)dst,
465                                         *(uint64_t *)src) == 0)
466                 return -1;
467
468         return 0;
469 }
470
471 static void
472 virtio_dev_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
473 {
474         unsigned i;
475
476         for (i = 0; i < dev->data->nb_tx_queues; i++) {
477                 const struct virtqueue *txvq = dev->data->tx_queues[i];
478                 if (txvq == NULL)
479                         continue;
480
481                 stats->opackets += txvq->packets;
482                 stats->obytes += txvq->bytes;
483                 stats->oerrors += txvq->errors;
484
485                 if (i < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
486                         stats->q_opackets[i] = txvq->packets;
487                         stats->q_obytes[i] = txvq->bytes;
488                 }
489         }
490
491         for (i = 0; i < dev->data->nb_rx_queues; i++) {
492                 const struct virtqueue *rxvq = dev->data->rx_queues[i];
493                 if (rxvq == NULL)
494                         continue;
495
496                 stats->ipackets += rxvq->packets;
497                 stats->ibytes += rxvq->bytes;
498                 stats->ierrors += rxvq->errors;
499
500                 if (i < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
501                         stats->q_ipackets[i] = rxvq->packets;
502                         stats->q_ibytes[i] = rxvq->bytes;
503                 }
504         }
505
506         stats->rx_nombuf = dev->data->rx_mbuf_alloc_failed;
507 }
508
509 static void
510 virtio_dev_stats_reset(struct rte_eth_dev *dev)
511 {
512         unsigned int i;
513
514         for (i = 0; i < dev->data->nb_tx_queues; i++) {
515                 struct virtqueue *txvq = dev->data->tx_queues[i];
516                 if (txvq == NULL)
517                         continue;
518
519                 txvq->packets = 0;
520                 txvq->bytes = 0;
521                 txvq->errors = 0;
522         }
523
524         for (i = 0; i < dev->data->nb_rx_queues; i++) {
525                 struct virtqueue *rxvq = dev->data->rx_queues[i];
526                 if (rxvq == NULL)
527                         continue;
528
529                 rxvq->packets = 0;
530                 rxvq->bytes = 0;
531                 rxvq->errors = 0;
532         }
533
534         dev->data->rx_mbuf_alloc_failed = 0;
535 }
536
537 static void
538 virtio_set_hwaddr(struct virtio_hw *hw)
539 {
540         vtpci_write_dev_config(hw,
541                         offsetof(struct virtio_net_config, mac),
542                         &hw->mac_addr, ETHER_ADDR_LEN);
543 }
544
545 static void
546 virtio_get_hwaddr(struct virtio_hw *hw)
547 {
548         if (vtpci_with_feature(hw, VIRTIO_NET_F_MAC)) {
549                 vtpci_read_dev_config(hw,
550                         offsetof(struct virtio_net_config, mac),
551                         &hw->mac_addr, ETHER_ADDR_LEN);
552         } else {
553                 eth_random_addr(&hw->mac_addr[0]);
554                 virtio_set_hwaddr(hw);
555         }
556 }
557
558
559 static void
560 virtio_negotiate_features(struct virtio_hw *hw)
561 {
562         uint32_t host_features, mask;
563
564         mask = VIRTIO_NET_F_CTRL_RX | VIRTIO_NET_F_CTRL_VLAN;
565         mask |= VIRTIO_NET_F_CSUM | VIRTIO_NET_F_GUEST_CSUM;
566
567         /* TSO and LRO are only available when their corresponding
568          * checksum offload feature is also negotiated.
569          */
570         mask |= VIRTIO_NET_F_HOST_TSO4 | VIRTIO_NET_F_HOST_TSO6 | VIRTIO_NET_F_HOST_ECN;
571         mask |= VIRTIO_NET_F_GUEST_TSO4 | VIRTIO_NET_F_GUEST_TSO6 | VIRTIO_NET_F_GUEST_ECN;
572         mask |= VTNET_LRO_FEATURES;
573
574         /* rx_mbuf should not be in multiple merged segments */
575         mask |= VIRTIO_NET_F_MRG_RXBUF;
576
577         /* not negotiating INDIRECT descriptor table support */
578         mask |= VIRTIO_RING_F_INDIRECT_DESC;
579
580         /* Prepare guest_features: feature that driver wants to support */
581         hw->guest_features = VTNET_FEATURES & ~mask;
582         PMD_INIT_LOG(DEBUG, "guest_features before negotiate = %x",
583                 guest_features);
584
585         /* Read device(host) feature bits */
586         host_features = VIRTIO_READ_REG_4(hw, VIRTIO_PCI_HOST_FEATURES);
587         PMD_INIT_LOG(DEBUG, "host_features before negotiate = %x",
588                 host_features);
589
590         /*
591          * Negotiate features: Subset of device feature bits are written back
592          * guest feature bits.
593          */
594         hw->guest_features = vtpci_negotiate_features(hw, host_features);
595         PMD_INIT_LOG(DEBUG, "features after negotiate = %x",
596                 hw->guest_features);
597 }
598
599 #ifdef RTE_EXEC_ENV_LINUXAPP
600 static int
601 parse_sysfs_value(const char *filename, unsigned long *val)
602 {
603         FILE *f;
604         char buf[BUFSIZ];
605         char *end = NULL;
606
607         f = fopen(filename, "r");
608         if (f == NULL) {
609                 PMD_INIT_LOG(ERR, "%s(): cannot open sysfs value %s",
610                              __func__, filename);
611                 return -1;
612         }
613
614         if (fgets(buf, sizeof(buf), f) == NULL) {
615                 PMD_INIT_LOG(ERR, "%s(): cannot read sysfs value %s",
616                              __func__, filename);
617                 fclose(f);
618                 return -1;
619         }
620         *val = strtoul(buf, &end, 0);
621         if ((buf[0] == '\0') || (end == NULL) || (*end != '\n')) {
622                 PMD_INIT_LOG(ERR, "%s(): cannot parse sysfs value %s",
623                              __func__, filename);
624                 fclose(f);
625                 return -1;
626         }
627         fclose(f);
628         return 0;
629 }
630
631 static int get_uio_dev(struct rte_pci_addr *loc, char *buf, unsigned int buflen)
632 {
633         unsigned int uio_num;
634         struct dirent *e;
635         DIR *dir;
636         char dirname[PATH_MAX];
637
638         /* depending on kernel version, uio can be located in uio/uioX
639          * or uio:uioX */
640         snprintf(dirname, sizeof(dirname),
641                      SYSFS_PCI_DEVICES "/" PCI_PRI_FMT "/uio",
642                      loc->domain, loc->bus, loc->devid, loc->function);
643         dir = opendir(dirname);
644         if (dir == NULL) {
645                 /* retry with the parent directory */
646                 snprintf(dirname, sizeof(dirname),
647                              SYSFS_PCI_DEVICES "/" PCI_PRI_FMT,
648                              loc->domain, loc->bus, loc->devid, loc->function);
649                 dir = opendir(dirname);
650
651                 if (dir == NULL) {
652                         PMD_INIT_LOG(ERR, "Cannot opendir %s", dirname);
653                         return -1;
654                 }
655         }
656
657         /* take the first file starting with "uio" */
658         while ((e = readdir(dir)) != NULL) {
659                 /* format could be uio%d ...*/
660                 int shortprefix_len = sizeof("uio") - 1;
661                 /* ... or uio:uio%d */
662                 int longprefix_len = sizeof("uio:uio") - 1;
663                 char *endptr;
664
665                 if (strncmp(e->d_name, "uio", 3) != 0)
666                         continue;
667
668                 /* first try uio%d */
669                 errno = 0;
670                 uio_num = strtoull(e->d_name + shortprefix_len, &endptr, 10);
671                 if (errno == 0 && endptr != (e->d_name + shortprefix_len)) {
672                         snprintf(buf, buflen, "%s/uio%u", dirname, uio_num);
673                         break;
674                 }
675
676                 /* then try uio:uio%d */
677                 errno = 0;
678                 uio_num = strtoull(e->d_name + longprefix_len, &endptr, 10);
679                 if (errno == 0 && endptr != (e->d_name + longprefix_len)) {
680                         snprintf(buf, buflen, "%s/uio:uio%u", dirname,
681                                      uio_num);
682                         break;
683                 }
684         }
685         closedir(dir);
686
687         /* No uio resource found */
688         if (e == NULL) {
689                 PMD_INIT_LOG(ERR, "Could not find uio resource");
690                 return -1;
691         }
692
693         return 0;
694 }
695
696 static int
697 virtio_has_msix(const struct rte_pci_addr *loc)
698 {
699         DIR *d;
700         char dirname[PATH_MAX];
701
702         snprintf(dirname, sizeof(dirname),
703                      SYSFS_PCI_DEVICES "/" PCI_PRI_FMT "/msi_irqs",
704                      loc->domain, loc->bus, loc->devid, loc->function);
705
706         d = opendir(dirname);
707         if (d)
708                 closedir(d);
709
710         return (d != NULL);
711 }
712 #else
713 static int
714 virtio_has_msix(const struct rte_pci_addr *loc __rte_unused)
715 {
716         /* nic_uio does not enable interrupts, return 0 (false). */
717         return 0;
718 }
719 #endif
720
721 /*
722  * This function is based on probe() function in virtio_pci.c
723  * It returns 0 on success.
724  */
725 static int
726 eth_virtio_dev_init(__rte_unused struct eth_driver *eth_drv,
727                 struct rte_eth_dev *eth_dev)
728 {
729         struct virtio_net_config *config;
730         struct virtio_net_config local_config;
731         uint32_t offset_conf = sizeof(config->mac);
732         struct rte_pci_device *pci_dev;
733         struct virtio_hw *hw =
734                 VIRTIO_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
735
736         if (RTE_PKTMBUF_HEADROOM < sizeof(struct virtio_net_hdr)) {
737                 PMD_INIT_LOG(ERR,
738                         "MBUF HEADROOM should be enough to hold virtio net hdr\n");
739                 return -1;
740         }
741
742         if (!(rte_eal_get_configuration()->flags & EAL_FLG_HIGH_IOPL)) {
743                 PMD_INIT_LOG(ERR,
744                         "IOPL call failed in EAL init - cannot use virtio PMD driver\n");
745                 return -1;
746         }
747
748         eth_dev->dev_ops = &virtio_eth_dev_ops;
749         eth_dev->rx_pkt_burst = &virtio_recv_pkts;
750         eth_dev->tx_pkt_burst = &virtio_xmit_pkts;
751
752         if (rte_eal_process_type() == RTE_PROC_SECONDARY)
753                 return 0;
754
755         pci_dev = eth_dev->pci_dev;
756
757 #ifdef RTE_EXEC_ENV_LINUXAPP
758         {
759                 char dirname[PATH_MAX];
760                 char filename[PATH_MAX];
761                 unsigned long start, size;
762
763                 if (get_uio_dev(&pci_dev->addr, dirname, sizeof(dirname)) < 0)
764                         return -1;
765
766                 /* get portio size */
767                 snprintf(filename, sizeof(filename),
768                              "%s/portio/port0/size", dirname);
769                 if (parse_sysfs_value(filename, &size) < 0) {
770                         PMD_INIT_LOG(ERR, "%s(): cannot parse size",
771                                      __func__);
772                         return -1;
773                 }
774
775                 /* get portio start */
776                 snprintf(filename, sizeof(filename),
777                              "%s/portio/port0/start", dirname);
778                 if (parse_sysfs_value(filename, &start) < 0) {
779                         PMD_INIT_LOG(ERR, "%s(): cannot parse portio start",
780                                      __func__);
781                         return -1;
782                 }
783                 pci_dev->mem_resource[0].addr = (void *)(uintptr_t)start;
784                 pci_dev->mem_resource[0].len =  (uint64_t)size;
785                 PMD_INIT_LOG(DEBUG,
786                              "PCI Port IO found start=0x%lx with size=0x%lx",
787                              start, size);
788         }
789 #endif
790         hw->use_msix = virtio_has_msix(&pci_dev->addr);
791         hw->io_base = (uint32_t)(uintptr_t)pci_dev->mem_resource[0].addr;
792
793         /* Reset the device although not necessary at startup */
794         vtpci_reset(hw);
795
796         /* Tell the host we've noticed this device. */
797         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_ACK);
798
799         /* Tell the host we've known how to drive the device. */
800         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_DRIVER);
801         virtio_negotiate_features(hw);
802
803         /* Setting up rx_header size for the device */
804         if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF))
805                 hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr_mrg_rxbuf);
806         else
807                 hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr);
808
809         /* Allocate memory for storing MAC addresses */
810         eth_dev->data->mac_addrs = rte_zmalloc("virtio", ETHER_ADDR_LEN, 0);
811         if (eth_dev->data->mac_addrs == NULL) {
812                 PMD_INIT_LOG(ERR,
813                         "Failed to allocate %d bytes needed to store MAC addresses",
814                         ETHER_ADDR_LEN);
815                 return -ENOMEM;
816         }
817
818         /* Copy the permanent MAC address to: virtio_hw */
819         virtio_get_hwaddr(hw);
820         ether_addr_copy((struct ether_addr *) hw->mac_addr,
821                         &eth_dev->data->mac_addrs[0]);
822         PMD_INIT_LOG(DEBUG,
823                      "PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X",
824                      hw->mac_addr[0], hw->mac_addr[1], hw->mac_addr[2],
825                      hw->mac_addr[3], hw->mac_addr[4], hw->mac_addr[5]);
826
827         if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VQ)) {
828                 config = &local_config;
829
830                 if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
831                         offset_conf += sizeof(config->status);
832                 } else {
833                         PMD_INIT_LOG(DEBUG,
834                                      "VIRTIO_NET_F_STATUS is not supported");
835                         config->status = 0;
836                 }
837
838                 if (vtpci_with_feature(hw, VIRTIO_NET_F_MQ)) {
839                         offset_conf += sizeof(config->max_virtqueue_pairs);
840                 } else {
841                         PMD_INIT_LOG(DEBUG,
842                                      "VIRTIO_NET_F_MQ is not supported");
843                         config->max_virtqueue_pairs = 1;
844                 }
845
846                 vtpci_read_dev_config(hw, 0, (uint8_t *)config, offset_conf);
847
848                 hw->max_rx_queues =
849                         (VIRTIO_MAX_RX_QUEUES < config->max_virtqueue_pairs) ?
850                         VIRTIO_MAX_RX_QUEUES : config->max_virtqueue_pairs;
851                 hw->max_tx_queues =
852                         (VIRTIO_MAX_TX_QUEUES < config->max_virtqueue_pairs) ?
853                         VIRTIO_MAX_TX_QUEUES : config->max_virtqueue_pairs;
854
855                 virtio_dev_cq_queue_setup(eth_dev,
856                                         config->max_virtqueue_pairs * 2,
857                                         SOCKET_ID_ANY);
858
859                 PMD_INIT_LOG(DEBUG, "config->max_virtqueue_pairs=%d",
860                                 config->max_virtqueue_pairs);
861                 PMD_INIT_LOG(DEBUG, "config->status=%d", config->status);
862                 PMD_INIT_LOG(DEBUG,
863                                 "PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X",
864                                 config->mac[0], config->mac[1],
865                                 config->mac[2], config->mac[3],
866                                 config->mac[4], config->mac[5]);
867         } else {
868                 hw->max_rx_queues = 1;
869                 hw->max_tx_queues = 1;
870         }
871
872         eth_dev->data->nb_rx_queues = hw->max_rx_queues;
873         eth_dev->data->nb_tx_queues = hw->max_tx_queues;
874
875         PMD_INIT_LOG(DEBUG, "hw->max_rx_queues=%d   hw->max_tx_queues=%d",
876                         hw->max_rx_queues, hw->max_tx_queues);
877         PMD_INIT_LOG(DEBUG, "port %d vendorID=0x%x deviceID=0x%x",
878                         eth_dev->data->port_id, pci_dev->id.vendor_id,
879                         pci_dev->id.device_id);
880         return 0;
881 }
882
883 static struct eth_driver rte_virtio_pmd = {
884         {
885                 .name = "rte_virtio_pmd",
886                 .id_table = pci_id_virtio_map,
887                 .drv_flags = RTE_PCI_DRV_NEED_MAPPING,
888         },
889         .eth_dev_init = eth_virtio_dev_init,
890         .dev_private_size = sizeof(struct virtio_adapter),
891 };
892
893 /*
894  * Driver initialization routine.
895  * Invoked once at EAL init time.
896  * Register itself as the [Poll Mode] Driver of PCI virtio devices.
897  * Returns 0 on success.
898  */
899 static int
900 rte_virtio_pmd_init(const char *name __rte_unused, const char *param __rte_unused)
901 {
902         rte_eth_driver_register(&rte_virtio_pmd);
903         return 0;
904 }
905
906 /*
907  * Only 1 queue is supported, no queue release related operation
908  */
909 static void
910 virtio_dev_rx_queue_release(__rte_unused void *rxq)
911 {
912 }
913
914 static void
915 virtio_dev_tx_queue_release(__rte_unused void *txq)
916 {
917 }
918
919 /*
920  * Configure virtio device
921  * It returns 0 on success.
922  */
923 static int
924 virtio_dev_configure(struct rte_eth_dev *dev)
925 {
926         const struct rte_eth_rxmode *rxmode = &dev->data->dev_conf.rxmode;
927
928         PMD_INIT_LOG(DEBUG, "configure");
929
930         if (rxmode->hw_ip_checksum) {
931                 PMD_DRV_LOG(ERR, "HW IP checksum not supported");
932                 return (-EINVAL);
933         }
934
935         return 0;
936 }
937
938
939 static int
940 virtio_dev_start(struct rte_eth_dev *dev)
941 {
942         uint16_t nb_queues, i;
943         uint16_t status;
944         struct virtio_hw *hw =
945                 VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
946
947         /* Tell the host we've noticed this device. */
948         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_ACK);
949
950         /* Tell the host we've known how to drive the device. */
951         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_DRIVER);
952
953         virtio_dev_cq_start(dev);
954
955         /* Do final configuration before rx/tx engine starts */
956         virtio_dev_rxtx_start(dev);
957
958         /* Check VIRTIO_NET_F_STATUS for link status*/
959         if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
960                 vtpci_read_dev_config(hw,
961                                 offsetof(struct virtio_net_config, status),
962                                 &status, sizeof(status));
963                 if ((status & VIRTIO_NET_S_LINK_UP) == 0) {
964                         PMD_INIT_LOG(ERR, "Port: %d Link is DOWN",
965                                      dev->data->port_id);
966                         return -EIO;
967                 } else {
968                         PMD_INIT_LOG(DEBUG, "Port: %d Link is UP",
969                                      dev->data->port_id);
970                 }
971         }
972         vtpci_reinit_complete(hw);
973
974         /*Notify the backend
975          *Otherwise the tap backend might already stop its queue due to fullness.
976          *vhost backend will have no chance to be waked up
977          */
978         nb_queues = dev->data->nb_rx_queues;
979         if (nb_queues > 1) {
980                 if (virtio_set_multiple_queues(dev, nb_queues) != 0)
981                         return -EINVAL;
982         }
983
984         PMD_INIT_LOG(DEBUG, "nb_queues=%d", nb_queues);
985
986         for (i = 0; i < nb_queues; i++)
987                 virtqueue_notify(dev->data->rx_queues[i]);
988
989         PMD_INIT_LOG(DEBUG, "Notified backend at initialization");
990
991         for (i = 0; i < dev->data->nb_rx_queues; i++)
992                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->rx_queues[i]);
993
994         for (i = 0; i < dev->data->nb_tx_queues; i++)
995                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->tx_queues[i]);
996
997         return 0;
998 }
999
1000 static void virtio_dev_free_mbufs(struct rte_eth_dev *dev)
1001 {
1002         struct rte_mbuf *buf;
1003         int i, mbuf_num = 0;
1004
1005         for (i = 0; i < dev->data->nb_rx_queues; i++) {
1006                 PMD_INIT_LOG(DEBUG,
1007                              "Before freeing rxq[%d] used and unused buf", i);
1008                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->rx_queues[i]);
1009
1010                 while ((buf = (struct rte_mbuf *)virtqueue_detatch_unused(
1011                                         dev->data->rx_queues[i])) != NULL) {
1012                         rte_pktmbuf_free_seg(buf);
1013                         mbuf_num++;
1014                 }
1015
1016                 PMD_INIT_LOG(DEBUG, "free %d mbufs", mbuf_num);
1017                 PMD_INIT_LOG(DEBUG,
1018                              "After freeing rxq[%d] used and unused buf", i);
1019                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->rx_queues[i]);
1020         }
1021
1022         for (i = 0; i < dev->data->nb_tx_queues; i++) {
1023                 PMD_INIT_LOG(DEBUG,
1024                              "Before freeing txq[%d] used and unused bufs",
1025                              i);
1026                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->tx_queues[i]);
1027
1028                 mbuf_num = 0;
1029                 while ((buf = (struct rte_mbuf *)virtqueue_detatch_unused(
1030                                         dev->data->tx_queues[i])) != NULL) {
1031                         rte_pktmbuf_free_seg(buf);
1032                         mbuf_num++;
1033                 }
1034
1035                 PMD_INIT_LOG(DEBUG, "free %d mbufs", mbuf_num);
1036                 PMD_INIT_LOG(DEBUG,
1037                              "After freeing txq[%d] used and unused buf", i);
1038                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->tx_queues[i]);
1039         }
1040 }
1041
1042 /*
1043  * Stop device: disable rx and tx functions to allow for reconfiguring.
1044  */
1045 static void
1046 virtio_dev_stop(struct rte_eth_dev *dev)
1047 {
1048         struct virtio_hw *hw =
1049                 VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
1050
1051         /* reset the NIC */
1052         vtpci_reset(hw);
1053         virtio_dev_free_mbufs(dev);
1054 }
1055
1056 static int
1057 virtio_dev_link_update(struct rte_eth_dev *dev, __rte_unused int wait_to_complete)
1058 {
1059         struct rte_eth_link link, old;
1060         uint16_t status;
1061         struct virtio_hw *hw =
1062                 VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
1063         memset(&link, 0, sizeof(link));
1064         virtio_dev_atomic_read_link_status(dev, &link);
1065         old = link;
1066         link.link_duplex = FULL_DUPLEX;
1067         link.link_speed  = SPEED_10G;
1068         if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
1069                 PMD_INIT_LOG(DEBUG, "Get link status from hw");
1070                 vtpci_read_dev_config(hw,
1071                                 offsetof(struct virtio_net_config, status),
1072                                 &status, sizeof(status));
1073                 if ((status & VIRTIO_NET_S_LINK_UP) == 0) {
1074                         link.link_status = 0;
1075                         PMD_INIT_LOG(DEBUG, "Port %d is down",
1076                                      dev->data->port_id);
1077                 } else {
1078                         link.link_status = 1;
1079                         PMD_INIT_LOG(DEBUG, "Port %d is up",
1080                                      dev->data->port_id);
1081                 }
1082         } else {
1083                 link.link_status = 1;   /* Link up */
1084         }
1085         virtio_dev_atomic_write_link_status(dev, &link);
1086         if (old.link_status == link.link_status)
1087                 return -1;
1088         /*changed*/
1089         return 0;
1090 }
1091
1092 static void
1093 virtio_dev_info_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *dev_info)
1094 {
1095         struct virtio_hw *hw = VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
1096
1097         dev_info->driver_name = dev->driver->pci_drv.name;
1098         dev_info->max_rx_queues = (uint16_t)hw->max_rx_queues;
1099         dev_info->max_tx_queues = (uint16_t)hw->max_tx_queues;
1100         dev_info->min_rx_bufsize = VIRTIO_MIN_RX_BUFSIZE;
1101         dev_info->max_rx_pktlen = VIRTIO_MAX_RX_PKTLEN;
1102         dev_info->max_mac_addrs = VIRTIO_MAX_MAC_ADDRS;
1103 }
1104
1105 /*
1106  * It enables testpmd to collect per queue stats.
1107  */
1108 static int
1109 virtio_dev_queue_stats_mapping_set(__rte_unused struct rte_eth_dev *eth_dev,
1110 __rte_unused uint16_t queue_id, __rte_unused uint8_t stat_idx,
1111 __rte_unused uint8_t is_rx)
1112 {
1113         return 0;
1114 }
1115
1116 static struct rte_driver rte_virtio_driver = {
1117         .type = PMD_PDEV,
1118         .init = rte_virtio_pmd_init,
1119 };
1120
1121 PMD_REGISTER_DRIVER(rte_virtio_driver);