vhost: get guest/host physical address mappings
[dpdk.git] / lib / librte_vhost / vhost_user.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2016 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 <stdint.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <sys/mman.h>
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <assert.h>
43 #ifdef RTE_LIBRTE_VHOST_NUMA
44 #include <numaif.h>
45 #endif
46
47 #include <rte_common.h>
48 #include <rte_malloc.h>
49 #include <rte_log.h>
50
51 #include "vhost.h"
52 #include "vhost_user.h"
53
54 static const char *vhost_message_str[VHOST_USER_MAX] = {
55         [VHOST_USER_NONE] = "VHOST_USER_NONE",
56         [VHOST_USER_GET_FEATURES] = "VHOST_USER_GET_FEATURES",
57         [VHOST_USER_SET_FEATURES] = "VHOST_USER_SET_FEATURES",
58         [VHOST_USER_SET_OWNER] = "VHOST_USER_SET_OWNER",
59         [VHOST_USER_RESET_OWNER] = "VHOST_USER_RESET_OWNER",
60         [VHOST_USER_SET_MEM_TABLE] = "VHOST_USER_SET_MEM_TABLE",
61         [VHOST_USER_SET_LOG_BASE] = "VHOST_USER_SET_LOG_BASE",
62         [VHOST_USER_SET_LOG_FD] = "VHOST_USER_SET_LOG_FD",
63         [VHOST_USER_SET_VRING_NUM] = "VHOST_USER_SET_VRING_NUM",
64         [VHOST_USER_SET_VRING_ADDR] = "VHOST_USER_SET_VRING_ADDR",
65         [VHOST_USER_SET_VRING_BASE] = "VHOST_USER_SET_VRING_BASE",
66         [VHOST_USER_GET_VRING_BASE] = "VHOST_USER_GET_VRING_BASE",
67         [VHOST_USER_SET_VRING_KICK] = "VHOST_USER_SET_VRING_KICK",
68         [VHOST_USER_SET_VRING_CALL] = "VHOST_USER_SET_VRING_CALL",
69         [VHOST_USER_SET_VRING_ERR]  = "VHOST_USER_SET_VRING_ERR",
70         [VHOST_USER_GET_PROTOCOL_FEATURES]  = "VHOST_USER_GET_PROTOCOL_FEATURES",
71         [VHOST_USER_SET_PROTOCOL_FEATURES]  = "VHOST_USER_SET_PROTOCOL_FEATURES",
72         [VHOST_USER_GET_QUEUE_NUM]  = "VHOST_USER_GET_QUEUE_NUM",
73         [VHOST_USER_SET_VRING_ENABLE]  = "VHOST_USER_SET_VRING_ENABLE",
74         [VHOST_USER_SEND_RARP]  = "VHOST_USER_SEND_RARP",
75 };
76
77 static uint64_t
78 get_blk_size(int fd)
79 {
80         struct stat stat;
81         int ret;
82
83         ret = fstat(fd, &stat);
84         return ret == -1 ? (uint64_t)-1 : (uint64_t)stat.st_blksize;
85 }
86
87 static void
88 free_mem_region(struct virtio_net *dev)
89 {
90         uint32_t i;
91         struct virtio_memory_region *reg;
92
93         if (!dev || !dev->mem)
94                 return;
95
96         for (i = 0; i < dev->mem->nregions; i++) {
97                 reg = &dev->mem->regions[i];
98                 if (reg->host_user_addr) {
99                         munmap(reg->mmap_addr, reg->mmap_size);
100                         close(reg->fd);
101                 }
102         }
103 }
104
105 void
106 vhost_backend_cleanup(struct virtio_net *dev)
107 {
108         if (dev->mem) {
109                 free_mem_region(dev);
110                 rte_free(dev->mem);
111                 dev->mem = NULL;
112         }
113         if (dev->log_addr) {
114                 munmap((void *)(uintptr_t)dev->log_addr, dev->log_size);
115                 dev->log_addr = 0;
116         }
117 }
118
119 /*
120  * This function just returns success at the moment unless
121  * the device hasn't been initialised.
122  */
123 static int
124 vhost_user_set_owner(void)
125 {
126         return 0;
127 }
128
129 static int
130 vhost_user_reset_owner(struct virtio_net *dev)
131 {
132         if (dev->flags & VIRTIO_DEV_RUNNING) {
133                 dev->flags &= ~VIRTIO_DEV_RUNNING;
134                 notify_ops->destroy_device(dev->vid);
135         }
136
137         cleanup_device(dev, 0);
138         reset_device(dev);
139         return 0;
140 }
141
142 /*
143  * The features that we support are requested.
144  */
145 static uint64_t
146 vhost_user_get_features(void)
147 {
148         return VHOST_FEATURES;
149 }
150
151 /*
152  * We receive the negotiated features supported by us and the virtio device.
153  */
154 static int
155 vhost_user_set_features(struct virtio_net *dev, uint64_t features)
156 {
157         if (features & ~VHOST_FEATURES)
158                 return -1;
159
160         dev->features = features;
161         if (dev->features &
162                 ((1 << VIRTIO_NET_F_MRG_RXBUF) | (1ULL << VIRTIO_F_VERSION_1))) {
163                 dev->vhost_hlen = sizeof(struct virtio_net_hdr_mrg_rxbuf);
164         } else {
165                 dev->vhost_hlen = sizeof(struct virtio_net_hdr);
166         }
167         LOG_DEBUG(VHOST_CONFIG,
168                 "(%d) mergeable RX buffers %s, virtio 1 %s\n",
169                 dev->vid,
170                 (dev->features & (1 << VIRTIO_NET_F_MRG_RXBUF)) ? "on" : "off",
171                 (dev->features & (1ULL << VIRTIO_F_VERSION_1)) ? "on" : "off");
172
173         return 0;
174 }
175
176 /*
177  * The virtio device sends us the size of the descriptor ring.
178  */
179 static int
180 vhost_user_set_vring_num(struct virtio_net *dev,
181                          struct vhost_vring_state *state)
182 {
183         dev->virtqueue[state->index]->size = state->num;
184
185         return 0;
186 }
187
188 /*
189  * Reallocate virtio_dev and vhost_virtqueue data structure to make them on the
190  * same numa node as the memory of vring descriptor.
191  */
192 #ifdef RTE_LIBRTE_VHOST_NUMA
193 static struct virtio_net*
194 numa_realloc(struct virtio_net *dev, int index)
195 {
196         int oldnode, newnode;
197         struct virtio_net *old_dev;
198         struct vhost_virtqueue *old_vq, *vq;
199         int ret;
200
201         /*
202          * vq is allocated on pairs, we should try to do realloc
203          * on first queue of one queue pair only.
204          */
205         if (index % VIRTIO_QNUM != 0)
206                 return dev;
207
208         old_dev = dev;
209         vq = old_vq = dev->virtqueue[index];
210
211         ret = get_mempolicy(&newnode, NULL, 0, old_vq->desc,
212                             MPOL_F_NODE | MPOL_F_ADDR);
213
214         /* check if we need to reallocate vq */
215         ret |= get_mempolicy(&oldnode, NULL, 0, old_vq,
216                              MPOL_F_NODE | MPOL_F_ADDR);
217         if (ret) {
218                 RTE_LOG(ERR, VHOST_CONFIG,
219                         "Unable to get vq numa information.\n");
220                 return dev;
221         }
222         if (oldnode != newnode) {
223                 RTE_LOG(INFO, VHOST_CONFIG,
224                         "reallocate vq from %d to %d node\n", oldnode, newnode);
225                 vq = rte_malloc_socket(NULL, sizeof(*vq) * VIRTIO_QNUM, 0,
226                                        newnode);
227                 if (!vq)
228                         return dev;
229
230                 memcpy(vq, old_vq, sizeof(*vq) * VIRTIO_QNUM);
231                 rte_free(old_vq);
232         }
233
234         /* check if we need to reallocate dev */
235         ret = get_mempolicy(&oldnode, NULL, 0, old_dev,
236                             MPOL_F_NODE | MPOL_F_ADDR);
237         if (ret) {
238                 RTE_LOG(ERR, VHOST_CONFIG,
239                         "Unable to get dev numa information.\n");
240                 goto out;
241         }
242         if (oldnode != newnode) {
243                 RTE_LOG(INFO, VHOST_CONFIG,
244                         "reallocate dev from %d to %d node\n",
245                         oldnode, newnode);
246                 dev = rte_malloc_socket(NULL, sizeof(*dev), 0, newnode);
247                 if (!dev) {
248                         dev = old_dev;
249                         goto out;
250                 }
251
252                 memcpy(dev, old_dev, sizeof(*dev));
253                 rte_free(old_dev);
254         }
255
256 out:
257         dev->virtqueue[index] = vq;
258         dev->virtqueue[index + 1] = vq + 1;
259         vhost_devices[dev->vid] = dev;
260
261         return dev;
262 }
263 #else
264 static struct virtio_net*
265 numa_realloc(struct virtio_net *dev, int index __rte_unused)
266 {
267         return dev;
268 }
269 #endif
270
271 /*
272  * Converts QEMU virtual address to Vhost virtual address. This function is
273  * used to convert the ring addresses to our address space.
274  */
275 static uint64_t
276 qva_to_vva(struct virtio_net *dev, uint64_t qva)
277 {
278         struct virtio_memory_region *reg;
279         uint32_t i;
280
281         /* Find the region where the address lives. */
282         for (i = 0; i < dev->mem->nregions; i++) {
283                 reg = &dev->mem->regions[i];
284
285                 if (qva >= reg->guest_user_addr &&
286                     qva <  reg->guest_user_addr + reg->size) {
287                         return qva - reg->guest_user_addr +
288                                reg->host_user_addr;
289                 }
290         }
291
292         return 0;
293 }
294
295 /*
296  * The virtio device sends us the desc, used and avail ring addresses.
297  * This function then converts these to our address space.
298  */
299 static int
300 vhost_user_set_vring_addr(struct virtio_net *dev, struct vhost_vring_addr *addr)
301 {
302         struct vhost_virtqueue *vq;
303
304         if (dev->mem == NULL)
305                 return -1;
306
307         /* addr->index refers to the queue index. The txq 1, rxq is 0. */
308         vq = dev->virtqueue[addr->index];
309
310         /* The addresses are converted from QEMU virtual to Vhost virtual. */
311         vq->desc = (struct vring_desc *)(uintptr_t)qva_to_vva(dev,
312                         addr->desc_user_addr);
313         if (vq->desc == 0) {
314                 RTE_LOG(ERR, VHOST_CONFIG,
315                         "(%d) failed to find desc ring address.\n",
316                         dev->vid);
317                 return -1;
318         }
319
320         dev = numa_realloc(dev, addr->index);
321         vq = dev->virtqueue[addr->index];
322
323         vq->avail = (struct vring_avail *)(uintptr_t)qva_to_vva(dev,
324                         addr->avail_user_addr);
325         if (vq->avail == 0) {
326                 RTE_LOG(ERR, VHOST_CONFIG,
327                         "(%d) failed to find avail ring address.\n",
328                         dev->vid);
329                 return -1;
330         }
331
332         vq->used = (struct vring_used *)(uintptr_t)qva_to_vva(dev,
333                         addr->used_user_addr);
334         if (vq->used == 0) {
335                 RTE_LOG(ERR, VHOST_CONFIG,
336                         "(%d) failed to find used ring address.\n",
337                         dev->vid);
338                 return -1;
339         }
340
341         if (vq->last_used_idx != vq->used->idx) {
342                 RTE_LOG(WARNING, VHOST_CONFIG,
343                         "last_used_idx (%u) and vq->used->idx (%u) mismatches; "
344                         "some packets maybe resent for Tx and dropped for Rx\n",
345                         vq->last_used_idx, vq->used->idx);
346                 vq->last_used_idx     = vq->used->idx;
347         }
348
349         vq->log_guest_addr = addr->log_guest_addr;
350
351         LOG_DEBUG(VHOST_CONFIG, "(%d) mapped address desc: %p\n",
352                         dev->vid, vq->desc);
353         LOG_DEBUG(VHOST_CONFIG, "(%d) mapped address avail: %p\n",
354                         dev->vid, vq->avail);
355         LOG_DEBUG(VHOST_CONFIG, "(%d) mapped address used: %p\n",
356                         dev->vid, vq->used);
357         LOG_DEBUG(VHOST_CONFIG, "(%d) log_guest_addr: %" PRIx64 "\n",
358                         dev->vid, vq->log_guest_addr);
359
360         return 0;
361 }
362
363 /*
364  * The virtio device sends us the available ring last used index.
365  */
366 static int
367 vhost_user_set_vring_base(struct virtio_net *dev,
368                           struct vhost_vring_state *state)
369 {
370         dev->virtqueue[state->index]->last_used_idx = state->num;
371
372         return 0;
373 }
374
375 static void
376 add_one_guest_page(struct virtio_net *dev, uint64_t guest_phys_addr,
377                    uint64_t host_phys_addr, uint64_t size)
378 {
379         struct guest_page *page, *last_page;
380
381         if (dev->nr_guest_pages == dev->max_guest_pages) {
382                 dev->max_guest_pages *= 2;
383                 dev->guest_pages = realloc(dev->guest_pages,
384                                         dev->max_guest_pages * sizeof(*page));
385         }
386
387         if (dev->nr_guest_pages > 0) {
388                 last_page = &dev->guest_pages[dev->nr_guest_pages - 1];
389                 /* merge if the two pages are continuous */
390                 if (host_phys_addr == last_page->host_phys_addr +
391                                       last_page->size) {
392                         last_page->size += size;
393                         return;
394                 }
395         }
396
397         page = &dev->guest_pages[dev->nr_guest_pages++];
398         page->guest_phys_addr = guest_phys_addr;
399         page->host_phys_addr  = host_phys_addr;
400         page->size = size;
401 }
402
403 static void
404 add_guest_pages(struct virtio_net *dev, struct virtio_memory_region *reg,
405                 uint64_t page_size)
406 {
407         uint64_t reg_size = reg->size;
408         uint64_t host_user_addr  = reg->host_user_addr;
409         uint64_t guest_phys_addr = reg->guest_phys_addr;
410         uint64_t host_phys_addr;
411         uint64_t size;
412
413         host_phys_addr = rte_mem_virt2phy((void *)(uintptr_t)host_user_addr);
414         size = page_size - (guest_phys_addr & (page_size - 1));
415         size = RTE_MIN(size, reg_size);
416
417         add_one_guest_page(dev, guest_phys_addr, host_phys_addr, size);
418         host_user_addr  += size;
419         guest_phys_addr += size;
420         reg_size -= size;
421
422         while (reg_size > 0) {
423                 host_phys_addr = rte_mem_virt2phy((void *)(uintptr_t)
424                                                   host_user_addr);
425                 add_one_guest_page(dev, guest_phys_addr, host_phys_addr,
426                                    page_size);
427
428                 host_user_addr  += page_size;
429                 guest_phys_addr += page_size;
430                 reg_size -= page_size;
431         }
432 }
433
434 #ifdef RTE_LIBRTE_VHOST_DEBUG
435 /* TODO: enable it only in debug mode? */
436 static void
437 dump_guest_pages(struct virtio_net *dev)
438 {
439         uint32_t i;
440         struct guest_page *page;
441
442         for (i = 0; i < dev->nr_guest_pages; i++) {
443                 page = &dev->guest_pages[i];
444
445                 RTE_LOG(INFO, VHOST_CONFIG,
446                         "guest physical page region %u\n"
447                         "\t guest_phys_addr: %" PRIx64 "\n"
448                         "\t host_phys_addr : %" PRIx64 "\n"
449                         "\t size           : %" PRIx64 "\n",
450                         i,
451                         page->guest_phys_addr,
452                         page->host_phys_addr,
453                         page->size);
454         }
455 }
456 #else
457 #define dump_guest_pages(dev)
458 #endif
459
460 static int
461 vhost_user_set_mem_table(struct virtio_net *dev, struct VhostUserMsg *pmsg)
462 {
463         struct VhostUserMemory memory = pmsg->payload.memory;
464         struct virtio_memory_region *reg;
465         void *mmap_addr;
466         uint64_t mmap_size;
467         uint64_t mmap_offset;
468         uint64_t alignment;
469         uint32_t i;
470         int fd;
471
472         /* Remove from the data plane. */
473         if (dev->flags & VIRTIO_DEV_RUNNING) {
474                 dev->flags &= ~VIRTIO_DEV_RUNNING;
475                 notify_ops->destroy_device(dev->vid);
476         }
477
478         if (dev->mem) {
479                 free_mem_region(dev);
480                 rte_free(dev->mem);
481                 dev->mem = NULL;
482         }
483
484         dev->nr_guest_pages = 0;
485         if (!dev->guest_pages) {
486                 dev->max_guest_pages = 8;
487                 dev->guest_pages = malloc(dev->max_guest_pages *
488                                                 sizeof(struct guest_page));
489         }
490
491         dev->mem = rte_zmalloc("vhost-mem-table", sizeof(struct virtio_memory) +
492                 sizeof(struct virtio_memory_region) * memory.nregions, 0);
493         if (dev->mem == NULL) {
494                 RTE_LOG(ERR, VHOST_CONFIG,
495                         "(%d) failed to allocate memory for dev->mem\n",
496                         dev->vid);
497                 return -1;
498         }
499         dev->mem->nregions = memory.nregions;
500
501         for (i = 0; i < memory.nregions; i++) {
502                 fd  = pmsg->fds[i];
503                 reg = &dev->mem->regions[i];
504
505                 reg->guest_phys_addr = memory.regions[i].guest_phys_addr;
506                 reg->guest_user_addr = memory.regions[i].userspace_addr;
507                 reg->size            = memory.regions[i].memory_size;
508                 reg->fd              = fd;
509
510                 mmap_offset = memory.regions[i].mmap_offset;
511                 mmap_size   = reg->size + mmap_offset;
512
513                 /* mmap() without flag of MAP_ANONYMOUS, should be called
514                  * with length argument aligned with hugepagesz at older
515                  * longterm version Linux, like 2.6.32 and 3.2.72, or
516                  * mmap() will fail with EINVAL.
517                  *
518                  * to avoid failure, make sure in caller to keep length
519                  * aligned.
520                  */
521                 alignment = get_blk_size(fd);
522                 if (alignment == (uint64_t)-1) {
523                         RTE_LOG(ERR, VHOST_CONFIG,
524                                 "couldn't get hugepage size through fstat\n");
525                         goto err_mmap;
526                 }
527                 mmap_size = RTE_ALIGN_CEIL(mmap_size, alignment);
528
529                 mmap_addr = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE,
530                                  MAP_SHARED | MAP_POPULATE, fd, 0);
531
532                 if (mmap_addr == MAP_FAILED) {
533                         RTE_LOG(ERR, VHOST_CONFIG,
534                                 "mmap region %u failed.\n", i);
535                         goto err_mmap;
536                 }
537
538                 reg->mmap_addr = mmap_addr;
539                 reg->mmap_size = mmap_size;
540                 reg->host_user_addr = (uint64_t)(uintptr_t)mmap_addr +
541                                       mmap_offset;
542
543                 add_guest_pages(dev, reg, alignment);
544
545                 RTE_LOG(INFO, VHOST_CONFIG,
546                         "guest memory region %u, size: 0x%" PRIx64 "\n"
547                         "\t guest physical addr: 0x%" PRIx64 "\n"
548                         "\t guest virtual  addr: 0x%" PRIx64 "\n"
549                         "\t host  virtual  addr: 0x%" PRIx64 "\n"
550                         "\t mmap addr : 0x%" PRIx64 "\n"
551                         "\t mmap size : 0x%" PRIx64 "\n"
552                         "\t mmap align: 0x%" PRIx64 "\n"
553                         "\t mmap off  : 0x%" PRIx64 "\n",
554                         i, reg->size,
555                         reg->guest_phys_addr,
556                         reg->guest_user_addr,
557                         reg->host_user_addr,
558                         (uint64_t)(uintptr_t)mmap_addr,
559                         mmap_size,
560                         alignment,
561                         mmap_offset);
562         }
563
564         dump_guest_pages(dev);
565
566         return 0;
567
568 err_mmap:
569         free_mem_region(dev);
570         rte_free(dev->mem);
571         dev->mem = NULL;
572         return -1;
573 }
574
575 static int
576 vq_is_ready(struct vhost_virtqueue *vq)
577 {
578         return vq && vq->desc   &&
579                vq->kickfd != VIRTIO_UNINITIALIZED_EVENTFD &&
580                vq->callfd != VIRTIO_UNINITIALIZED_EVENTFD;
581 }
582
583 static int
584 virtio_is_ready(struct virtio_net *dev)
585 {
586         struct vhost_virtqueue *rvq, *tvq;
587         uint32_t i;
588
589         for (i = 0; i < dev->virt_qp_nb; i++) {
590                 rvq = dev->virtqueue[i * VIRTIO_QNUM + VIRTIO_RXQ];
591                 tvq = dev->virtqueue[i * VIRTIO_QNUM + VIRTIO_TXQ];
592
593                 if (!vq_is_ready(rvq) || !vq_is_ready(tvq)) {
594                         RTE_LOG(INFO, VHOST_CONFIG,
595                                 "virtio is not ready for processing.\n");
596                         return 0;
597                 }
598         }
599
600         RTE_LOG(INFO, VHOST_CONFIG,
601                 "virtio is now ready for processing.\n");
602         return 1;
603 }
604
605 static void
606 vhost_user_set_vring_call(struct virtio_net *dev, struct VhostUserMsg *pmsg)
607 {
608         struct vhost_vring_file file;
609         struct vhost_virtqueue *vq;
610         uint32_t cur_qp_idx;
611
612         file.index = pmsg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
613         if (pmsg->payload.u64 & VHOST_USER_VRING_NOFD_MASK)
614                 file.fd = VIRTIO_INVALID_EVENTFD;
615         else
616                 file.fd = pmsg->fds[0];
617         RTE_LOG(INFO, VHOST_CONFIG,
618                 "vring call idx:%d file:%d\n", file.index, file.fd);
619
620         /*
621          * FIXME: VHOST_SET_VRING_CALL is the first per-vring message
622          * we get, so we do vring queue pair allocation here.
623          */
624         cur_qp_idx = file.index / VIRTIO_QNUM;
625         if (cur_qp_idx + 1 > dev->virt_qp_nb) {
626                 if (alloc_vring_queue_pair(dev, cur_qp_idx) < 0)
627                         return;
628         }
629
630         vq = dev->virtqueue[file.index];
631         assert(vq != NULL);
632
633         if (vq->callfd >= 0)
634                 close(vq->callfd);
635
636         vq->callfd = file.fd;
637 }
638
639 /*
640  *  In vhost-user, when we receive kick message, will test whether virtio
641  *  device is ready for packet processing.
642  */
643 static void
644 vhost_user_set_vring_kick(struct virtio_net *dev, struct VhostUserMsg *pmsg)
645 {
646         struct vhost_vring_file file;
647         struct vhost_virtqueue *vq;
648
649         file.index = pmsg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
650         if (pmsg->payload.u64 & VHOST_USER_VRING_NOFD_MASK)
651                 file.fd = VIRTIO_INVALID_EVENTFD;
652         else
653                 file.fd = pmsg->fds[0];
654         RTE_LOG(INFO, VHOST_CONFIG,
655                 "vring kick idx:%d file:%d\n", file.index, file.fd);
656
657         vq = dev->virtqueue[file.index];
658         if (vq->kickfd >= 0)
659                 close(vq->kickfd);
660         vq->kickfd = file.fd;
661
662         if (virtio_is_ready(dev) && !(dev->flags & VIRTIO_DEV_RUNNING)) {
663                 if (notify_ops->new_device(dev->vid) == 0)
664                         dev->flags |= VIRTIO_DEV_RUNNING;
665         }
666 }
667
668 /*
669  * when virtio is stopped, qemu will send us the GET_VRING_BASE message.
670  */
671 static int
672 vhost_user_get_vring_base(struct virtio_net *dev,
673                           struct vhost_vring_state *state)
674 {
675         /* We have to stop the queue (virtio) if it is running. */
676         if (dev->flags & VIRTIO_DEV_RUNNING) {
677                 dev->flags &= ~VIRTIO_DEV_RUNNING;
678                 notify_ops->destroy_device(dev->vid);
679         }
680
681         /* Here we are safe to get the last used index */
682         state->num = dev->virtqueue[state->index]->last_used_idx;
683
684         RTE_LOG(INFO, VHOST_CONFIG,
685                 "vring base idx:%d file:%d\n", state->index, state->num);
686         /*
687          * Based on current qemu vhost-user implementation, this message is
688          * sent and only sent in vhost_vring_stop.
689          * TODO: cleanup the vring, it isn't usable since here.
690          */
691         if (dev->virtqueue[state->index]->kickfd >= 0)
692                 close(dev->virtqueue[state->index]->kickfd);
693
694         dev->virtqueue[state->index]->kickfd = VIRTIO_UNINITIALIZED_EVENTFD;
695
696         return 0;
697 }
698
699 /*
700  * when virtio queues are ready to work, qemu will send us to
701  * enable the virtio queue pair.
702  */
703 static int
704 vhost_user_set_vring_enable(struct virtio_net *dev,
705                             struct vhost_vring_state *state)
706 {
707         int enable = (int)state->num;
708
709         RTE_LOG(INFO, VHOST_CONFIG,
710                 "set queue enable: %d to qp idx: %d\n",
711                 enable, state->index);
712
713         if (notify_ops->vring_state_changed)
714                 notify_ops->vring_state_changed(dev->vid, state->index, enable);
715
716         dev->virtqueue[state->index]->enabled = enable;
717
718         return 0;
719 }
720
721 static void
722 vhost_user_set_protocol_features(struct virtio_net *dev,
723                                  uint64_t protocol_features)
724 {
725         if (protocol_features & ~VHOST_USER_PROTOCOL_FEATURES)
726                 return;
727
728         dev->protocol_features = protocol_features;
729 }
730
731 static int
732 vhost_user_set_log_base(struct virtio_net *dev, struct VhostUserMsg *msg)
733 {
734         int fd = msg->fds[0];
735         uint64_t size, off;
736         void *addr;
737
738         if (fd < 0) {
739                 RTE_LOG(ERR, VHOST_CONFIG, "invalid log fd: %d\n", fd);
740                 return -1;
741         }
742
743         if (msg->size != sizeof(VhostUserLog)) {
744                 RTE_LOG(ERR, VHOST_CONFIG,
745                         "invalid log base msg size: %"PRId32" != %d\n",
746                         msg->size, (int)sizeof(VhostUserLog));
747                 return -1;
748         }
749
750         size = msg->payload.log.mmap_size;
751         off  = msg->payload.log.mmap_offset;
752         RTE_LOG(INFO, VHOST_CONFIG,
753                 "log mmap size: %"PRId64", offset: %"PRId64"\n",
754                 size, off);
755
756         /*
757          * mmap from 0 to workaround a hugepage mmap bug: mmap will
758          * fail when offset is not page size aligned.
759          */
760         addr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
761         close(fd);
762         if (addr == MAP_FAILED) {
763                 RTE_LOG(ERR, VHOST_CONFIG, "mmap log base failed!\n");
764                 return -1;
765         }
766
767         /*
768          * Free previously mapped log memory on occasionally
769          * multiple VHOST_USER_SET_LOG_BASE.
770          */
771         if (dev->log_addr) {
772                 munmap((void *)(uintptr_t)dev->log_addr, dev->log_size);
773         }
774         dev->log_addr = (uint64_t)(uintptr_t)addr;
775         dev->log_base = dev->log_addr + off;
776         dev->log_size = size;
777
778         return 0;
779 }
780
781 /*
782  * An rarp packet is constructed and broadcasted to notify switches about
783  * the new location of the migrated VM, so that packets from outside will
784  * not be lost after migration.
785  *
786  * However, we don't actually "send" a rarp packet here, instead, we set
787  * a flag 'broadcast_rarp' to let rte_vhost_dequeue_burst() inject it.
788  */
789 static int
790 vhost_user_send_rarp(struct virtio_net *dev, struct VhostUserMsg *msg)
791 {
792         uint8_t *mac = (uint8_t *)&msg->payload.u64;
793
794         RTE_LOG(DEBUG, VHOST_CONFIG,
795                 ":: mac: %02x:%02x:%02x:%02x:%02x:%02x\n",
796                 mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
797         memcpy(dev->mac.addr_bytes, mac, 6);
798
799         /*
800          * Set the flag to inject a RARP broadcast packet at
801          * rte_vhost_dequeue_burst().
802          *
803          * rte_smp_wmb() is for making sure the mac is copied
804          * before the flag is set.
805          */
806         rte_smp_wmb();
807         rte_atomic16_set(&dev->broadcast_rarp, 1);
808
809         return 0;
810 }
811
812 /* return bytes# of read on success or negative val on failure. */
813 static int
814 read_vhost_message(int sockfd, struct VhostUserMsg *msg)
815 {
816         int ret;
817
818         ret = read_fd_message(sockfd, (char *)msg, VHOST_USER_HDR_SIZE,
819                 msg->fds, VHOST_MEMORY_MAX_NREGIONS);
820         if (ret <= 0)
821                 return ret;
822
823         if (msg && msg->size) {
824                 if (msg->size > sizeof(msg->payload)) {
825                         RTE_LOG(ERR, VHOST_CONFIG,
826                                 "invalid msg size: %d\n", msg->size);
827                         return -1;
828                 }
829                 ret = read(sockfd, &msg->payload, msg->size);
830                 if (ret <= 0)
831                         return ret;
832                 if (ret != (int)msg->size) {
833                         RTE_LOG(ERR, VHOST_CONFIG,
834                                 "read control message failed\n");
835                         return -1;
836                 }
837         }
838
839         return ret;
840 }
841
842 static int
843 send_vhost_message(int sockfd, struct VhostUserMsg *msg)
844 {
845         int ret;
846
847         if (!msg)
848                 return 0;
849
850         msg->flags &= ~VHOST_USER_VERSION_MASK;
851         msg->flags |= VHOST_USER_VERSION;
852         msg->flags |= VHOST_USER_REPLY_MASK;
853
854         ret = send_fd_message(sockfd, (char *)msg,
855                 VHOST_USER_HDR_SIZE + msg->size, NULL, 0);
856
857         return ret;
858 }
859
860 int
861 vhost_user_msg_handler(int vid, int fd)
862 {
863         struct virtio_net *dev;
864         struct VhostUserMsg msg;
865         int ret;
866
867         dev = get_device(vid);
868         if (dev == NULL)
869                 return -1;
870
871         ret = read_vhost_message(fd, &msg);
872         if (ret <= 0 || msg.request >= VHOST_USER_MAX) {
873                 if (ret < 0)
874                         RTE_LOG(ERR, VHOST_CONFIG,
875                                 "vhost read message failed\n");
876                 else if (ret == 0)
877                         RTE_LOG(INFO, VHOST_CONFIG,
878                                 "vhost peer closed\n");
879                 else
880                         RTE_LOG(ERR, VHOST_CONFIG,
881                                 "vhost read incorrect message\n");
882
883                 return -1;
884         }
885
886         RTE_LOG(INFO, VHOST_CONFIG, "read message %s\n",
887                 vhost_message_str[msg.request]);
888         switch (msg.request) {
889         case VHOST_USER_GET_FEATURES:
890                 msg.payload.u64 = vhost_user_get_features();
891                 msg.size = sizeof(msg.payload.u64);
892                 send_vhost_message(fd, &msg);
893                 break;
894         case VHOST_USER_SET_FEATURES:
895                 vhost_user_set_features(dev, msg.payload.u64);
896                 break;
897
898         case VHOST_USER_GET_PROTOCOL_FEATURES:
899                 msg.payload.u64 = VHOST_USER_PROTOCOL_FEATURES;
900                 msg.size = sizeof(msg.payload.u64);
901                 send_vhost_message(fd, &msg);
902                 break;
903         case VHOST_USER_SET_PROTOCOL_FEATURES:
904                 vhost_user_set_protocol_features(dev, msg.payload.u64);
905                 break;
906
907         case VHOST_USER_SET_OWNER:
908                 vhost_user_set_owner();
909                 break;
910         case VHOST_USER_RESET_OWNER:
911                 vhost_user_reset_owner(dev);
912                 break;
913
914         case VHOST_USER_SET_MEM_TABLE:
915                 vhost_user_set_mem_table(dev, &msg);
916                 break;
917
918         case VHOST_USER_SET_LOG_BASE:
919                 vhost_user_set_log_base(dev, &msg);
920
921                 /* it needs a reply */
922                 msg.size = sizeof(msg.payload.u64);
923                 send_vhost_message(fd, &msg);
924                 break;
925         case VHOST_USER_SET_LOG_FD:
926                 close(msg.fds[0]);
927                 RTE_LOG(INFO, VHOST_CONFIG, "not implemented.\n");
928                 break;
929
930         case VHOST_USER_SET_VRING_NUM:
931                 vhost_user_set_vring_num(dev, &msg.payload.state);
932                 break;
933         case VHOST_USER_SET_VRING_ADDR:
934                 vhost_user_set_vring_addr(dev, &msg.payload.addr);
935                 break;
936         case VHOST_USER_SET_VRING_BASE:
937                 vhost_user_set_vring_base(dev, &msg.payload.state);
938                 break;
939
940         case VHOST_USER_GET_VRING_BASE:
941                 ret = vhost_user_get_vring_base(dev, &msg.payload.state);
942                 msg.size = sizeof(msg.payload.state);
943                 send_vhost_message(fd, &msg);
944                 break;
945
946         case VHOST_USER_SET_VRING_KICK:
947                 vhost_user_set_vring_kick(dev, &msg);
948                 break;
949         case VHOST_USER_SET_VRING_CALL:
950                 vhost_user_set_vring_call(dev, &msg);
951                 break;
952
953         case VHOST_USER_SET_VRING_ERR:
954                 if (!(msg.payload.u64 & VHOST_USER_VRING_NOFD_MASK))
955                         close(msg.fds[0]);
956                 RTE_LOG(INFO, VHOST_CONFIG, "not implemented\n");
957                 break;
958
959         case VHOST_USER_GET_QUEUE_NUM:
960                 msg.payload.u64 = VHOST_MAX_QUEUE_PAIRS;
961                 msg.size = sizeof(msg.payload.u64);
962                 send_vhost_message(fd, &msg);
963                 break;
964
965         case VHOST_USER_SET_VRING_ENABLE:
966                 vhost_user_set_vring_enable(dev, &msg.payload.state);
967                 break;
968         case VHOST_USER_SEND_RARP:
969                 vhost_user_send_rarp(dev, &msg);
970                 break;
971
972         default:
973                 break;
974
975         }
976
977         return 0;
978 }