virtio: fix 32-bit build for 64-bit kernel
[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.\n",
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\n",
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\n", 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\n",
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...\n");
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\n", 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\n", 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\n", __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\n", __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\n",
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                 memcpy(vq->vq_name, vq_name, sizeof(vq->vq_name));
275         } else if (queue_type == VTNET_TQ) {
276                 snprintf(vq_name, sizeof(vq_name), "port%d_tvq%d",
277                         dev->data->port_id, queue_idx);
278                 vq = rte_zmalloc(vq_name, sizeof(struct virtqueue) +
279                         vq_size * sizeof(struct vq_desc_extra), CACHE_LINE_SIZE);
280                 memcpy(vq->vq_name, vq_name, sizeof(vq->vq_name));
281         } else if (queue_type == VTNET_CQ) {
282                 snprintf(vq_name, sizeof(vq_name), "port%d_cvq",
283                         dev->data->port_id);
284                 vq = rte_zmalloc(vq_name, sizeof(struct virtqueue) +
285                         vq_size * sizeof(struct vq_desc_extra),
286                         CACHE_LINE_SIZE);
287                 memcpy(vq->vq_name, vq_name, sizeof(vq->vq_name));
288         }
289         if (vq == NULL) {
290                 PMD_INIT_LOG(ERR, "%s: Can not allocate virtqueue\n", __func__);
291                 return (-ENOMEM);
292         }
293
294         vq->hw = hw;
295         vq->port_id = dev->data->port_id;
296         vq->queue_id = queue_idx;
297         vq->vq_queue_index = vtpci_queue_idx;
298         vq->vq_alignment = VIRTIO_PCI_VRING_ALIGN;
299         vq->vq_nentries = vq_size;
300         vq->vq_free_cnt = vq_size;
301
302         /*
303          * Reserve a memzone for vring elements
304          */
305         size = vring_size(vq_size, VIRTIO_PCI_VRING_ALIGN);
306         vq->vq_ring_size = RTE_ALIGN_CEIL(size, VIRTIO_PCI_VRING_ALIGN);
307         PMD_INIT_LOG(DEBUG, "vring_size: %d, rounded_vring_size: %d\n", size, vq->vq_ring_size);
308
309         mz = rte_memzone_reserve_aligned(vq_name, vq->vq_ring_size,
310                 socket_id, 0, VIRTIO_PCI_VRING_ALIGN);
311         if (mz == NULL) {
312                 rte_free(vq);
313                 return -ENOMEM;
314         }
315
316         /*
317          * Virtio PCI device VIRTIO_PCI_QUEUE_PF register is 32bit,
318          * and only accepts 32 bit page frame number.
319          * Check if the allocated physical memory exceeds 16TB.
320          */
321         if ((mz->phys_addr + vq->vq_ring_size - 1) >> (VIRTIO_PCI_QUEUE_ADDR_SHIFT + 32)) {
322                 PMD_INIT_LOG(ERR, "vring address shouldn't be above 16TB!\n");
323                 rte_free(vq);
324                 return -ENOMEM;
325         }
326
327         memset(mz->addr, 0, sizeof(mz->len));
328         vq->mz = mz;
329         vq->vq_ring_mem = mz->phys_addr;
330         vq->vq_ring_virt_mem = mz->addr;
331         PMD_INIT_LOG(DEBUG, "vq->vq_ring_mem:      0x%"PRIx64"\n", (uint64_t)mz->phys_addr);
332         PMD_INIT_LOG(DEBUG, "vq->vq_ring_virt_mem: 0x%"PRIx64"\n", (uint64_t)mz->addr);
333         vq->virtio_net_hdr_mz  = NULL;
334         vq->virtio_net_hdr_mem = 0;
335
336         if (queue_type == VTNET_TQ) {
337                 /*
338                  * For each xmit packet, allocate a virtio_net_hdr
339                  */
340                 snprintf(vq_name, sizeof(vq_name), "port%d_tvq%d_hdrzone",
341                         dev->data->port_id, queue_idx);
342                 vq->virtio_net_hdr_mz = rte_memzone_reserve_aligned(vq_name,
343                         vq_size * sizeof(struct virtio_net_hdr),
344                         socket_id, 0, CACHE_LINE_SIZE);
345                 if (vq->virtio_net_hdr_mz == NULL) {
346                         rte_free(vq);
347                         return -ENOMEM;
348                 }
349                 vq->virtio_net_hdr_mem =
350                         vq->virtio_net_hdr_mz->phys_addr;
351                 memset(vq->virtio_net_hdr_mz->addr, 0,
352                         vq_size * sizeof(struct virtio_net_hdr));
353         } else if (queue_type == VTNET_CQ) {
354                 /* Allocate a page for control vq command, data and status */
355                 snprintf(vq_name, sizeof(vq_name), "port%d_cvq_hdrzone",
356                         dev->data->port_id);
357                 vq->virtio_net_hdr_mz = rte_memzone_reserve_aligned(vq_name,
358                         PAGE_SIZE, socket_id, 0, CACHE_LINE_SIZE);
359                 if (vq->virtio_net_hdr_mz == NULL) {
360                         rte_free(vq);
361                         return -ENOMEM;
362                 }
363                 vq->virtio_net_hdr_mem =
364                         vq->virtio_net_hdr_mz->phys_addr;
365                 memset(vq->virtio_net_hdr_mz->addr, 0, PAGE_SIZE);
366         }
367
368         /*
369          * Set guest physical address of the virtqueue
370          * in VIRTIO_PCI_QUEUE_PFN config register of device
371          */
372         VIRTIO_WRITE_REG_4(hw, VIRTIO_PCI_QUEUE_PFN,
373                         mz->phys_addr >> VIRTIO_PCI_QUEUE_ADDR_SHIFT);
374         *pvq = vq;
375         return 0;
376 }
377
378 static int
379 virtio_dev_cq_queue_setup(struct rte_eth_dev *dev, uint16_t vtpci_queue_idx,
380                 uint32_t socket_id)
381 {
382         struct virtqueue *vq;
383         uint16_t nb_desc = 0;
384         int ret;
385         struct virtio_hw *hw =
386                 VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
387
388         PMD_INIT_FUNC_TRACE();
389         ret = virtio_dev_queue_setup(dev, VTNET_CQ, VTNET_SQ_CQ_QUEUE_IDX,
390                         vtpci_queue_idx, nb_desc, socket_id, &vq);
391
392         if (ret < 0) {
393                 PMD_INIT_LOG(ERR, "control vq initialization failed\n");
394                 return ret;
395         }
396
397         hw->cvq = vq;
398         return 0;
399 }
400
401 static void
402 virtio_dev_close(struct rte_eth_dev *dev)
403 {
404         PMD_INIT_LOG(DEBUG, "virtio_dev_close");
405
406         virtio_dev_stop(dev);
407 }
408
409 /*
410  * dev_ops for virtio, bare necessities for basic operation
411  */
412 static struct eth_dev_ops virtio_eth_dev_ops = {
413         .dev_configure           = virtio_dev_configure,
414         .dev_start               = virtio_dev_start,
415         .dev_stop                = virtio_dev_stop,
416         .dev_close               = virtio_dev_close,
417
418         .dev_infos_get           = virtio_dev_info_get,
419         .stats_get               = virtio_dev_stats_get,
420         .stats_reset             = virtio_dev_stats_reset,
421         .link_update             = virtio_dev_link_update,
422         .mac_addr_add            = NULL,
423         .mac_addr_remove         = NULL,
424         .rx_queue_setup          = virtio_dev_rx_queue_setup,
425         /* meaningfull only to multiple queue */
426         .rx_queue_release        = virtio_dev_rx_queue_release,
427         .tx_queue_setup          = virtio_dev_tx_queue_setup,
428         /* meaningfull only to multiple queue */
429         .tx_queue_release        = virtio_dev_tx_queue_release,
430         /* collect stats per queue */
431         .queue_stats_mapping_set = virtio_dev_queue_stats_mapping_set,
432 };
433
434 static inline int
435 virtio_dev_atomic_read_link_status(struct rte_eth_dev *dev,
436                                 struct rte_eth_link *link)
437 {
438         struct rte_eth_link *dst = link;
439         struct rte_eth_link *src = &(dev->data->dev_link);
440
441         if (rte_atomic64_cmpset((uint64_t *)dst, *(uint64_t *)dst,
442                         *(uint64_t *)src) == 0)
443                 return -1;
444
445         return 0;
446 }
447
448 /**
449  * Atomically writes the link status information into global
450  * structure rte_eth_dev.
451  *
452  * @param dev
453  *   - Pointer to the structure rte_eth_dev to read from.
454  *   - Pointer to the buffer to be saved with the link status.
455  *
456  * @return
457  *   - On success, zero.
458  *   - On failure, negative value.
459  */
460 static inline int
461 virtio_dev_atomic_write_link_status(struct rte_eth_dev *dev,
462                 struct rte_eth_link *link)
463 {
464         struct rte_eth_link *dst = &(dev->data->dev_link);
465         struct rte_eth_link *src = link;
466
467         if (rte_atomic64_cmpset((uint64_t *)dst, *(uint64_t *)dst,
468                                         *(uint64_t *)src) == 0)
469                 return -1;
470
471         return 0;
472 }
473
474 static void
475 virtio_dev_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
476 {
477         struct virtio_hw *hw =
478                 VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
479         if (stats)
480                 memcpy(stats, &hw->eth_stats, sizeof(*stats));
481 }
482
483 static void
484 virtio_dev_stats_reset(struct rte_eth_dev *dev)
485 {
486         struct virtio_hw *hw =
487                 VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
488         /* Reset software totals */
489         memset(&hw->eth_stats, 0, sizeof(hw->eth_stats));
490 }
491
492 static void
493 virtio_set_hwaddr(struct virtio_hw *hw)
494 {
495         vtpci_write_dev_config(hw,
496                         offsetof(struct virtio_net_config, mac),
497                         &hw->mac_addr, ETHER_ADDR_LEN);
498 }
499
500 static void
501 virtio_get_hwaddr(struct virtio_hw *hw)
502 {
503         if (vtpci_with_feature(hw, VIRTIO_NET_F_MAC)) {
504                 vtpci_read_dev_config(hw,
505                         offsetof(struct virtio_net_config, mac),
506                         &hw->mac_addr, ETHER_ADDR_LEN);
507         } else {
508                 eth_random_addr(&hw->mac_addr[0]);
509                 virtio_set_hwaddr(hw);
510         }
511 }
512
513
514 static void
515 virtio_negotiate_features(struct virtio_hw *hw)
516 {
517         uint32_t guest_features, mask;
518
519         mask = VIRTIO_NET_F_CTRL_RX | VIRTIO_NET_F_CTRL_VLAN;
520         mask |= VIRTIO_NET_F_CSUM | VIRTIO_NET_F_GUEST_CSUM;
521
522         /* TSO and LRO are only available when their corresponding
523          * checksum offload feature is also negotiated.
524          */
525         mask |= VIRTIO_NET_F_HOST_TSO4 | VIRTIO_NET_F_HOST_TSO6 | VIRTIO_NET_F_HOST_ECN;
526         mask |= VIRTIO_NET_F_GUEST_TSO4 | VIRTIO_NET_F_GUEST_TSO6 | VIRTIO_NET_F_GUEST_ECN;
527         mask |= VTNET_LRO_FEATURES;
528
529         /* rx_mbuf should not be in multiple merged segments */
530         mask |= VIRTIO_NET_F_MRG_RXBUF;
531
532         /* not negotiating INDIRECT descriptor table support */
533         mask |= VIRTIO_RING_F_INDIRECT_DESC;
534
535         /* Prepare guest_features: feature that driver wants to support */
536         guest_features = VTNET_FEATURES & ~mask;
537         PMD_INIT_LOG(DEBUG, "guest_features before negotiate = %x\n",
538                 guest_features);
539
540         /* Read device(host) feature bits */
541         hw->host_features = VIRTIO_READ_REG_4(hw, VIRTIO_PCI_HOST_FEATURES);
542         PMD_INIT_LOG(DEBUG, "host_features before negotiate = %x\n",
543                 hw->host_features);
544
545         /*
546          * Negotiate features: Subset of device feature bits are written back
547          * guest feature bits.
548          */
549         hw->guest_features = vtpci_negotiate_features(hw, guest_features);
550         PMD_INIT_LOG(DEBUG, "features after negotiate = %x\n",
551                 hw->guest_features);
552 }
553
554 #ifdef RTE_EXEC_ENV_LINUXAPP
555 static int
556 parse_sysfs_value(const char *filename, unsigned long *val)
557 {
558         FILE *f;
559         char buf[BUFSIZ];
560         char *end = NULL;
561
562         f = fopen(filename, "r");
563         if (f == NULL) {
564                 PMD_INIT_LOG(ERR, "%s(): cannot open sysfs value %s\n",
565                              __func__, filename);
566                 return -1;
567         }
568
569         if (fgets(buf, sizeof(buf), f) == NULL) {
570                 PMD_INIT_LOG(ERR, "%s(): cannot read sysfs value %s\n",
571                              __func__, filename);
572                 fclose(f);
573                 return -1;
574         }
575         *val = strtoul(buf, &end, 0);
576         if ((buf[0] == '\0') || (end == NULL) || (*end != '\n')) {
577                 PMD_INIT_LOG(ERR, "%s(): cannot parse sysfs value %s\n",
578                              __func__, filename);
579                 fclose(f);
580                 return -1;
581         }
582         fclose(f);
583         return 0;
584 }
585
586 static int get_uio_dev(struct rte_pci_addr *loc, char *buf, unsigned int buflen)
587 {
588         unsigned int uio_num;
589         struct dirent *e;
590         DIR *dir;
591         char dirname[PATH_MAX];
592
593         /* depending on kernel version, uio can be located in uio/uioX
594          * or uio:uioX */
595         snprintf(dirname, sizeof(dirname),
596                      SYSFS_PCI_DEVICES "/" PCI_PRI_FMT "/uio",
597                      loc->domain, loc->bus, loc->devid, loc->function);
598         dir = opendir(dirname);
599         if (dir == NULL) {
600                 /* retry with the parent directory */
601                 snprintf(dirname, sizeof(dirname),
602                              SYSFS_PCI_DEVICES "/" PCI_PRI_FMT,
603                              loc->domain, loc->bus, loc->devid, loc->function);
604                 dir = opendir(dirname);
605
606                 if (dir == NULL) {
607                         PMD_INIT_LOG(ERR, "Cannot opendir %s\n", dirname);
608                         return -1;
609                 }
610         }
611
612         /* take the first file starting with "uio" */
613         while ((e = readdir(dir)) != NULL) {
614                 /* format could be uio%d ...*/
615                 int shortprefix_len = sizeof("uio") - 1;
616                 /* ... or uio:uio%d */
617                 int longprefix_len = sizeof("uio:uio") - 1;
618                 char *endptr;
619
620                 if (strncmp(e->d_name, "uio", 3) != 0)
621                         continue;
622
623                 /* first try uio%d */
624                 errno = 0;
625                 uio_num = strtoull(e->d_name + shortprefix_len, &endptr, 10);
626                 if (errno == 0 && endptr != (e->d_name + shortprefix_len)) {
627                         snprintf(buf, buflen, "%s/uio%u", dirname, uio_num);
628                         break;
629                 }
630
631                 /* then try uio:uio%d */
632                 errno = 0;
633                 uio_num = strtoull(e->d_name + longprefix_len, &endptr, 10);
634                 if (errno == 0 && endptr != (e->d_name + longprefix_len)) {
635                         snprintf(buf, buflen, "%s/uio:uio%u", dirname,
636                                      uio_num);
637                         break;
638                 }
639         }
640         closedir(dir);
641
642         /* No uio resource found */
643         if (e == NULL) {
644                 PMD_INIT_LOG(ERR, "Could not find uio resource\n");
645                 return -1;
646         }
647
648         return 0;
649 }
650
651 static int
652 virtio_has_msix(const struct rte_pci_addr *loc)
653 {
654         DIR *d;
655         char dirname[PATH_MAX];
656
657         snprintf(dirname, sizeof(dirname),
658                      SYSFS_PCI_DEVICES "/" PCI_PRI_FMT "/msi_irqs",
659                      loc->domain, loc->bus, loc->devid, loc->function);
660
661         d = opendir(dirname);
662         if (d)
663                 closedir(d);
664
665         return (d != NULL);
666 }
667 #else
668 static int
669 virtio_has_msix(const struct rte_pci_addr *loc __rte_unused)
670 {
671         /* nic_uio does not enable interrupts, return 0 (false). */
672         return 0;
673 }
674 #endif
675
676 /*
677  * This function is based on probe() function in virtio_pci.c
678  * It returns 0 on success.
679  */
680 static int
681 eth_virtio_dev_init(__rte_unused struct eth_driver *eth_drv,
682                 struct rte_eth_dev *eth_dev)
683 {
684         struct virtio_net_config *config;
685         struct virtio_net_config local_config;
686         uint32_t offset_conf = sizeof(config->mac);
687         struct rte_pci_device *pci_dev;
688         struct virtio_hw *hw =
689                 VIRTIO_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
690
691         if (RTE_PKTMBUF_HEADROOM < sizeof(struct virtio_net_hdr)) {
692                 PMD_INIT_LOG(ERR,
693                         "MBUF HEADROOM should be enough to hold virtio net hdr\n");
694                 return -1;
695         }
696
697         if (!(rte_eal_get_configuration()->flags & EAL_FLG_HIGH_IOPL)) {
698                 PMD_INIT_LOG(ERR,
699                         "IOPL call failed in EAL init - cannot use virtio PMD driver\n");
700                 return -1;
701         }
702
703         eth_dev->dev_ops = &virtio_eth_dev_ops;
704         eth_dev->rx_pkt_burst = &virtio_recv_pkts;
705         eth_dev->tx_pkt_burst = &virtio_xmit_pkts;
706
707         if (rte_eal_process_type() == RTE_PROC_SECONDARY)
708                 return 0;
709
710         pci_dev = eth_dev->pci_dev;
711
712         hw->device_id = pci_dev->id.device_id;
713         hw->vendor_id = pci_dev->id.vendor_id;
714 #ifdef RTE_EXEC_ENV_LINUXAPP
715         {
716                 char dirname[PATH_MAX];
717                 char filename[PATH_MAX];
718                 unsigned long start, size;
719
720                 if (get_uio_dev(&pci_dev->addr, dirname, sizeof(dirname)) < 0)
721                         return -1;
722
723                 /* get portio size */
724                 snprintf(filename, sizeof(filename),
725                              "%s/portio/port0/size", dirname);
726                 if (parse_sysfs_value(filename, &size) < 0) {
727                         PMD_INIT_LOG(ERR, "%s(): cannot parse size\n",
728                                      __func__);
729                         return -1;
730                 }
731
732                 /* get portio start */
733                 snprintf(filename, sizeof(filename),
734                              "%s/portio/port0/start", dirname);
735                 if (parse_sysfs_value(filename, &start) < 0) {
736                         PMD_INIT_LOG(ERR, "%s(): cannot parse portio start\n",
737                                      __func__);
738                         return -1;
739                 }
740                 pci_dev->mem_resource[0].addr = (void *)(uintptr_t)start;
741                 pci_dev->mem_resource[0].len =  (uint64_t)size;
742                 PMD_INIT_LOG(DEBUG,
743                              "PCI Port IO found start=0x%lx with size=0x%lx\n",
744                              start, size);
745         }
746 #endif
747         hw->use_msix = virtio_has_msix(&pci_dev->addr);
748         hw->io_base = (uint32_t)(uintptr_t)pci_dev->mem_resource[0].addr;
749
750         /* Reset the device although not necessary at startup */
751         vtpci_reset(hw);
752
753         /* Tell the host we've noticed this device. */
754         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_ACK);
755
756         /* Tell the host we've known how to drive the device. */
757         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_DRIVER);
758         virtio_negotiate_features(hw);
759
760         /* Setting up rx_header size for the device */
761         if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF))
762                 hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr_mrg_rxbuf);
763         else
764                 hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr);
765
766         /* Allocate memory for storing MAC addresses */
767         eth_dev->data->mac_addrs = rte_zmalloc("virtio", ETHER_ADDR_LEN, 0);
768         if (eth_dev->data->mac_addrs == NULL) {
769                 PMD_INIT_LOG(ERR,
770                         "Failed to allocate %d bytes needed to store MAC addresses",
771                         ETHER_ADDR_LEN);
772                 return -ENOMEM;
773         }
774
775         /* Copy the permanent MAC address to: virtio_hw */
776         virtio_get_hwaddr(hw);
777         ether_addr_copy((struct ether_addr *) hw->mac_addr,
778                         &eth_dev->data->mac_addrs[0]);
779         PMD_INIT_LOG(DEBUG,
780                      "PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X\n",
781                      hw->mac_addr[0], hw->mac_addr[1], hw->mac_addr[2],
782                      hw->mac_addr[3], hw->mac_addr[4], hw->mac_addr[5]);
783
784         if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VQ)) {
785                 config = &local_config;
786
787                 if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
788                         offset_conf += sizeof(config->status);
789                 } else {
790                         PMD_INIT_LOG(DEBUG,
791                                      "VIRTIO_NET_F_STATUS is not supported\n");
792                         config->status = 0;
793                 }
794
795                 if (vtpci_with_feature(hw, VIRTIO_NET_F_MQ)) {
796                         offset_conf += sizeof(config->max_virtqueue_pairs);
797                 } else {
798                         PMD_INIT_LOG(DEBUG,
799                                      "VIRTIO_NET_F_MQ is not supported\n");
800                         config->max_virtqueue_pairs = 1;
801                 }
802
803                 vtpci_read_dev_config(hw, 0, (uint8_t *)config, offset_conf);
804
805                 hw->max_rx_queues =
806                         (VIRTIO_MAX_RX_QUEUES < config->max_virtqueue_pairs) ?
807                         VIRTIO_MAX_RX_QUEUES : config->max_virtqueue_pairs;
808                 hw->max_tx_queues =
809                         (VIRTIO_MAX_TX_QUEUES < config->max_virtqueue_pairs) ?
810                         VIRTIO_MAX_TX_QUEUES : config->max_virtqueue_pairs;
811
812                 virtio_dev_cq_queue_setup(eth_dev,
813                                         config->max_virtqueue_pairs * 2,
814                                         SOCKET_ID_ANY);
815
816                 PMD_INIT_LOG(DEBUG, "config->max_virtqueue_pairs=%d\n",
817                                 config->max_virtqueue_pairs);
818                 PMD_INIT_LOG(DEBUG, "config->status=%d\n", config->status);
819                 PMD_INIT_LOG(DEBUG,
820                                 "PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X\n",
821                                 config->mac[0], config->mac[1],
822                                 config->mac[2], config->mac[3],
823                                 config->mac[4], config->mac[5]);
824         } else {
825                 hw->max_rx_queues = 1;
826                 hw->max_tx_queues = 1;
827         }
828
829         eth_dev->data->nb_rx_queues = hw->max_rx_queues;
830         eth_dev->data->nb_tx_queues = hw->max_tx_queues;
831
832         PMD_INIT_LOG(DEBUG, "hw->max_rx_queues=%d   hw->max_tx_queues=%d\n",
833                         hw->max_rx_queues, hw->max_tx_queues);
834         PMD_INIT_LOG(DEBUG, "port %d vendorID=0x%x deviceID=0x%x",
835                         eth_dev->data->port_id, pci_dev->id.vendor_id,
836                         pci_dev->id.device_id);
837         return 0;
838 }
839
840 static struct eth_driver rte_virtio_pmd = {
841         {
842                 .name = "rte_virtio_pmd",
843                 .id_table = pci_id_virtio_map,
844                 .drv_flags = RTE_PCI_DRV_NEED_MAPPING,
845         },
846         .eth_dev_init = eth_virtio_dev_init,
847         .dev_private_size = sizeof(struct virtio_adapter),
848 };
849
850 /*
851  * Driver initialization routine.
852  * Invoked once at EAL init time.
853  * Register itself as the [Poll Mode] Driver of PCI virtio devices.
854  * Returns 0 on success.
855  */
856 static int
857 rte_virtio_pmd_init(const char *name __rte_unused, const char *param __rte_unused)
858 {
859         rte_eth_driver_register(&rte_virtio_pmd);
860         return 0;
861 }
862
863 /*
864  * Only 1 queue is supported, no queue release related operation
865  */
866 static void
867 virtio_dev_rx_queue_release(__rte_unused void *rxq)
868 {
869 }
870
871 static void
872 virtio_dev_tx_queue_release(__rte_unused void *txq)
873 {
874 }
875
876 /*
877  * Configure virtio device
878  * It returns 0 on success.
879  */
880 static int
881 virtio_dev_configure(__rte_unused struct rte_eth_dev *dev)
882 {
883         return 0;
884 }
885
886
887 static int
888 virtio_dev_start(struct rte_eth_dev *dev)
889 {
890         uint16_t nb_queues, i;
891         uint16_t status;
892         struct virtio_hw *hw =
893                 VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
894
895         /* Tell the host we've noticed this device. */
896         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_ACK);
897
898         /* Tell the host we've known how to drive the device. */
899         vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_DRIVER);
900
901         hw->adapter_stopped = 0;
902
903         virtio_dev_cq_start(dev);
904
905         /* Do final configuration before rx/tx engine starts */
906         virtio_dev_rxtx_start(dev);
907
908         /* Check VIRTIO_NET_F_STATUS for link status*/
909         if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
910                 vtpci_read_dev_config(hw,
911                                 offsetof(struct virtio_net_config, status),
912                                 &status, sizeof(status));
913                 if ((status & VIRTIO_NET_S_LINK_UP) == 0) {
914                         PMD_INIT_LOG(ERR,     "Port: %d Link is DOWN\n", dev->data->port_id);
915                         return -EIO;
916                 } else {
917                         PMD_INIT_LOG(DEBUG, "Port: %d Link is UP\n",  dev->data->port_id);
918                 }
919         }
920         vtpci_reinit_complete(hw);
921
922         /*Notify the backend
923          *Otherwise the tap backend might already stop its queue due to fullness.
924          *vhost backend will have no chance to be waked up
925          */
926         nb_queues = dev->data->nb_rx_queues;
927         if (nb_queues > 1) {
928                 if (virtio_set_multiple_queues(dev, nb_queues) != 0)
929                         return -EINVAL;
930         }
931
932         PMD_INIT_LOG(DEBUG, "nb_queues=%d\n", nb_queues);
933
934         for (i = 0; i < nb_queues; i++)
935                 virtqueue_notify(dev->data->rx_queues[i]);
936
937         PMD_INIT_LOG(DEBUG, "Notified backend at initialization\n");
938
939         for (i = 0; i < dev->data->nb_rx_queues; i++)
940                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->rx_queues[i]);
941
942         for (i = 0; i < dev->data->nb_tx_queues; i++)
943                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->tx_queues[i]);
944
945         return 0;
946 }
947
948 static void virtio_dev_free_mbufs(struct rte_eth_dev *dev)
949 {
950         struct rte_mbuf *buf;
951         int i, mbuf_num = 0;
952
953         for (i = 0; i < dev->data->nb_rx_queues; i++) {
954                 PMD_INIT_LOG(DEBUG,
955                              "Before freeing rxq[%d] used and unused buf\n", i);
956                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->rx_queues[i]);
957
958                 while ((buf = (struct rte_mbuf *)virtqueue_detatch_unused(
959                                         dev->data->rx_queues[i])) != NULL) {
960                         rte_pktmbuf_free_seg(buf);
961                         mbuf_num++;
962                 }
963
964                 PMD_INIT_LOG(DEBUG, "free %d mbufs\n", mbuf_num);
965                 PMD_INIT_LOG(DEBUG,
966                              "After freeing rxq[%d] used and unused buf\n", i);
967                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->rx_queues[i]);
968         }
969
970         for (i = 0; i < dev->data->nb_tx_queues; i++) {
971                 PMD_INIT_LOG(DEBUG,
972                              "Before freeing txq[%d] used and unused bufs\n",
973                              i);
974                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->tx_queues[i]);
975
976                 mbuf_num = 0;
977                 while ((buf = (struct rte_mbuf *)virtqueue_detatch_unused(
978                                         dev->data->tx_queues[i])) != NULL) {
979                         rte_pktmbuf_free_seg(buf);
980                         mbuf_num++;
981                 }
982
983                 PMD_INIT_LOG(DEBUG, "free %d mbufs\n", mbuf_num);
984                 PMD_INIT_LOG(DEBUG, "After freeing txq[%d] used and "
985                         "unused buf\n", i);
986                 VIRTQUEUE_DUMP((struct virtqueue *)dev->data->tx_queues[i]);
987         }
988 }
989
990 /*
991  * Stop device: disable rx and tx functions to allow for reconfiguring.
992  */
993 static void
994 virtio_dev_stop(struct rte_eth_dev *dev)
995 {
996         struct virtio_hw *hw =
997                 VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
998
999         /* reset the NIC */
1000         vtpci_reset(hw);
1001         virtio_dev_free_mbufs(dev);
1002 }
1003
1004 static int
1005 virtio_dev_link_update(struct rte_eth_dev *dev, __rte_unused int wait_to_complete)
1006 {
1007         struct rte_eth_link link, old;
1008         uint16_t status;
1009         struct virtio_hw *hw =
1010                 VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
1011         memset(&link, 0, sizeof(link));
1012         virtio_dev_atomic_read_link_status(dev, &link);
1013         old = link;
1014         link.link_duplex = FULL_DUPLEX;
1015         link.link_speed  = SPEED_10G;
1016         if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
1017                 PMD_INIT_LOG(DEBUG, "Get link status from hw\n");
1018                 vtpci_read_dev_config(hw,
1019                                 offsetof(struct virtio_net_config, status),
1020                                 &status, sizeof(status));
1021                 if ((status & VIRTIO_NET_S_LINK_UP) == 0) {
1022                         link.link_status = 0;
1023                         PMD_INIT_LOG(DEBUG, "Port %d is down\n",
1024                                      dev->data->port_id);
1025                 } else {
1026                         link.link_status = 1;
1027                         PMD_INIT_LOG(DEBUG, "Port %d is up\n",
1028                                      dev->data->port_id);
1029                 }
1030         } else {
1031                 link.link_status = 1;   /* Link up */
1032         }
1033         virtio_dev_atomic_write_link_status(dev, &link);
1034         if (old.link_status == link.link_status)
1035                 return -1;
1036         /*changed*/
1037         return 0;
1038 }
1039
1040 static void
1041 virtio_dev_info_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *dev_info)
1042 {
1043         struct virtio_hw *hw = VIRTIO_DEV_PRIVATE_TO_HW(dev->data->dev_private);
1044
1045         dev_info->driver_name = dev->driver->pci_drv.name;
1046         dev_info->max_rx_queues = (uint16_t)hw->max_rx_queues;
1047         dev_info->max_tx_queues = (uint16_t)hw->max_tx_queues;
1048         dev_info->min_rx_bufsize = VIRTIO_MIN_RX_BUFSIZE;
1049         dev_info->max_rx_pktlen = VIRTIO_MAX_RX_PKTLEN;
1050         dev_info->max_mac_addrs = VIRTIO_MAX_MAC_ADDRS;
1051 }
1052
1053 /*
1054  * It enables testpmd to collect per queue stats.
1055  */
1056 static int
1057 virtio_dev_queue_stats_mapping_set(__rte_unused struct rte_eth_dev *eth_dev,
1058 __rte_unused uint16_t queue_id, __rte_unused uint8_t stat_idx,
1059 __rte_unused uint8_t is_rx)
1060 {
1061         return 0;
1062 }
1063
1064 static struct rte_driver rte_virtio_driver = {
1065         .type = PMD_PDEV,
1066         .init = rte_virtio_pmd_init,
1067 };
1068
1069 PMD_REGISTER_DRIVER(rte_virtio_driver);