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