remove trailing whitespaces
[dpdk.git] / examples / vhost / virtio-net.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 <dirent.h>
35 #include <fuse/cuse_lowlevel.h>
36 #include <linux/vhost.h>
37 #include <linux/virtio_net.h>
38 #include <stddef.h>
39 #include <stdint.h>
40 #include <stdlib.h>
41 #include <sys/eventfd.h>
42 #include <sys/ioctl.h>
43 #include <sys/mman.h>
44 #include <unistd.h>
45
46 #include <rte_ethdev.h>
47 #include <rte_log.h>
48 #include <rte_string_fns.h>
49 #include <rte_memory.h>
50
51 #include "main.h"
52 #include "virtio-net.h"
53 #include "vhost-net-cdev.h"
54 #include "eventfd_link/eventfd_link.h"
55
56 const char eventfd_cdev[] = "/dev/eventfd-link";
57
58 extern uint32_t num_devices;
59 static uint32_t num_cur_devices = 0;
60
61 /* device ops to add/remove device to data core. */
62 static struct virtio_net_device_ops const * notify_ops;
63 /* Root address of the linked list in the configuration core. */
64 static struct virtio_net_config_ll                      *ll_root = NULL;
65
66 /* Features supported by this application. RX merge buffers are disabled by default. */
67 uint64_t VHOST_FEATURES = (0ULL << VIRTIO_NET_F_MRG_RXBUF);
68
69 /* Line size for reading maps file. */
70 const uint32_t BUFSIZE = PATH_MAX;
71
72 /* Size of prot char array in procmap. */
73 #define PROT_SZ 5
74
75 /* Number of elements in procmap struct. */
76 #define PROCMAP_SZ 8
77
78 /* Structure containing information gathered from maps file. */
79 struct procmap
80 {
81         uint64_t        va_start;                       /* Start virtual address in file. */
82         uint64_t        len;                            /* Size of file. */
83         uint64_t        pgoff;                          /* Not used. */
84         uint32_t        maj;                            /* Not used. */
85         uint32_t        min;                            /* Not used. */
86         uint32_t        ino;                            /* Not used. */
87         char            prot[PROT_SZ];          /* Not used. */
88         char            fname[PATH_MAX];        /* File name. */
89 };
90
91 /*
92  * Converts QEMU virtual address to Vhost virtual address. This function is used
93  * to convert the ring addresses to our address space.
94  */
95 static uint64_t
96 qva_to_vva(struct virtio_net *dev, uint64_t qemu_va)
97 {
98         struct virtio_memory_regions *region;
99         uint64_t vhost_va = 0;
100         uint32_t regionidx = 0;
101
102         /* Find the region where the address lives. */
103         for (regionidx = 0; regionidx < dev->mem->nregions; regionidx++) {
104                 region = &dev->mem->regions[regionidx];
105                 if ((qemu_va >= region->userspace_address) &&
106                                 (qemu_va <= region->userspace_address +
107                                 region->memory_size)) {
108                         vhost_va = dev->mem->mapped_address + qemu_va - dev->mem->base_address;
109                         break;
110                 }
111         }
112         return vhost_va;
113 }
114
115 /*
116  * Locate the file containing QEMU's memory space and map it to our address space.
117  */
118 static int
119 host_memory_map (struct virtio_net *dev, struct virtio_memory *mem, pid_t pid, uint64_t addr)
120 {
121         struct dirent *dptr = NULL;
122         struct procmap procmap;
123         DIR *dp = NULL;
124         int fd;
125         int i;
126         char memfile[PATH_MAX];
127         char mapfile[PATH_MAX];
128         char procdir[PATH_MAX];
129         char resolved_path[PATH_MAX];
130         FILE            *fmap;
131         void            *map;
132         uint8_t         found = 0;
133         char            line[BUFSIZE];
134         char dlm[] = "-   :   ";
135         char *str, *sp, *in[PROCMAP_SZ];
136         char *end = NULL;
137
138         /* Path where mem files are located. */
139         rte_snprintf (procdir, PATH_MAX, "/proc/%u/fd/", pid);
140         /* Maps file used to locate mem file. */
141         rte_snprintf (mapfile, PATH_MAX, "/proc/%u/maps", pid);
142
143         fmap = fopen(mapfile, "r");
144         if (fmap == NULL) {
145                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Failed to open maps file for pid %d\n", dev->device_fh, pid);
146                 return -1;
147         }
148
149         /* Read through maps file until we find out base_address. */
150         while (fgets(line, BUFSIZE, fmap) != 0) {
151                 str = line;
152                 errno = 0;
153                 /* Split line in to fields. */
154                 for (i = 0; i < PROCMAP_SZ; i++) {
155                         if (((in[i] = strtok_r(str, &dlm[i], &sp)) == NULL) || (errno != 0)) {
156                                 fclose(fmap);
157                                 return -1;
158                         }
159                         str = NULL;
160                 }
161
162                 /* Convert/Copy each field as needed. */
163                 procmap.va_start = strtoull(in[0], &end, 16);
164                 if ((in[0] == '\0') || (end == NULL) || (*end != '\0') || (errno != 0)) {
165                         fclose(fmap);
166                         return -1;
167                 }
168
169                 procmap.len = strtoull(in[1], &end, 16);
170                 if ((in[1] == '\0') || (end == NULL) || (*end != '\0') || (errno != 0)) {
171                         fclose(fmap);
172                         return -1;
173                 }
174
175                 procmap.pgoff = strtoull(in[3], &end, 16);
176                 if ((in[3] == '\0') || (end == NULL) || (*end != '\0') || (errno != 0)) {
177                         fclose(fmap);
178                         return -1;
179                 }
180
181                 procmap.maj = strtoul(in[4], &end, 16);
182                 if ((in[4] == '\0') || (end == NULL) || (*end != '\0') || (errno != 0)) {
183                         fclose(fmap);
184                         return -1;
185                 }
186
187                 procmap.min = strtoul(in[5], &end, 16);
188                 if ((in[5] == '\0') || (end == NULL) || (*end != '\0') || (errno != 0)) {
189                         fclose(fmap);
190                         return -1;
191                 }
192
193                 procmap.ino = strtoul(in[6], &end, 16);
194                 if ((in[6] == '\0') || (end == NULL) || (*end != '\0') || (errno != 0)) {
195                         fclose(fmap);
196                         return -1;
197                 }
198
199                 memcpy(&procmap.prot, in[2], PROT_SZ);
200                 memcpy(&procmap.fname, in[7], PATH_MAX);
201
202                 if (procmap.va_start == addr) {
203                         procmap.len = procmap.len - procmap.va_start;
204                         found = 1;
205                         break;
206                 }
207         }
208         fclose(fmap);
209
210         if (!found) {
211                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Failed to find memory file in pid %d maps file\n", dev->device_fh, pid);
212                 return -1;
213         }
214
215         /* Find the guest memory file among the process fds. */
216         dp = opendir(procdir);
217         if (dp == NULL) {
218                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Cannot open pid %d process directory \n", dev->device_fh, pid);
219                 return -1;
220
221         }
222
223         found = 0;
224
225         /* Read the fd directory contents. */
226         while (NULL != (dptr = readdir(dp))) {
227                 rte_snprintf (memfile, PATH_MAX, "/proc/%u/fd/%s", pid, dptr->d_name);
228             realpath(memfile, resolved_path);
229                 if (resolved_path == NULL) {
230                         RTE_LOG(ERR, CONFIG, "(%"PRIu64") Failed to resolve fd directory\n", dev->device_fh);
231                         closedir(dp);
232                         return -1;
233                 }
234                 if (strncmp(resolved_path, procmap.fname,
235                         strnlen(procmap.fname, PATH_MAX)) == 0) {
236                         found = 1;
237                         break;
238                 }
239         }
240
241         closedir(dp);
242
243         if (found == 0) {
244                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Failed to find memory file for pid %d\n", dev->device_fh, pid);
245                 return -1;
246         }
247         /* Open the shared memory file and map the memory into this process. */
248         fd = open(memfile, O_RDWR);
249
250         if (fd == -1) {
251                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Failed to open %s for pid %d\n", dev->device_fh, memfile, pid);
252                 return -1;
253         }
254
255         map = mmap(0, (size_t)procmap.len, PROT_READ|PROT_WRITE , MAP_POPULATE|MAP_SHARED, fd, 0);
256         close (fd);
257
258         if (map == MAP_FAILED) {
259                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Error mapping the file %s for pid %d\n",  dev->device_fh, memfile, pid);
260                 return -1;
261         }
262
263         /* Store the memory address and size in the device data structure */
264         mem->mapped_address = (uint64_t)(uintptr_t)map;
265         mem->mapped_size = procmap.len;
266
267         LOG_DEBUG(CONFIG, "(%"PRIu64") Mem File: %s->%s - Size: %llu - VA: %p\n", dev->device_fh,
268                 memfile, resolved_path, (long long unsigned)mem->mapped_size, map);
269
270         return 0;
271 }
272
273 /*
274  * Retrieves an entry from the devices configuration linked list.
275  */
276 static struct virtio_net_config_ll *
277 get_config_ll_entry(struct vhost_device_ctx ctx)
278 {
279         struct virtio_net_config_ll *ll_dev = ll_root;
280
281         /* Loop through linked list until the device_fh is found. */
282         while (ll_dev != NULL) {
283                 if ((ll_dev->dev.device_fh == ctx.fh))
284             return ll_dev;
285                 ll_dev = ll_dev->next;
286         }
287
288         return NULL;
289 }
290
291 /*
292  * Searches the configuration core linked list and retrieves the device if it exists.
293  */
294 static struct virtio_net *
295 get_device(struct vhost_device_ctx ctx)
296 {
297         struct virtio_net_config_ll *ll_dev;
298
299         ll_dev = get_config_ll_entry(ctx);
300
301         /* If a matching entry is found in the linked list, return the device in that entry. */
302         if (ll_dev) {
303                 return &ll_dev->dev;
304         }
305
306         RTE_LOG(ERR, CONFIG, "(%"PRIu64") Device not found in linked list.\n", ctx.fh);
307         return NULL;
308 }
309
310 /*
311  * Add entry containing a device to the device configuration linked list.
312  */
313 static void
314 add_config_ll_entry(struct virtio_net_config_ll *new_ll_dev)
315 {
316         struct virtio_net_config_ll *ll_dev = ll_root;
317
318         /* If ll_dev == NULL then this is the first device so go to else */
319         if (ll_dev) {
320                 /* If the 1st device_fh != 0 then we insert our device here. */
321                 if (ll_dev->dev.device_fh != 0) {
322                         new_ll_dev->dev.device_fh = 0;
323                         new_ll_dev->next = ll_dev;
324                         ll_root = new_ll_dev;
325                 } else {
326                         /* Increment through the ll until we find un unused device_fh. Insert the device at that entry*/
327                         while ((ll_dev->next != NULL) && (ll_dev->dev.device_fh == (ll_dev->next->dev.device_fh - 1)))
328                                 ll_dev = ll_dev->next;
329
330                         new_ll_dev->dev.device_fh = ll_dev->dev.device_fh + 1;
331                         new_ll_dev->next = ll_dev->next;
332                         ll_dev->next = new_ll_dev;
333                 }
334         } else {
335                 ll_root = new_ll_dev;
336                 ll_root->dev.device_fh = 0;
337         }
338
339 }
340
341 /*
342  * Unmap any memory, close any file descriptors and free any memory owned by a device.
343  */
344 static void
345 cleanup_device(struct virtio_net *dev)
346 {
347         /* Unmap QEMU memory file if mapped. */
348         if (dev->mem) {
349                 munmap((void*)(uintptr_t)dev->mem->mapped_address, (size_t)dev->mem->mapped_size);
350                 if (dev->mem->regions_hpa)
351                         free(dev->mem->regions_hpa);
352                 free(dev->mem);
353         }
354
355         /* Close any event notifiers opened by device. */
356         if (dev->virtqueue[VIRTIO_RXQ]->callfd)
357                 close((int)dev->virtqueue[VIRTIO_RXQ]->callfd);
358         if (dev->virtqueue[VIRTIO_RXQ]->kickfd)
359                 close((int)dev->virtqueue[VIRTIO_RXQ]->kickfd);
360         if (dev->virtqueue[VIRTIO_TXQ]->callfd)
361                 close((int)dev->virtqueue[VIRTIO_TXQ]->callfd);
362         if (dev->virtqueue[VIRTIO_TXQ]->kickfd)
363                 close((int)dev->virtqueue[VIRTIO_TXQ]->kickfd);
364 }
365
366 /*
367  * Release virtqueues and device memory.
368  */
369 static void
370 free_device(struct virtio_net_config_ll *ll_dev)
371 {
372         /* Free any malloc'd memory */
373         free(ll_dev->dev.virtqueue[VIRTIO_RXQ]);
374         free(ll_dev->dev.virtqueue[VIRTIO_TXQ]);
375         free(ll_dev);
376 }
377 /*
378  * Remove an entry from the device configuration linked list.
379  */
380 static struct virtio_net_config_ll *
381 rm_config_ll_entry(struct virtio_net_config_ll *ll_dev, struct virtio_net_config_ll *ll_dev_last)
382 {
383         /* First remove the device and then clean it up. */
384         if (ll_dev == ll_root) {
385                 ll_root = ll_dev->next;
386                 cleanup_device(&ll_dev->dev);
387                 free_device(ll_dev);
388                 return ll_root;
389         } else {
390                 if (likely(ll_dev_last != NULL)) {
391                         ll_dev_last->next = ll_dev->next;
392                         cleanup_device(&ll_dev->dev);
393                         free_device(ll_dev);
394                         return ll_dev_last->next;
395                 } else {
396                         cleanup_device(&ll_dev->dev);
397                         free_device(ll_dev);
398                         RTE_LOG(ERR, CONFIG, "Remove entry from config_ll failed\n");
399                         return NULL;
400                 }
401         }
402 }
403
404 /*
405  *  Initialise all variables in device structure.
406  */
407 static void
408 init_device(struct virtio_net *dev)
409 {
410         uint64_t vq_offset;
411
412         /* Virtqueues have already been malloced so we don't want to set them to NULL. */
413         vq_offset = offsetof(struct virtio_net, mem);
414
415         /* Set everything to 0. */
416         memset((void*)(uintptr_t)((uint64_t)(uintptr_t)dev + vq_offset), 0,
417                 (sizeof(struct virtio_net) - (size_t)vq_offset));
418         memset(dev->virtqueue[VIRTIO_RXQ], 0, sizeof(struct vhost_virtqueue));
419         memset(dev->virtqueue[VIRTIO_TXQ], 0, sizeof(struct vhost_virtqueue));
420
421         /* Backends are set to -1 indicating an inactive device. */
422         dev->virtqueue[VIRTIO_RXQ]->backend = VIRTIO_DEV_STOPPED;
423         dev->virtqueue[VIRTIO_TXQ]->backend = VIRTIO_DEV_STOPPED;
424 }
425
426 /*
427  * Function is called from the CUSE open function. The device structure is
428  * initialised and a new entry is added to the device configuration linked
429  * list.
430  */
431 static int
432 new_device(struct vhost_device_ctx ctx)
433 {
434         struct virtio_net_config_ll *new_ll_dev;
435         struct vhost_virtqueue *virtqueue_rx, *virtqueue_tx;
436
437         /*check the number of devices in the system*/
438         if (num_cur_devices == num_devices) {
439                 RTE_LOG(ERR, CONFIG, "() Max num devices (%u) exceeded\n", num_devices);
440                 return -1;
441         }
442
443         /* Setup device and virtqueues. */
444         new_ll_dev = malloc(sizeof(struct virtio_net_config_ll));
445         if (new_ll_dev == NULL) {
446                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Failed to allocate memory for dev.\n", ctx.fh);
447                 return -1;
448         }
449
450         virtqueue_rx = malloc(sizeof(struct vhost_virtqueue));
451         if (virtqueue_rx == NULL) {
452                 free(new_ll_dev);
453                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Failed to allocate memory for virtqueue_rx.\n", ctx.fh);
454                 return -1;
455         }
456
457         virtqueue_tx = malloc(sizeof(struct vhost_virtqueue));
458         if (virtqueue_tx == NULL) {
459                 free(virtqueue_rx);
460                 free(new_ll_dev);
461                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Failed to allocate memory for virtqueue_tx.\n", ctx.fh);
462                 return -1;
463         }
464
465         new_ll_dev->dev.virtqueue[VIRTIO_RXQ] = virtqueue_rx;
466         new_ll_dev->dev.virtqueue[VIRTIO_TXQ] = virtqueue_tx;
467
468         /* Initialise device and virtqueues. */
469         init_device(&new_ll_dev->dev);
470
471         new_ll_dev->next = NULL;
472
473         /* Add entry to device configuration linked list. */
474         add_config_ll_entry(new_ll_dev);
475
476         /*increment the number of devices in the system*/
477         num_cur_devices++;
478
479         return new_ll_dev->dev.device_fh;
480 }
481
482 /*
483  * Function is called from the CUSE release function. This function will cleanup
484  * the device and remove it from device configuration linked list.
485  */
486 static void
487 destroy_device(struct vhost_device_ctx ctx)
488 {
489         struct virtio_net_config_ll *ll_dev_cur_ctx, *ll_dev_last = NULL;
490         struct virtio_net_config_ll *ll_dev_cur = ll_root;
491
492         /* Find the linked list entry for the device to be removed. */
493         ll_dev_cur_ctx = get_config_ll_entry(ctx);
494         while (ll_dev_cur != NULL) {
495                 /* If the device is found or a device that doesn't exist is found then it is removed. */
496                 if (ll_dev_cur == ll_dev_cur_ctx) {
497                         /*
498                          * If the device is running on a data core then call the function to remove it from
499                          * the data core.
500                          */
501                         if ((ll_dev_cur->dev.flags & VIRTIO_DEV_RUNNING))
502                                 notify_ops->destroy_device(&(ll_dev_cur->dev));
503                         ll_dev_cur = rm_config_ll_entry(ll_dev_cur, ll_dev_last);
504                 } else {
505                         ll_dev_last = ll_dev_cur;
506                         ll_dev_cur = ll_dev_cur->next;
507                 }
508         }
509
510         /*decrement the number of devices in the system*/
511         num_cur_devices--;
512 }
513
514 /*
515  * Called from CUSE IOCTL: VHOST_SET_OWNER
516  * This function just returns success at the moment unless the device hasn't been initialised.
517  */
518 static int
519 set_owner(struct vhost_device_ctx ctx)
520 {
521         struct virtio_net *dev;
522
523         dev = get_device(ctx);
524         if (dev == NULL)
525                 return -1;
526
527         return 0;
528 }
529
530 /*
531  * Called from CUSE IOCTL: VHOST_RESET_OWNER
532  */
533 static int
534 reset_owner(struct vhost_device_ctx ctx)
535 {
536         struct virtio_net_config_ll *ll_dev;
537
538         ll_dev = get_config_ll_entry(ctx);
539
540         cleanup_device(&ll_dev->dev);
541         init_device(&ll_dev->dev);
542
543         return 0;
544 }
545
546 /*
547  * Called from CUSE IOCTL: VHOST_GET_FEATURES
548  * The features that we support are requested.
549  */
550 static int
551 get_features(struct vhost_device_ctx ctx, uint64_t *pu)
552 {
553         struct virtio_net *dev;
554
555         dev = get_device(ctx);
556         if (dev == NULL)
557                 return -1;
558
559         /* Send our supported features. */
560         *pu = VHOST_FEATURES;
561         return 0;
562 }
563
564 /*
565  * Called from CUSE IOCTL: VHOST_SET_FEATURES
566  * We receive the negotiated set of features supported by us and the virtio device.
567  */
568 static int
569 set_features(struct vhost_device_ctx ctx, uint64_t *pu)
570 {
571         struct virtio_net *dev;
572
573         dev = get_device(ctx);
574         if (dev == NULL)
575                 return -1;
576         if (*pu & ~VHOST_FEATURES)
577                 return -1;
578
579         /* Store the negotiated feature list for the device. */
580         dev->features = *pu;
581
582         /* Set the vhost_hlen depending on if VIRTIO_NET_F_MRG_RXBUF is set. */
583         if (dev->features & (1 << VIRTIO_NET_F_MRG_RXBUF)) {
584                 LOG_DEBUG(CONFIG, "(%"PRIu64") Mergeable RX buffers enabled\n", dev->device_fh);
585                 dev->virtqueue[VIRTIO_RXQ]->vhost_hlen = sizeof(struct virtio_net_hdr_mrg_rxbuf);
586                 dev->virtqueue[VIRTIO_TXQ]->vhost_hlen = sizeof(struct virtio_net_hdr_mrg_rxbuf);
587         } else {
588                 LOG_DEBUG(CONFIG, "(%"PRIu64") Mergeable RX buffers disabled\n", dev->device_fh);
589                 dev->virtqueue[VIRTIO_RXQ]->vhost_hlen = sizeof(struct virtio_net_hdr);
590                 dev->virtqueue[VIRTIO_TXQ]->vhost_hlen = sizeof(struct virtio_net_hdr);
591         }
592         return 0;
593 }
594
595 /*
596  * Calculate the region count of physical continous regions for one particular
597  * region of whose vhost virtual address is continous. The particular region
598  * start from vva_start, with size of 'size' in argument.
599  */
600 static uint32_t check_hpa_regions(uint64_t vva_start, uint64_t size)
601 {
602         uint32_t i, nregions = 0, page_size = PAGE_SIZE;
603         uint64_t cur_phys_addr = 0, next_phys_addr = 0;
604         if (vva_start % page_size) {
605                 LOG_DEBUG(CONFIG,
606                         "in check_countinous: vva start(%p) mod page_size(%d) "
607                         "has remainder\n",
608                         (void *)(uintptr_t)vva_start, page_size);
609                 return 0;
610         }
611         if (size % page_size) {
612                 LOG_DEBUG(CONFIG,
613                         "in check_countinous: "
614                         "size((%"PRIu64")) mod page_size(%d) has remainder\n",
615                         size, page_size);
616                 return 0;
617         }
618         for (i = 0; i < size - page_size; i = i + page_size) {
619                 cur_phys_addr
620                         = rte_mem_virt2phy((void *)(uintptr_t)(vva_start + i));
621                 next_phys_addr = rte_mem_virt2phy(
622                         (void *)(uintptr_t)(vva_start + i + page_size));
623                 if ((cur_phys_addr + page_size) != next_phys_addr) {
624                         ++nregions;
625                         LOG_DEBUG(CONFIG,
626                                 "in check_continuous: hva addr:(%p) is not "
627                                 "continuous with hva addr:(%p), diff:%d\n",
628                                 (void *)(uintptr_t)(vva_start + (uint64_t)i),
629                                 (void *)(uintptr_t)(vva_start + (uint64_t)i
630                                 + page_size), page_size);
631                         LOG_DEBUG(CONFIG,
632                                 "in check_continuous: hpa addr:(%p) is not "
633                                 "continuous with hpa addr:(%p), "
634                                 "diff:(%"PRIu64")\n",
635                                 (void *)(uintptr_t)cur_phys_addr,
636                                 (void *)(uintptr_t)next_phys_addr,
637                                 (next_phys_addr-cur_phys_addr));
638                 }
639         }
640         return nregions;
641 }
642
643 /*
644  * Divide each region whose vhost virtual address is continous into a few
645  * sub-regions, make sure the physical address within each sub-region are
646  * continous. And fill offset(to GPA) and size etc. information of each
647  * sub-region into regions_hpa.
648  */
649 static uint32_t fill_hpa_memory_regions(void *memory)
650 {
651         uint32_t regionidx, regionidx_hpa = 0, i, k, page_size = PAGE_SIZE;
652         uint64_t cur_phys_addr = 0, next_phys_addr = 0, vva_start;
653         struct virtio_memory *virtio_memory = (struct virtio_memory *)memory;
654         struct virtio_memory_regions_hpa *mem_region_hpa
655                 = virtio_memory->regions_hpa;
656
657         if (mem_region_hpa == NULL)
658                 return 0;
659
660         for (regionidx = 0; regionidx < virtio_memory->nregions; regionidx++) {
661                 vva_start = virtio_memory->regions[regionidx].guest_phys_address
662                         + virtio_memory->regions[regionidx].address_offset;
663                 mem_region_hpa[regionidx_hpa].guest_phys_address
664                         = virtio_memory->regions[regionidx].guest_phys_address;
665                 mem_region_hpa[regionidx_hpa].host_phys_addr_offset =
666                         rte_mem_virt2phy((void *)(uintptr_t)(vva_start))
667                         - mem_region_hpa[regionidx_hpa].guest_phys_address;
668                 LOG_DEBUG(CONFIG,
669                         "in fill_hpa_regions: guest phys addr start[%d]:(%p)\n",
670                         regionidx_hpa,
671                         (void *)(uintptr_t)
672                         (mem_region_hpa[regionidx_hpa].guest_phys_address));
673                 LOG_DEBUG(CONFIG,
674                         "in fill_hpa_regions: host  phys addr start[%d]:(%p)\n",
675                         regionidx_hpa,
676                         (void *)(uintptr_t)
677                         (mem_region_hpa[regionidx_hpa].host_phys_addr_offset));
678                 for (i = 0, k = 0;
679                         i < virtio_memory->regions[regionidx].memory_size
680                                 - page_size;
681                         i += page_size) {
682                         cur_phys_addr = rte_mem_virt2phy(
683                                         (void *)(uintptr_t)(vva_start + i));
684                         next_phys_addr = rte_mem_virt2phy(
685                                         (void *)(uintptr_t)(vva_start
686                                         + i + page_size));
687                         if ((cur_phys_addr + page_size) != next_phys_addr) {
688                                 mem_region_hpa[regionidx_hpa].guest_phys_address_end =
689                                         mem_region_hpa[regionidx_hpa].guest_phys_address
690                                         + k + page_size;
691                                 mem_region_hpa[regionidx_hpa].memory_size
692                                         = k + page_size;
693                                 LOG_DEBUG(CONFIG, "in fill_hpa_regions: guest "
694                                         "phys addr end  [%d]:(%p)\n",
695                                         regionidx_hpa,
696                                         (void *)(uintptr_t)
697                                         (mem_region_hpa[regionidx_hpa].guest_phys_address_end));
698                                 LOG_DEBUG(CONFIG,
699                                         "in fill_hpa_regions: guest phys addr "
700                                         "size [%d]:(%p)\n",
701                                         regionidx_hpa,
702                                         (void *)(uintptr_t)
703                                         (mem_region_hpa[regionidx_hpa].memory_size));
704                                 mem_region_hpa[regionidx_hpa + 1].guest_phys_address
705                                         = mem_region_hpa[regionidx_hpa].guest_phys_address_end;
706                                 ++regionidx_hpa;
707                                 mem_region_hpa[regionidx_hpa].host_phys_addr_offset =
708                                         next_phys_addr
709                                         - mem_region_hpa[regionidx_hpa].guest_phys_address;
710                                 LOG_DEBUG(CONFIG, "in fill_hpa_regions: guest"
711                                         " phys addr start[%d]:(%p)\n",
712                                         regionidx_hpa,
713                                         (void *)(uintptr_t)
714                                         (mem_region_hpa[regionidx_hpa].guest_phys_address));
715                                 LOG_DEBUG(CONFIG,
716                                         "in fill_hpa_regions: host  phys addr "
717                                         "start[%d]:(%p)\n",
718                                         regionidx_hpa,
719                                         (void *)(uintptr_t)
720                                         (mem_region_hpa[regionidx_hpa].host_phys_addr_offset));
721                                 k = 0;
722                         } else {
723                                 k += page_size;
724                         }
725                 }
726                 mem_region_hpa[regionidx_hpa].guest_phys_address_end
727                         = mem_region_hpa[regionidx_hpa].guest_phys_address
728                         + k + page_size;
729                 mem_region_hpa[regionidx_hpa].memory_size = k + page_size;
730                 LOG_DEBUG(CONFIG, "in fill_hpa_regions: guest phys addr end  "
731                         "[%d]:(%p)\n", regionidx_hpa,
732                         (void *)(uintptr_t)
733                         (mem_region_hpa[regionidx_hpa].guest_phys_address_end));
734                 LOG_DEBUG(CONFIG, "in fill_hpa_regions: guest phys addr size "
735                         "[%d]:(%p)\n", regionidx_hpa,
736                         (void *)(uintptr_t)
737                         (mem_region_hpa[regionidx_hpa].memory_size));
738                 ++regionidx_hpa;
739         }
740         return regionidx_hpa;
741 }
742
743 /*
744  * Called from CUSE IOCTL: VHOST_SET_MEM_TABLE
745  * This function creates and populates the memory structure for the device. This includes
746  * storing offsets used to translate buffer addresses.
747  */
748 static int
749 set_mem_table(struct vhost_device_ctx ctx, const void *mem_regions_addr, uint32_t nregions)
750 {
751         struct virtio_net *dev;
752         struct vhost_memory_region *mem_regions;
753         struct virtio_memory *mem;
754         uint64_t size = offsetof(struct vhost_memory, regions);
755         uint32_t regionidx, valid_regions;
756
757         dev = get_device(ctx);
758         if (dev == NULL)
759                 return -1;
760
761         if (dev->mem) {
762                 munmap((void*)(uintptr_t)dev->mem->mapped_address, (size_t)dev->mem->mapped_size);
763                 free(dev->mem);
764         }
765
766         /* Malloc the memory structure depending on the number of regions. */
767         mem = calloc(1, sizeof(struct virtio_memory) + (sizeof(struct virtio_memory_regions) * nregions));
768         if (mem == NULL) {
769                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Failed to allocate memory for dev->mem.\n", dev->device_fh);
770                 return -1;
771         }
772
773         mem->nregions = nregions;
774
775         mem_regions = (void*)(uintptr_t)((uint64_t)(uintptr_t)mem_regions_addr + size);
776
777         for (regionidx = 0; regionidx < mem->nregions; regionidx++) {
778                 /* Populate the region structure for each region. */
779                 mem->regions[regionidx].guest_phys_address = mem_regions[regionidx].guest_phys_addr;
780                 mem->regions[regionidx].guest_phys_address_end = mem->regions[regionidx].guest_phys_address +
781                         mem_regions[regionidx].memory_size;
782                 mem->regions[regionidx].memory_size = mem_regions[regionidx].memory_size;
783                 mem->regions[regionidx].userspace_address = mem_regions[regionidx].userspace_addr;
784
785                 LOG_DEBUG(CONFIG, "(%"PRIu64") REGION: %u - GPA: %p - QEMU VA: %p - SIZE (%"PRIu64")\n", dev->device_fh,
786                                 regionidx, (void*)(uintptr_t)mem->regions[regionidx].guest_phys_address,
787                                 (void*)(uintptr_t)mem->regions[regionidx].userspace_address,
788                                 mem->regions[regionidx].memory_size);
789
790                 /*set the base address mapping*/
791                 if (mem->regions[regionidx].guest_phys_address == 0x0) {
792                         mem->base_address = mem->regions[regionidx].userspace_address;
793                         /* Map VM memory file */
794                         if (host_memory_map(dev, mem, ctx.pid, mem->base_address) != 0) {
795                                 free(mem);
796                                 return -1;
797                         }
798                 }
799         }
800
801         /* Check that we have a valid base address. */
802         if (mem->base_address == 0) {
803                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Failed to find base address of qemu memory file.\n", dev->device_fh);
804                 free(mem);
805                 return -1;
806         }
807
808         /* Check if all of our regions have valid mappings. Usually one does not exist in the QEMU memory file. */
809         valid_regions = mem->nregions;
810         for (regionidx = 0; regionidx < mem->nregions; regionidx++) {
811                 if ((mem->regions[regionidx].userspace_address < mem->base_address) ||
812                         (mem->regions[regionidx].userspace_address > (mem->base_address + mem->mapped_size)))
813                                 valid_regions--;
814         }
815
816         /* If a region does not have a valid mapping we rebuild our memory struct to contain only valid entries. */
817         if (valid_regions != mem->nregions) {
818                 LOG_DEBUG(CONFIG, "(%"PRIu64") Not all memory regions exist in the QEMU mem file. Re-populating mem structure\n",
819                         dev->device_fh);
820
821                 /* Re-populate the memory structure with only valid regions. Invalid regions are over-written with memmove. */
822                 valid_regions = 0;
823
824                 for (regionidx = mem->nregions; 0 != regionidx--;) {
825                         if ((mem->regions[regionidx].userspace_address < mem->base_address) ||
826                                         (mem->regions[regionidx].userspace_address > (mem->base_address + mem->mapped_size))) {
827                                 memmove(&mem->regions[regionidx], &mem->regions[regionidx + 1],
828                                         sizeof(struct virtio_memory_regions) * valid_regions);
829                         } else {
830                                 valid_regions++;
831                         }
832                 }
833         }
834         mem->nregions = valid_regions;
835         mem->nregions_hpa = mem->nregions;
836         dev->mem = mem;
837
838         /*
839          * Calculate the address offset for each region. This offset is used to identify the vhost virtual address
840          * corresponding to a QEMU guest physical address.
841          */
842         for (regionidx = 0; regionidx < dev->mem->nregions; regionidx++) {
843                 dev->mem->regions[regionidx].address_offset = dev->mem->regions[regionidx].userspace_address - dev->mem->base_address
844                         + dev->mem->mapped_address - dev->mem->regions[regionidx].guest_phys_address;
845
846                 dev->mem->nregions_hpa
847                         += check_hpa_regions(
848                                 dev->mem->regions[regionidx].guest_phys_address
849                                 + dev->mem->regions[regionidx].address_offset,
850                                 dev->mem->regions[regionidx].memory_size);
851         }
852         if (dev->mem->regions_hpa != NULL) {
853                 free(dev->mem->regions_hpa);
854                 dev->mem->regions_hpa = NULL;
855         }
856
857         dev->mem->regions_hpa = (struct virtio_memory_regions_hpa *) calloc(1,
858                 (sizeof(struct virtio_memory_regions_hpa)
859                 * dev->mem->nregions_hpa));
860         if (dev->mem->regions_hpa == NULL) {
861                 RTE_LOG(ERR, CONFIG,
862                         "(%"PRIu64") Failed to allocate memory for "
863                         "dev->mem->regions_hpa.\n", dev->device_fh);
864                 return -1;
865         }
866         if (fill_hpa_memory_regions(
867                 (void *)dev->mem) != dev->mem->nregions_hpa) {
868                 RTE_LOG(ERR, CONFIG,
869                         "in set_mem_table: hpa memory regions number mismatch: "
870                         "[%d]\n", dev->mem->nregions_hpa);
871                 return -1;
872         }
873
874         return 0;
875 }
876
877 /*
878  * Called from CUSE IOCTL: VHOST_SET_VRING_NUM
879  * The virtio device sends us the size of the descriptor ring.
880  */
881 static int
882 set_vring_num(struct vhost_device_ctx ctx, struct vhost_vring_state *state)
883 {
884         struct virtio_net *dev;
885
886         dev = get_device(ctx);
887         if (dev == NULL)
888                 return -1;
889
890         /* State->index refers to the queue index. The TX queue is 1, RX queue is 0. */
891         dev->virtqueue[state->index]->size = state->num;
892
893         return 0;
894 }
895
896 /*
897  * Called from CUSE IOCTL: VHOST_SET_VRING_ADDR
898  * The virtio device sends us the desc, used and avail ring addresses. This function
899  * then converts these to our address space.
900  */
901 static int
902 set_vring_addr(struct vhost_device_ctx ctx, struct vhost_vring_addr *addr)
903 {
904         struct virtio_net *dev;
905         struct vhost_virtqueue *vq;
906
907         dev = get_device(ctx);
908         if (dev == NULL)
909                 return -1;
910
911         /* addr->index refers to the queue index. The TX queue is 1, RX queue is 0. */
912         vq = dev->virtqueue[addr->index];
913
914         /* The addresses are converted from QEMU virtual to Vhost virtual. */
915         vq->desc = (struct vring_desc*)(uintptr_t)qva_to_vva(dev, addr->desc_user_addr);
916         if (vq->desc == 0) {
917                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Failed to find descriptor ring address.\n", dev->device_fh);
918                 return -1;
919         }
920
921         vq->avail = (struct vring_avail*)(uintptr_t)qva_to_vva(dev, addr->avail_user_addr);
922         if (vq->avail == 0) {
923                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Failed to find available ring address.\n", dev->device_fh);
924                 return -1;
925         }
926
927         vq->used = (struct vring_used*)(uintptr_t)qva_to_vva(dev, addr->used_user_addr);
928         if (vq->used == 0) {
929                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") Failed to find used ring address.\n", dev->device_fh);
930                 return -1;
931         }
932
933         LOG_DEBUG(CONFIG, "(%"PRIu64") mapped address desc: %p\n", dev->device_fh, vq->desc);
934         LOG_DEBUG(CONFIG, "(%"PRIu64") mapped address avail: %p\n", dev->device_fh, vq->avail);
935         LOG_DEBUG(CONFIG, "(%"PRIu64") mapped address used: %p\n", dev->device_fh, vq->used);
936
937         return 0;
938 }
939
940 /*
941  * Called from CUSE IOCTL: VHOST_SET_VRING_BASE
942  * The virtio device sends us the available ring last used index.
943  */
944 static int
945 set_vring_base(struct vhost_device_ctx ctx, struct vhost_vring_state *state)
946 {
947         struct virtio_net *dev;
948
949         dev = get_device(ctx);
950         if (dev == NULL)
951                 return -1;
952
953         /* State->index refers to the queue index. The TX queue is 1, RX queue is 0. */
954         dev->virtqueue[state->index]->last_used_idx = state->num;
955         dev->virtqueue[state->index]->last_used_idx_res = state->num;
956
957         return 0;
958 }
959
960 /*
961  * Called from CUSE IOCTL: VHOST_GET_VRING_BASE
962  * We send the virtio device our available ring last used index.
963  */
964 static int
965 get_vring_base(struct vhost_device_ctx ctx, uint32_t index, struct vhost_vring_state *state)
966 {
967         struct virtio_net *dev;
968
969         dev = get_device(ctx);
970         if (dev == NULL)
971                 return -1;
972
973         state->index = index;
974         /* State->index refers to the queue index. The TX queue is 1, RX queue is 0. */
975         state->num = dev->virtqueue[state->index]->last_used_idx;
976
977         return 0;
978 }
979
980 /*
981  * This function uses the eventfd_link kernel module to copy an eventfd file descriptor
982  * provided by QEMU in to our process space.
983  */
984 static int
985 eventfd_copy(struct virtio_net *dev, struct eventfd_copy *eventfd_copy)
986 {
987         int eventfd_link, ret;
988
989         /* Open the character device to the kernel module. */
990         eventfd_link = open(eventfd_cdev, O_RDWR);
991         if (eventfd_link < 0) {
992                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") eventfd_link module is not loaded\n",  dev->device_fh);
993                 return -1;
994         }
995
996         /* Call the IOCTL to copy the eventfd. */
997         ret = ioctl(eventfd_link, EVENTFD_COPY, eventfd_copy);
998         close(eventfd_link);
999
1000         if (ret < 0) {
1001                 RTE_LOG(ERR, CONFIG, "(%"PRIu64") EVENTFD_COPY ioctl failed\n",  dev->device_fh);
1002                 return -1;
1003         }
1004
1005
1006         return 0;
1007 }
1008
1009 /*
1010  * Called from CUSE IOCTL: VHOST_SET_VRING_CALL
1011  * The virtio device sends an eventfd to interrupt the guest. This fd gets copied in
1012  * to our process space.
1013  */
1014 static int
1015 set_vring_call(struct vhost_device_ctx ctx, struct vhost_vring_file *file)
1016 {
1017         struct virtio_net *dev;
1018         struct eventfd_copy     eventfd_kick;
1019         struct vhost_virtqueue *vq;
1020
1021         dev = get_device(ctx);
1022         if (dev == NULL)
1023                 return -1;
1024
1025         /* file->index refers to the queue index. The TX queue is 1, RX queue is 0. */
1026         vq = dev->virtqueue[file->index];
1027
1028         if (vq->kickfd)
1029                 close((int)vq->kickfd);
1030
1031         /* Populate the eventfd_copy structure and call eventfd_copy. */
1032         vq->kickfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
1033         eventfd_kick.source_fd = vq->kickfd;
1034         eventfd_kick.target_fd = file->fd;
1035         eventfd_kick.target_pid = ctx.pid;
1036
1037         if (eventfd_copy(dev, &eventfd_kick))
1038                 return -1;
1039
1040         return 0;
1041 }
1042
1043 /*
1044  * Called from CUSE IOCTL: VHOST_SET_VRING_KICK
1045  * The virtio device sends an eventfd that it can use to notify us. This fd gets copied in
1046  * to our process space.
1047  */
1048 static int
1049 set_vring_kick(struct vhost_device_ctx ctx, struct vhost_vring_file *file)
1050 {
1051         struct virtio_net *dev;
1052         struct eventfd_copy eventfd_call;
1053         struct vhost_virtqueue *vq;
1054
1055         dev = get_device(ctx);
1056         if (dev == NULL)
1057                 return -1;
1058
1059         /* file->index refers to the queue index. The TX queue is 1, RX queue is 0. */
1060         vq = dev->virtqueue[file->index];
1061
1062         if (vq->callfd)
1063                 close((int)vq->callfd);
1064
1065         /* Populate the eventfd_copy structure and call eventfd_copy. */
1066         vq->callfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
1067         eventfd_call.source_fd = vq->callfd;
1068         eventfd_call.target_fd = file->fd;
1069         eventfd_call.target_pid = ctx.pid;
1070
1071         if (eventfd_copy(dev, &eventfd_call))
1072         return -1;
1073
1074         return 0;
1075 }
1076
1077 /*
1078  * Called from CUSE IOCTL: VHOST_NET_SET_BACKEND
1079  * To complete device initialisation when the virtio driver is loaded we are provided with a
1080  * valid fd for a tap device (not used by us). If this happens then we can add the device to a
1081  * data core. When the virtio driver is removed we get fd=-1. At that point we remove the device
1082  * from the data core. The device will still exist in the device configuration linked list.
1083  */
1084 static int
1085 set_backend(struct vhost_device_ctx ctx, struct vhost_vring_file *file)
1086 {
1087         struct virtio_net *dev;
1088
1089         dev = get_device(ctx);
1090         if (dev == NULL) {
1091                 return -1;
1092         }
1093
1094         /* file->index refers to the queue index. The TX queue is 1, RX queue is 0. */
1095         dev->virtqueue[file->index]->backend = file->fd;
1096
1097         /* If the device isn't already running and both backend fds are set we add the device. */
1098         if (!(dev->flags & VIRTIO_DEV_RUNNING)) {
1099                 if (((int)dev->virtqueue[VIRTIO_TXQ]->backend != VIRTIO_DEV_STOPPED) &&
1100                         ((int)dev->virtqueue[VIRTIO_RXQ]->backend != VIRTIO_DEV_STOPPED))
1101                         return notify_ops->new_device(dev);
1102         /* Otherwise we remove it. */
1103         } else
1104                 if (file->fd == VIRTIO_DEV_STOPPED) {
1105                         notify_ops->destroy_device(dev);
1106                 }
1107         return 0;
1108 }
1109
1110 /*
1111  * Function pointers are set for the device operations to allow CUSE to call functions
1112  * when an IOCTL, device_add or device_release is received.
1113  */
1114 static const struct vhost_net_device_ops vhost_device_ops =
1115 {
1116         .new_device = new_device,
1117         .destroy_device = destroy_device,
1118
1119         .get_features = get_features,
1120         .set_features = set_features,
1121
1122         .set_mem_table = set_mem_table,
1123
1124         .set_vring_num = set_vring_num,
1125         .set_vring_addr = set_vring_addr,
1126         .set_vring_base = set_vring_base,
1127         .get_vring_base = get_vring_base,
1128
1129         .set_vring_kick = set_vring_kick,
1130         .set_vring_call = set_vring_call,
1131
1132         .set_backend = set_backend,
1133
1134         .set_owner = set_owner,
1135         .reset_owner = reset_owner,
1136 };
1137
1138 /*
1139  * Called by main to setup callbacks when registering CUSE device.
1140  */
1141 struct vhost_net_device_ops const *
1142 get_virtio_net_callbacks(void)
1143 {
1144         return &vhost_device_ops;
1145 }
1146
1147 /*
1148  * Register ops so that we can add/remove device to data core.
1149  */
1150 int
1151 init_virtio_net(struct virtio_net_device_ops const * const ops)
1152 {
1153         notify_ops = ops;
1154
1155         return 0;
1156 }
1157
1158 /*
1159  * Currently not used as we Ctrl+c to exit application.
1160  */
1161 int
1162 deinit_virtio_net(void)
1163 {
1164         return 0;
1165 }