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