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