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