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