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