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