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