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