c08f506c1fc8090f02ae71d01e2c8ce369e8a0cd
[dpdk.git] / lib / librte_vhost / vhost_user.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2018 Intel Corporation
3  */
4
5 /* Security model
6  * --------------
7  * The vhost-user protocol connection is an external interface, so it must be
8  * robust against invalid inputs.
9  *
10  * This is important because the vhost-user master is only one step removed
11  * from the guest.  Malicious guests that have escaped will then launch further
12  * attacks from the vhost-user master.
13  *
14  * Even in deployments where guests are trusted, a bug in the vhost-user master
15  * can still cause invalid messages to be sent.  Such messages must not
16  * compromise the stability of the DPDK application by causing crashes, memory
17  * corruption, or other problematic behavior.
18  *
19  * Do not assume received VhostUserMsg fields contain sensible values!
20  */
21
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <sys/ioctl.h>
29 #include <sys/mman.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/syscall.h>
33 #include <assert.h>
34 #ifdef RTE_LIBRTE_VHOST_NUMA
35 #include <numaif.h>
36 #endif
37 #ifdef RTE_LIBRTE_VHOST_POSTCOPY
38 #include <linux/userfaultfd.h>
39 #endif
40 #ifdef F_ADD_SEALS /* if file sealing is supported, so is memfd */
41 #include <linux/memfd.h>
42 #define MEMFD_SUPPORTED
43 #endif
44
45 #include <rte_common.h>
46 #include <rte_malloc.h>
47 #include <rte_log.h>
48
49 #include "iotlb.h"
50 #include "vhost.h"
51 #include "vhost_user.h"
52
53 #define VIRTIO_MIN_MTU 68
54 #define VIRTIO_MAX_MTU 65535
55
56 #define INFLIGHT_ALIGNMENT      64
57 #define INFLIGHT_VERSION        0x1
58
59 static const char *vhost_message_str[VHOST_USER_MAX] = {
60         [VHOST_USER_NONE] = "VHOST_USER_NONE",
61         [VHOST_USER_GET_FEATURES] = "VHOST_USER_GET_FEATURES",
62         [VHOST_USER_SET_FEATURES] = "VHOST_USER_SET_FEATURES",
63         [VHOST_USER_SET_OWNER] = "VHOST_USER_SET_OWNER",
64         [VHOST_USER_RESET_OWNER] = "VHOST_USER_RESET_OWNER",
65         [VHOST_USER_SET_MEM_TABLE] = "VHOST_USER_SET_MEM_TABLE",
66         [VHOST_USER_SET_LOG_BASE] = "VHOST_USER_SET_LOG_BASE",
67         [VHOST_USER_SET_LOG_FD] = "VHOST_USER_SET_LOG_FD",
68         [VHOST_USER_SET_VRING_NUM] = "VHOST_USER_SET_VRING_NUM",
69         [VHOST_USER_SET_VRING_ADDR] = "VHOST_USER_SET_VRING_ADDR",
70         [VHOST_USER_SET_VRING_BASE] = "VHOST_USER_SET_VRING_BASE",
71         [VHOST_USER_GET_VRING_BASE] = "VHOST_USER_GET_VRING_BASE",
72         [VHOST_USER_SET_VRING_KICK] = "VHOST_USER_SET_VRING_KICK",
73         [VHOST_USER_SET_VRING_CALL] = "VHOST_USER_SET_VRING_CALL",
74         [VHOST_USER_SET_VRING_ERR]  = "VHOST_USER_SET_VRING_ERR",
75         [VHOST_USER_GET_PROTOCOL_FEATURES]  = "VHOST_USER_GET_PROTOCOL_FEATURES",
76         [VHOST_USER_SET_PROTOCOL_FEATURES]  = "VHOST_USER_SET_PROTOCOL_FEATURES",
77         [VHOST_USER_GET_QUEUE_NUM]  = "VHOST_USER_GET_QUEUE_NUM",
78         [VHOST_USER_SET_VRING_ENABLE]  = "VHOST_USER_SET_VRING_ENABLE",
79         [VHOST_USER_SEND_RARP]  = "VHOST_USER_SEND_RARP",
80         [VHOST_USER_NET_SET_MTU]  = "VHOST_USER_NET_SET_MTU",
81         [VHOST_USER_SET_SLAVE_REQ_FD]  = "VHOST_USER_SET_SLAVE_REQ_FD",
82         [VHOST_USER_IOTLB_MSG]  = "VHOST_USER_IOTLB_MSG",
83         [VHOST_USER_CRYPTO_CREATE_SESS] = "VHOST_USER_CRYPTO_CREATE_SESS",
84         [VHOST_USER_CRYPTO_CLOSE_SESS] = "VHOST_USER_CRYPTO_CLOSE_SESS",
85         [VHOST_USER_POSTCOPY_ADVISE]  = "VHOST_USER_POSTCOPY_ADVISE",
86         [VHOST_USER_POSTCOPY_LISTEN]  = "VHOST_USER_POSTCOPY_LISTEN",
87         [VHOST_USER_POSTCOPY_END]  = "VHOST_USER_POSTCOPY_END",
88         [VHOST_USER_GET_INFLIGHT_FD] = "VHOST_USER_GET_INFLIGHT_FD",
89         [VHOST_USER_SET_INFLIGHT_FD] = "VHOST_USER_SET_INFLIGHT_FD",
90 };
91
92 static int send_vhost_reply(int sockfd, struct VhostUserMsg *msg);
93 static int read_vhost_message(int sockfd, struct VhostUserMsg *msg);
94
95 static void
96 close_msg_fds(struct VhostUserMsg *msg)
97 {
98         int i;
99
100         for (i = 0; i < msg->fd_num; i++)
101                 close(msg->fds[i]);
102 }
103
104 /*
105  * Ensure the expected number of FDs is received,
106  * close all FDs and return an error if this is not the case.
107  */
108 static int
109 validate_msg_fds(struct VhostUserMsg *msg, int expected_fds)
110 {
111         if (msg->fd_num == expected_fds)
112                 return 0;
113
114         VHOST_LOG_CONFIG(ERR,
115                 " Expect %d FDs for request %s, received %d\n",
116                 expected_fds,
117                 vhost_message_str[msg->request.master],
118                 msg->fd_num);
119
120         close_msg_fds(msg);
121
122         return -1;
123 }
124
125 static uint64_t
126 get_blk_size(int fd)
127 {
128         struct stat stat;
129         int ret;
130
131         ret = fstat(fd, &stat);
132         return ret == -1 ? (uint64_t)-1 : (uint64_t)stat.st_blksize;
133 }
134
135 /*
136  * Reclaim all the outstanding zmbufs for a virtqueue.
137  */
138 static void
139 drain_zmbuf_list(struct vhost_virtqueue *vq)
140 {
141         struct zcopy_mbuf *zmbuf, *next;
142
143         for (zmbuf = TAILQ_FIRST(&vq->zmbuf_list);
144              zmbuf != NULL; zmbuf = next) {
145                 next = TAILQ_NEXT(zmbuf, next);
146
147                 while (!mbuf_is_consumed(zmbuf->mbuf))
148                         usleep(1000);
149
150                 TAILQ_REMOVE(&vq->zmbuf_list, zmbuf, next);
151                 restore_mbuf(zmbuf->mbuf);
152                 rte_pktmbuf_free(zmbuf->mbuf);
153                 put_zmbuf(zmbuf);
154                 vq->nr_zmbuf -= 1;
155         }
156 }
157
158 static void
159 free_mem_region(struct virtio_net *dev)
160 {
161         uint32_t i;
162         struct rte_vhost_mem_region *reg;
163         struct vhost_virtqueue *vq;
164
165         if (!dev || !dev->mem)
166                 return;
167
168         if (dev->dequeue_zero_copy) {
169                 for (i = 0; i < dev->nr_vring; i++) {
170                         vq = dev->virtqueue[i];
171                         if (vq)
172                                 drain_zmbuf_list(vq);
173                 }
174         }
175
176         for (i = 0; i < dev->mem->nregions; i++) {
177                 reg = &dev->mem->regions[i];
178                 if (reg->host_user_addr) {
179                         munmap(reg->mmap_addr, reg->mmap_size);
180                         close(reg->fd);
181                 }
182         }
183 }
184
185 void
186 vhost_backend_cleanup(struct virtio_net *dev)
187 {
188         if (dev->mem) {
189                 free_mem_region(dev);
190                 rte_free(dev->mem);
191                 dev->mem = NULL;
192         }
193
194         rte_free(dev->guest_pages);
195         dev->guest_pages = NULL;
196
197         if (dev->log_addr) {
198                 munmap((void *)(uintptr_t)dev->log_addr, dev->log_size);
199                 dev->log_addr = 0;
200         }
201
202         if (dev->inflight_info) {
203                 if (dev->inflight_info->addr) {
204                         munmap(dev->inflight_info->addr,
205                                dev->inflight_info->size);
206                         dev->inflight_info->addr = NULL;
207                 }
208
209                 if (dev->inflight_info->fd >= 0) {
210                         close(dev->inflight_info->fd);
211                         dev->inflight_info->fd = -1;
212                 }
213
214                 free(dev->inflight_info);
215                 dev->inflight_info = NULL;
216         }
217
218         if (dev->slave_req_fd >= 0) {
219                 close(dev->slave_req_fd);
220                 dev->slave_req_fd = -1;
221         }
222
223         if (dev->postcopy_ufd >= 0) {
224                 close(dev->postcopy_ufd);
225                 dev->postcopy_ufd = -1;
226         }
227
228         dev->postcopy_listening = 0;
229 }
230
231 /*
232  * This function just returns success at the moment unless
233  * the device hasn't been initialised.
234  */
235 static int
236 vhost_user_set_owner(struct virtio_net **pdev __rte_unused,
237                         struct VhostUserMsg *msg,
238                         int main_fd __rte_unused)
239 {
240         if (validate_msg_fds(msg, 0) != 0)
241                 return RTE_VHOST_MSG_RESULT_ERR;
242
243         return RTE_VHOST_MSG_RESULT_OK;
244 }
245
246 static int
247 vhost_user_reset_owner(struct virtio_net **pdev,
248                         struct VhostUserMsg *msg,
249                         int main_fd __rte_unused)
250 {
251         struct virtio_net *dev = *pdev;
252
253         if (validate_msg_fds(msg, 0) != 0)
254                 return RTE_VHOST_MSG_RESULT_ERR;
255
256         vhost_destroy_device_notify(dev);
257
258         cleanup_device(dev, 0);
259         reset_device(dev);
260         return RTE_VHOST_MSG_RESULT_OK;
261 }
262
263 /*
264  * The features that we support are requested.
265  */
266 static int
267 vhost_user_get_features(struct virtio_net **pdev, struct VhostUserMsg *msg,
268                         int main_fd __rte_unused)
269 {
270         struct virtio_net *dev = *pdev;
271         uint64_t features = 0;
272
273         if (validate_msg_fds(msg, 0) != 0)
274                 return RTE_VHOST_MSG_RESULT_ERR;
275
276         rte_vhost_driver_get_features(dev->ifname, &features);
277
278         msg->payload.u64 = features;
279         msg->size = sizeof(msg->payload.u64);
280         msg->fd_num = 0;
281
282         return RTE_VHOST_MSG_RESULT_REPLY;
283 }
284
285 /*
286  * The queue number that we support are requested.
287  */
288 static int
289 vhost_user_get_queue_num(struct virtio_net **pdev, struct VhostUserMsg *msg,
290                         int main_fd __rte_unused)
291 {
292         struct virtio_net *dev = *pdev;
293         uint32_t queue_num = 0;
294
295         if (validate_msg_fds(msg, 0) != 0)
296                 return RTE_VHOST_MSG_RESULT_ERR;
297
298         rte_vhost_driver_get_queue_num(dev->ifname, &queue_num);
299
300         msg->payload.u64 = (uint64_t)queue_num;
301         msg->size = sizeof(msg->payload.u64);
302         msg->fd_num = 0;
303
304         return RTE_VHOST_MSG_RESULT_REPLY;
305 }
306
307 /*
308  * We receive the negotiated features supported by us and the virtio device.
309  */
310 static int
311 vhost_user_set_features(struct virtio_net **pdev, struct VhostUserMsg *msg,
312                         int main_fd __rte_unused)
313 {
314         struct virtio_net *dev = *pdev;
315         uint64_t features = msg->payload.u64;
316         uint64_t vhost_features = 0;
317         struct rte_vdpa_device *vdpa_dev;
318
319         if (validate_msg_fds(msg, 0) != 0)
320                 return RTE_VHOST_MSG_RESULT_ERR;
321
322         rte_vhost_driver_get_features(dev->ifname, &vhost_features);
323         if (features & ~vhost_features) {
324                 VHOST_LOG_CONFIG(ERR,
325                         "(%d) received invalid negotiated features.\n",
326                         dev->vid);
327                 return RTE_VHOST_MSG_RESULT_ERR;
328         }
329
330         if (dev->flags & VIRTIO_DEV_RUNNING) {
331                 if (dev->features == features)
332                         return RTE_VHOST_MSG_RESULT_OK;
333
334                 /*
335                  * Error out if master tries to change features while device is
336                  * in running state. The exception being VHOST_F_LOG_ALL, which
337                  * is enabled when the live-migration starts.
338                  */
339                 if ((dev->features ^ features) & ~(1ULL << VHOST_F_LOG_ALL)) {
340                         VHOST_LOG_CONFIG(ERR,
341                                 "(%d) features changed while device is running.\n",
342                                 dev->vid);
343                         return RTE_VHOST_MSG_RESULT_ERR;
344                 }
345
346                 if (dev->notify_ops->features_changed)
347                         dev->notify_ops->features_changed(dev->vid, features);
348         }
349
350         dev->features = features;
351         if (dev->features &
352                 ((1 << VIRTIO_NET_F_MRG_RXBUF) | (1ULL << VIRTIO_F_VERSION_1))) {
353                 dev->vhost_hlen = sizeof(struct virtio_net_hdr_mrg_rxbuf);
354         } else {
355                 dev->vhost_hlen = sizeof(struct virtio_net_hdr);
356         }
357         VHOST_LOG_CONFIG(INFO,
358                 "negotiated Virtio features: 0x%" PRIx64 "\n", dev->features);
359         VHOST_LOG_CONFIG(DEBUG,
360                 "(%d) mergeable RX buffers %s, virtio 1 %s\n",
361                 dev->vid,
362                 (dev->features & (1 << VIRTIO_NET_F_MRG_RXBUF)) ? "on" : "off",
363                 (dev->features & (1ULL << VIRTIO_F_VERSION_1)) ? "on" : "off");
364
365         if ((dev->flags & VIRTIO_DEV_BUILTIN_VIRTIO_NET) &&
366             !(dev->features & (1ULL << VIRTIO_NET_F_MQ))) {
367                 /*
368                  * Remove all but first queue pair if MQ hasn't been
369                  * negotiated. This is safe because the device is not
370                  * running at this stage.
371                  */
372                 while (dev->nr_vring > 2) {
373                         struct vhost_virtqueue *vq;
374
375                         vq = dev->virtqueue[--dev->nr_vring];
376                         if (!vq)
377                                 continue;
378
379                         dev->virtqueue[dev->nr_vring] = NULL;
380                         cleanup_vq(vq, 1);
381                         cleanup_vq_inflight(dev, vq);
382                         free_vq(dev, vq);
383                 }
384         }
385
386         vdpa_dev = dev->vdpa_dev;
387         if (vdpa_dev && vdpa_dev->ops->set_features)
388                 vdpa_dev->ops->set_features(dev->vid);
389
390         return RTE_VHOST_MSG_RESULT_OK;
391 }
392
393 /*
394  * The virtio device sends us the size of the descriptor ring.
395  */
396 static int
397 vhost_user_set_vring_num(struct virtio_net **pdev,
398                         struct VhostUserMsg *msg,
399                         int main_fd __rte_unused)
400 {
401         struct virtio_net *dev = *pdev;
402         struct vhost_virtqueue *vq = dev->virtqueue[msg->payload.state.index];
403
404         if (validate_msg_fds(msg, 0) != 0)
405                 return RTE_VHOST_MSG_RESULT_ERR;
406
407         vq->size = msg->payload.state.num;
408
409         /* VIRTIO 1.0, 2.4 Virtqueues says:
410          *
411          *   Queue Size value is always a power of 2. The maximum Queue Size
412          *   value is 32768.
413          *
414          * VIRTIO 1.1 2.7 Virtqueues says:
415          *
416          *   Packed virtqueues support up to 2^15 entries each.
417          */
418         if (!vq_is_packed(dev)) {
419                 if (vq->size & (vq->size - 1)) {
420                         VHOST_LOG_CONFIG(ERR,
421                                 "invalid virtqueue size %u\n", vq->size);
422                         return RTE_VHOST_MSG_RESULT_ERR;
423                 }
424         }
425
426         if (vq->size > 32768) {
427                 VHOST_LOG_CONFIG(ERR,
428                         "invalid virtqueue size %u\n", vq->size);
429                 return RTE_VHOST_MSG_RESULT_ERR;
430         }
431
432         if (dev->dequeue_zero_copy) {
433                 vq->nr_zmbuf = 0;
434                 vq->last_zmbuf_idx = 0;
435                 vq->zmbuf_size = vq->size;
436                 if (vq->zmbufs)
437                         rte_free(vq->zmbufs);
438                 vq->zmbufs = rte_zmalloc(NULL, vq->zmbuf_size *
439                                          sizeof(struct zcopy_mbuf), 0);
440                 if (vq->zmbufs == NULL) {
441                         VHOST_LOG_CONFIG(WARNING,
442                                 "failed to allocate mem for zero copy; "
443                                 "zero copy is force disabled\n");
444                         dev->dequeue_zero_copy = 0;
445                 }
446                 TAILQ_INIT(&vq->zmbuf_list);
447         }
448
449         if (vq_is_packed(dev)) {
450                 if (vq->shadow_used_packed)
451                         rte_free(vq->shadow_used_packed);
452                 vq->shadow_used_packed = rte_malloc(NULL,
453                                 vq->size *
454                                 sizeof(struct vring_used_elem_packed),
455                                 RTE_CACHE_LINE_SIZE);
456                 if (!vq->shadow_used_packed) {
457                         VHOST_LOG_CONFIG(ERR,
458                                         "failed to allocate memory for shadow used ring.\n");
459                         return RTE_VHOST_MSG_RESULT_ERR;
460                 }
461
462         } else {
463                 if (vq->shadow_used_split)
464                         rte_free(vq->shadow_used_split);
465                 vq->shadow_used_split = rte_malloc(NULL,
466                                 vq->size * sizeof(struct vring_used_elem),
467                                 RTE_CACHE_LINE_SIZE);
468                 if (!vq->shadow_used_split) {
469                         VHOST_LOG_CONFIG(ERR,
470                                         "failed to allocate memory for shadow used ring.\n");
471                         return RTE_VHOST_MSG_RESULT_ERR;
472                 }
473         }
474
475         if (vq->batch_copy_elems)
476                 rte_free(vq->batch_copy_elems);
477         vq->batch_copy_elems = rte_malloc(NULL,
478                                 vq->size * sizeof(struct batch_copy_elem),
479                                 RTE_CACHE_LINE_SIZE);
480         if (!vq->batch_copy_elems) {
481                 VHOST_LOG_CONFIG(ERR,
482                         "failed to allocate memory for batching copy.\n");
483                 return RTE_VHOST_MSG_RESULT_ERR;
484         }
485
486         return RTE_VHOST_MSG_RESULT_OK;
487 }
488
489 /*
490  * Reallocate virtio_dev and vhost_virtqueue data structure to make them on the
491  * same numa node as the memory of vring descriptor.
492  */
493 #ifdef RTE_LIBRTE_VHOST_NUMA
494 static struct virtio_net*
495 numa_realloc(struct virtio_net *dev, int index)
496 {
497         int oldnode, newnode;
498         struct virtio_net *old_dev;
499         struct vhost_virtqueue *old_vq, *vq;
500         struct zcopy_mbuf *new_zmbuf;
501         struct vring_used_elem *new_shadow_used_split;
502         struct vring_used_elem_packed *new_shadow_used_packed;
503         struct batch_copy_elem *new_batch_copy_elems;
504         int ret;
505
506         if (dev->flags & VIRTIO_DEV_RUNNING)
507                 return dev;
508
509         old_dev = dev;
510         vq = old_vq = dev->virtqueue[index];
511
512         ret = get_mempolicy(&newnode, NULL, 0, old_vq->desc,
513                             MPOL_F_NODE | MPOL_F_ADDR);
514
515         /* check if we need to reallocate vq */
516         ret |= get_mempolicy(&oldnode, NULL, 0, old_vq,
517                              MPOL_F_NODE | MPOL_F_ADDR);
518         if (ret) {
519                 VHOST_LOG_CONFIG(ERR,
520                         "Unable to get vq numa information.\n");
521                 return dev;
522         }
523         if (oldnode != newnode) {
524                 VHOST_LOG_CONFIG(INFO,
525                         "reallocate vq from %d to %d node\n", oldnode, newnode);
526                 vq = rte_malloc_socket(NULL, sizeof(*vq), 0, newnode);
527                 if (!vq)
528                         return dev;
529
530                 memcpy(vq, old_vq, sizeof(*vq));
531                 TAILQ_INIT(&vq->zmbuf_list);
532
533                 if (dev->dequeue_zero_copy) {
534                         new_zmbuf = rte_malloc_socket(NULL, vq->zmbuf_size *
535                                         sizeof(struct zcopy_mbuf), 0, newnode);
536                         if (new_zmbuf) {
537                                 rte_free(vq->zmbufs);
538                                 vq->zmbufs = new_zmbuf;
539                         }
540                 }
541
542                 if (vq_is_packed(dev)) {
543                         new_shadow_used_packed = rte_malloc_socket(NULL,
544                                         vq->size *
545                                         sizeof(struct vring_used_elem_packed),
546                                         RTE_CACHE_LINE_SIZE,
547                                         newnode);
548                         if (new_shadow_used_packed) {
549                                 rte_free(vq->shadow_used_packed);
550                                 vq->shadow_used_packed = new_shadow_used_packed;
551                         }
552                 } else {
553                         new_shadow_used_split = rte_malloc_socket(NULL,
554                                         vq->size *
555                                         sizeof(struct vring_used_elem),
556                                         RTE_CACHE_LINE_SIZE,
557                                         newnode);
558                         if (new_shadow_used_split) {
559                                 rte_free(vq->shadow_used_split);
560                                 vq->shadow_used_split = new_shadow_used_split;
561                         }
562                 }
563
564                 new_batch_copy_elems = rte_malloc_socket(NULL,
565                         vq->size * sizeof(struct batch_copy_elem),
566                         RTE_CACHE_LINE_SIZE,
567                         newnode);
568                 if (new_batch_copy_elems) {
569                         rte_free(vq->batch_copy_elems);
570                         vq->batch_copy_elems = new_batch_copy_elems;
571                 }
572
573                 rte_free(old_vq);
574         }
575
576         /* check if we need to reallocate dev */
577         ret = get_mempolicy(&oldnode, NULL, 0, old_dev,
578                             MPOL_F_NODE | MPOL_F_ADDR);
579         if (ret) {
580                 VHOST_LOG_CONFIG(ERR,
581                         "Unable to get dev numa information.\n");
582                 goto out;
583         }
584         if (oldnode != newnode) {
585                 VHOST_LOG_CONFIG(INFO,
586                         "reallocate dev from %d to %d node\n",
587                         oldnode, newnode);
588                 dev = rte_malloc_socket(NULL, sizeof(*dev), 0, newnode);
589                 if (!dev) {
590                         dev = old_dev;
591                         goto out;
592                 }
593
594                 memcpy(dev, old_dev, sizeof(*dev));
595                 rte_free(old_dev);
596         }
597
598 out:
599         dev->virtqueue[index] = vq;
600         vhost_devices[dev->vid] = dev;
601
602         if (old_vq != vq)
603                 vhost_user_iotlb_init(dev, index);
604
605         return dev;
606 }
607 #else
608 static struct virtio_net*
609 numa_realloc(struct virtio_net *dev, int index __rte_unused)
610 {
611         return dev;
612 }
613 #endif
614
615 /* Converts QEMU virtual address to Vhost virtual address. */
616 static uint64_t
617 qva_to_vva(struct virtio_net *dev, uint64_t qva, uint64_t *len)
618 {
619         struct rte_vhost_mem_region *r;
620         uint32_t i;
621
622         if (unlikely(!dev || !dev->mem))
623                 goto out_error;
624
625         /* Find the region where the address lives. */
626         for (i = 0; i < dev->mem->nregions; i++) {
627                 r = &dev->mem->regions[i];
628
629                 if (qva >= r->guest_user_addr &&
630                     qva <  r->guest_user_addr + r->size) {
631
632                         if (unlikely(*len > r->guest_user_addr + r->size - qva))
633                                 *len = r->guest_user_addr + r->size - qva;
634
635                         return qva - r->guest_user_addr +
636                                r->host_user_addr;
637                 }
638         }
639 out_error:
640         *len = 0;
641
642         return 0;
643 }
644
645
646 /*
647  * Converts ring address to Vhost virtual address.
648  * If IOMMU is enabled, the ring address is a guest IO virtual address,
649  * else it is a QEMU virtual address.
650  */
651 static uint64_t
652 ring_addr_to_vva(struct virtio_net *dev, struct vhost_virtqueue *vq,
653                 uint64_t ra, uint64_t *size)
654 {
655         if (dev->features & (1ULL << VIRTIO_F_IOMMU_PLATFORM)) {
656                 uint64_t vva;
657
658                 vhost_user_iotlb_rd_lock(vq);
659                 vva = vhost_iova_to_vva(dev, vq, ra,
660                                         size, VHOST_ACCESS_RW);
661                 vhost_user_iotlb_rd_unlock(vq);
662
663                 return vva;
664         }
665
666         return qva_to_vva(dev, ra, size);
667 }
668
669 static uint64_t
670 log_addr_to_gpa(struct virtio_net *dev, struct vhost_virtqueue *vq)
671 {
672         uint64_t log_gpa;
673
674         vhost_user_iotlb_rd_lock(vq);
675         log_gpa = translate_log_addr(dev, vq, vq->ring_addrs.log_guest_addr);
676         vhost_user_iotlb_rd_unlock(vq);
677
678         return log_gpa;
679 }
680
681 static struct virtio_net *
682 translate_ring_addresses(struct virtio_net *dev, int vq_index)
683 {
684         struct vhost_virtqueue *vq = dev->virtqueue[vq_index];
685         struct vhost_vring_addr *addr = &vq->ring_addrs;
686         uint64_t len, expected_len;
687
688         if (addr->flags & (1 << VHOST_VRING_F_LOG)) {
689                 vq->log_guest_addr =
690                         log_addr_to_gpa(dev, vq);
691                 if (vq->log_guest_addr == 0) {
692                         VHOST_LOG_CONFIG(DEBUG,
693                                 "(%d) failed to map log_guest_addr.\n",
694                                 dev->vid);
695                         return dev;
696                 }
697         }
698
699         if (vq_is_packed(dev)) {
700                 len = sizeof(struct vring_packed_desc) * vq->size;
701                 vq->desc_packed = (struct vring_packed_desc *)(uintptr_t)
702                         ring_addr_to_vva(dev, vq, addr->desc_user_addr, &len);
703                 if (vq->desc_packed == NULL ||
704                                 len != sizeof(struct vring_packed_desc) *
705                                 vq->size) {
706                         VHOST_LOG_CONFIG(DEBUG,
707                                 "(%d) failed to map desc_packed ring.\n",
708                                 dev->vid);
709                         return dev;
710                 }
711
712                 dev = numa_realloc(dev, vq_index);
713                 vq = dev->virtqueue[vq_index];
714                 addr = &vq->ring_addrs;
715
716                 len = sizeof(struct vring_packed_desc_event);
717                 vq->driver_event = (struct vring_packed_desc_event *)
718                                         (uintptr_t)ring_addr_to_vva(dev,
719                                         vq, addr->avail_user_addr, &len);
720                 if (vq->driver_event == NULL ||
721                                 len != sizeof(struct vring_packed_desc_event)) {
722                         VHOST_LOG_CONFIG(DEBUG,
723                                 "(%d) failed to find driver area address.\n",
724                                 dev->vid);
725                         return dev;
726                 }
727
728                 len = sizeof(struct vring_packed_desc_event);
729                 vq->device_event = (struct vring_packed_desc_event *)
730                                         (uintptr_t)ring_addr_to_vva(dev,
731                                         vq, addr->used_user_addr, &len);
732                 if (vq->device_event == NULL ||
733                                 len != sizeof(struct vring_packed_desc_event)) {
734                         VHOST_LOG_CONFIG(DEBUG,
735                                 "(%d) failed to find device area address.\n",
736                                 dev->vid);
737                         return dev;
738                 }
739
740                 vq->access_ok = 1;
741                 return dev;
742         }
743
744         /* The addresses are converted from QEMU virtual to Vhost virtual. */
745         if (vq->desc && vq->avail && vq->used)
746                 return dev;
747
748         len = sizeof(struct vring_desc) * vq->size;
749         vq->desc = (struct vring_desc *)(uintptr_t)ring_addr_to_vva(dev,
750                         vq, addr->desc_user_addr, &len);
751         if (vq->desc == 0 || len != sizeof(struct vring_desc) * vq->size) {
752                 VHOST_LOG_CONFIG(DEBUG,
753                         "(%d) failed to map desc ring.\n",
754                         dev->vid);
755                 return dev;
756         }
757
758         dev = numa_realloc(dev, vq_index);
759         vq = dev->virtqueue[vq_index];
760         addr = &vq->ring_addrs;
761
762         len = sizeof(struct vring_avail) + sizeof(uint16_t) * vq->size;
763         if (dev->features & (1ULL << VIRTIO_RING_F_EVENT_IDX))
764                 len += sizeof(uint16_t);
765         expected_len = len;
766         vq->avail = (struct vring_avail *)(uintptr_t)ring_addr_to_vva(dev,
767                         vq, addr->avail_user_addr, &len);
768         if (vq->avail == 0 || len != expected_len) {
769                 VHOST_LOG_CONFIG(DEBUG,
770                         "(%d) failed to map avail ring.\n",
771                         dev->vid);
772                 return dev;
773         }
774
775         len = sizeof(struct vring_used) +
776                 sizeof(struct vring_used_elem) * vq->size;
777         if (dev->features & (1ULL << VIRTIO_RING_F_EVENT_IDX))
778                 len += sizeof(uint16_t);
779         expected_len = len;
780         vq->used = (struct vring_used *)(uintptr_t)ring_addr_to_vva(dev,
781                         vq, addr->used_user_addr, &len);
782         if (vq->used == 0 || len != expected_len) {
783                 VHOST_LOG_CONFIG(DEBUG,
784                         "(%d) failed to map used ring.\n",
785                         dev->vid);
786                 return dev;
787         }
788
789         if (vq->last_used_idx != vq->used->idx) {
790                 VHOST_LOG_CONFIG(WARNING,
791                         "last_used_idx (%u) and vq->used->idx (%u) mismatches; "
792                         "some packets maybe resent for Tx and dropped for Rx\n",
793                         vq->last_used_idx, vq->used->idx);
794                 vq->last_used_idx  = vq->used->idx;
795                 vq->last_avail_idx = vq->used->idx;
796         }
797
798         vq->access_ok = 1;
799
800         VHOST_LOG_CONFIG(DEBUG, "(%d) mapped address desc: %p\n",
801                         dev->vid, vq->desc);
802         VHOST_LOG_CONFIG(DEBUG, "(%d) mapped address avail: %p\n",
803                         dev->vid, vq->avail);
804         VHOST_LOG_CONFIG(DEBUG, "(%d) mapped address used: %p\n",
805                         dev->vid, vq->used);
806         VHOST_LOG_CONFIG(DEBUG, "(%d) log_guest_addr: %" PRIx64 "\n",
807                         dev->vid, vq->log_guest_addr);
808
809         return dev;
810 }
811
812 /*
813  * The virtio device sends us the desc, used and avail ring addresses.
814  * This function then converts these to our address space.
815  */
816 static int
817 vhost_user_set_vring_addr(struct virtio_net **pdev, struct VhostUserMsg *msg,
818                         int main_fd __rte_unused)
819 {
820         struct virtio_net *dev = *pdev;
821         struct vhost_virtqueue *vq;
822         struct vhost_vring_addr *addr = &msg->payload.addr;
823         bool access_ok;
824
825         if (validate_msg_fds(msg, 0) != 0)
826                 return RTE_VHOST_MSG_RESULT_ERR;
827
828         if (dev->mem == NULL)
829                 return RTE_VHOST_MSG_RESULT_ERR;
830
831         /* addr->index refers to the queue index. The txq 1, rxq is 0. */
832         vq = dev->virtqueue[msg->payload.addr.index];
833
834         access_ok = vq->access_ok;
835
836         /*
837          * Rings addresses should not be interpreted as long as the ring is not
838          * started and enabled
839          */
840         memcpy(&vq->ring_addrs, addr, sizeof(*addr));
841
842         vring_invalidate(dev, vq);
843
844         if ((vq->enabled && (dev->features &
845                                 (1ULL << VHOST_USER_F_PROTOCOL_FEATURES))) ||
846                         access_ok) {
847                 dev = translate_ring_addresses(dev, msg->payload.addr.index);
848                 if (!dev)
849                         return RTE_VHOST_MSG_RESULT_ERR;
850
851                 *pdev = dev;
852         }
853
854         return RTE_VHOST_MSG_RESULT_OK;
855 }
856
857 /*
858  * The virtio device sends us the available ring last used index.
859  */
860 static int
861 vhost_user_set_vring_base(struct virtio_net **pdev,
862                         struct VhostUserMsg *msg,
863                         int main_fd __rte_unused)
864 {
865         struct virtio_net *dev = *pdev;
866         struct vhost_virtqueue *vq = dev->virtqueue[msg->payload.state.index];
867         uint64_t val = msg->payload.state.num;
868
869         if (validate_msg_fds(msg, 0) != 0)
870                 return RTE_VHOST_MSG_RESULT_ERR;
871
872         if (vq_is_packed(dev)) {
873                 /*
874                  * Bit[0:14]: avail index
875                  * Bit[15]: avail wrap counter
876                  */
877                 vq->last_avail_idx = val & 0x7fff;
878                 vq->avail_wrap_counter = !!(val & (0x1 << 15));
879                 /*
880                  * Set used index to same value as available one, as
881                  * their values should be the same since ring processing
882                  * was stopped at get time.
883                  */
884                 vq->last_used_idx = vq->last_avail_idx;
885                 vq->used_wrap_counter = vq->avail_wrap_counter;
886         } else {
887                 vq->last_used_idx = msg->payload.state.num;
888                 vq->last_avail_idx = msg->payload.state.num;
889         }
890
891         return RTE_VHOST_MSG_RESULT_OK;
892 }
893
894 static int
895 add_one_guest_page(struct virtio_net *dev, uint64_t guest_phys_addr,
896                    uint64_t host_phys_addr, uint64_t size)
897 {
898         struct guest_page *page, *last_page;
899         struct guest_page *old_pages;
900
901         if (dev->nr_guest_pages == dev->max_guest_pages) {
902                 dev->max_guest_pages *= 2;
903                 old_pages = dev->guest_pages;
904                 dev->guest_pages = rte_realloc(dev->guest_pages,
905                                         dev->max_guest_pages * sizeof(*page),
906                                         RTE_CACHE_LINE_SIZE);
907                 if (dev->guest_pages == NULL) {
908                         VHOST_LOG_CONFIG(ERR, "cannot realloc guest_pages\n");
909                         rte_free(old_pages);
910                         return -1;
911                 }
912         }
913
914         if (dev->nr_guest_pages > 0) {
915                 last_page = &dev->guest_pages[dev->nr_guest_pages - 1];
916                 /* merge if the two pages are continuous */
917                 if (host_phys_addr == last_page->host_phys_addr +
918                                       last_page->size) {
919                         last_page->size += size;
920                         return 0;
921                 }
922         }
923
924         page = &dev->guest_pages[dev->nr_guest_pages++];
925         page->guest_phys_addr = guest_phys_addr;
926         page->host_phys_addr  = host_phys_addr;
927         page->size = size;
928
929         return 0;
930 }
931
932 static int
933 add_guest_pages(struct virtio_net *dev, struct rte_vhost_mem_region *reg,
934                 uint64_t page_size)
935 {
936         uint64_t reg_size = reg->size;
937         uint64_t host_user_addr  = reg->host_user_addr;
938         uint64_t guest_phys_addr = reg->guest_phys_addr;
939         uint64_t host_phys_addr;
940         uint64_t size;
941
942         host_phys_addr = rte_mem_virt2iova((void *)(uintptr_t)host_user_addr);
943         size = page_size - (guest_phys_addr & (page_size - 1));
944         size = RTE_MIN(size, reg_size);
945
946         if (add_one_guest_page(dev, guest_phys_addr, host_phys_addr, size) < 0)
947                 return -1;
948
949         host_user_addr  += size;
950         guest_phys_addr += size;
951         reg_size -= size;
952
953         while (reg_size > 0) {
954                 size = RTE_MIN(reg_size, page_size);
955                 host_phys_addr = rte_mem_virt2iova((void *)(uintptr_t)
956                                                   host_user_addr);
957                 if (add_one_guest_page(dev, guest_phys_addr, host_phys_addr,
958                                 size) < 0)
959                         return -1;
960
961                 host_user_addr  += size;
962                 guest_phys_addr += size;
963                 reg_size -= size;
964         }
965
966         /* sort guest page array if over binary search threshold */
967         if (dev->nr_guest_pages >= VHOST_BINARY_SEARCH_THRESH) {
968                 qsort((void *)dev->guest_pages, dev->nr_guest_pages,
969                         sizeof(struct guest_page), guest_page_addrcmp);
970         }
971
972         return 0;
973 }
974
975 #ifdef RTE_LIBRTE_VHOST_DEBUG
976 /* TODO: enable it only in debug mode? */
977 static void
978 dump_guest_pages(struct virtio_net *dev)
979 {
980         uint32_t i;
981         struct guest_page *page;
982
983         for (i = 0; i < dev->nr_guest_pages; i++) {
984                 page = &dev->guest_pages[i];
985
986                 VHOST_LOG_CONFIG(INFO,
987                         "guest physical page region %u\n"
988                         "\t guest_phys_addr: %" PRIx64 "\n"
989                         "\t host_phys_addr : %" PRIx64 "\n"
990                         "\t size           : %" PRIx64 "\n",
991                         i,
992                         page->guest_phys_addr,
993                         page->host_phys_addr,
994                         page->size);
995         }
996 }
997 #else
998 #define dump_guest_pages(dev)
999 #endif
1000
1001 static bool
1002 vhost_memory_changed(struct VhostUserMemory *new,
1003                      struct rte_vhost_memory *old)
1004 {
1005         uint32_t i;
1006
1007         if (new->nregions != old->nregions)
1008                 return true;
1009
1010         for (i = 0; i < new->nregions; ++i) {
1011                 VhostUserMemoryRegion *new_r = &new->regions[i];
1012                 struct rte_vhost_mem_region *old_r = &old->regions[i];
1013
1014                 if (new_r->guest_phys_addr != old_r->guest_phys_addr)
1015                         return true;
1016                 if (new_r->memory_size != old_r->size)
1017                         return true;
1018                 if (new_r->userspace_addr != old_r->guest_user_addr)
1019                         return true;
1020         }
1021
1022         return false;
1023 }
1024
1025 static int
1026 vhost_user_set_mem_table(struct virtio_net **pdev, struct VhostUserMsg *msg,
1027                         int main_fd)
1028 {
1029         struct virtio_net *dev = *pdev;
1030         struct VhostUserMemory *memory = &msg->payload.memory;
1031         struct rte_vhost_mem_region *reg;
1032         void *mmap_addr;
1033         uint64_t mmap_size;
1034         uint64_t mmap_offset;
1035         uint64_t alignment;
1036         uint32_t i;
1037         int populate;
1038         int fd;
1039
1040         if (validate_msg_fds(msg, memory->nregions) != 0)
1041                 return RTE_VHOST_MSG_RESULT_ERR;
1042
1043         if (memory->nregions > VHOST_MEMORY_MAX_NREGIONS) {
1044                 VHOST_LOG_CONFIG(ERR,
1045                         "too many memory regions (%u)\n", memory->nregions);
1046                 return RTE_VHOST_MSG_RESULT_ERR;
1047         }
1048
1049         if (dev->mem && !vhost_memory_changed(memory, dev->mem)) {
1050                 VHOST_LOG_CONFIG(INFO,
1051                         "(%d) memory regions not changed\n", dev->vid);
1052
1053                 close_msg_fds(msg);
1054
1055                 return RTE_VHOST_MSG_RESULT_OK;
1056         }
1057
1058         if (dev->mem) {
1059                 free_mem_region(dev);
1060                 rte_free(dev->mem);
1061                 dev->mem = NULL;
1062         }
1063
1064         /* Flush IOTLB cache as previous HVAs are now invalid */
1065         if (dev->features & (1ULL << VIRTIO_F_IOMMU_PLATFORM))
1066                 for (i = 0; i < dev->nr_vring; i++)
1067                         vhost_user_iotlb_flush_all(dev->virtqueue[i]);
1068
1069         dev->nr_guest_pages = 0;
1070         if (dev->guest_pages == NULL) {
1071                 dev->max_guest_pages = 8;
1072                 dev->guest_pages = rte_zmalloc(NULL,
1073                                         dev->max_guest_pages *
1074                                         sizeof(struct guest_page),
1075                                         RTE_CACHE_LINE_SIZE);
1076                 if (dev->guest_pages == NULL) {
1077                         VHOST_LOG_CONFIG(ERR,
1078                                 "(%d) failed to allocate memory "
1079                                 "for dev->guest_pages\n",
1080                                 dev->vid);
1081                         return RTE_VHOST_MSG_RESULT_ERR;
1082                 }
1083         }
1084
1085         dev->mem = rte_zmalloc("vhost-mem-table", sizeof(struct rte_vhost_memory) +
1086                 sizeof(struct rte_vhost_mem_region) * memory->nregions, 0);
1087         if (dev->mem == NULL) {
1088                 VHOST_LOG_CONFIG(ERR,
1089                         "(%d) failed to allocate memory for dev->mem\n",
1090                         dev->vid);
1091                 return RTE_VHOST_MSG_RESULT_ERR;
1092         }
1093         dev->mem->nregions = memory->nregions;
1094
1095         for (i = 0; i < memory->nregions; i++) {
1096                 fd  = msg->fds[i];
1097                 reg = &dev->mem->regions[i];
1098
1099                 reg->guest_phys_addr = memory->regions[i].guest_phys_addr;
1100                 reg->guest_user_addr = memory->regions[i].userspace_addr;
1101                 reg->size            = memory->regions[i].memory_size;
1102                 reg->fd              = fd;
1103
1104                 mmap_offset = memory->regions[i].mmap_offset;
1105
1106                 /* Check for memory_size + mmap_offset overflow */
1107                 if (mmap_offset >= -reg->size) {
1108                         VHOST_LOG_CONFIG(ERR,
1109                                 "mmap_offset (%#"PRIx64") and memory_size "
1110                                 "(%#"PRIx64") overflow\n",
1111                                 mmap_offset, reg->size);
1112                         goto err_mmap;
1113                 }
1114
1115                 mmap_size = reg->size + mmap_offset;
1116
1117                 /* mmap() without flag of MAP_ANONYMOUS, should be called
1118                  * with length argument aligned with hugepagesz at older
1119                  * longterm version Linux, like 2.6.32 and 3.2.72, or
1120                  * mmap() will fail with EINVAL.
1121                  *
1122                  * to avoid failure, make sure in caller to keep length
1123                  * aligned.
1124                  */
1125                 alignment = get_blk_size(fd);
1126                 if (alignment == (uint64_t)-1) {
1127                         VHOST_LOG_CONFIG(ERR,
1128                                 "couldn't get hugepage size through fstat\n");
1129                         goto err_mmap;
1130                 }
1131                 mmap_size = RTE_ALIGN_CEIL(mmap_size, alignment);
1132                 if (mmap_size == 0) {
1133                         /*
1134                          * It could happen if initial mmap_size + alignment
1135                          * overflows the sizeof uint64, which could happen if
1136                          * either mmap_size or alignment value is wrong.
1137                          *
1138                          * mmap() kernel implementation would return an error,
1139                          * but better catch it before and provide useful info
1140                          * in the logs.
1141                          */
1142                         VHOST_LOG_CONFIG(ERR, "mmap size (0x%" PRIx64 ") "
1143                                         "or alignment (0x%" PRIx64 ") is invalid\n",
1144                                         reg->size + mmap_offset, alignment);
1145                         goto err_mmap;
1146                 }
1147
1148                 populate = (dev->dequeue_zero_copy) ? MAP_POPULATE : 0;
1149                 mmap_addr = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE,
1150                                  MAP_SHARED | populate, fd, 0);
1151
1152                 if (mmap_addr == MAP_FAILED) {
1153                         VHOST_LOG_CONFIG(ERR,
1154                                 "mmap region %u failed.\n", i);
1155                         goto err_mmap;
1156                 }
1157
1158                 reg->mmap_addr = mmap_addr;
1159                 reg->mmap_size = mmap_size;
1160                 reg->host_user_addr = (uint64_t)(uintptr_t)mmap_addr +
1161                                       mmap_offset;
1162
1163                 if (dev->dequeue_zero_copy)
1164                         if (add_guest_pages(dev, reg, alignment) < 0) {
1165                                 VHOST_LOG_CONFIG(ERR,
1166                                         "adding guest pages to region %u failed.\n",
1167                                         i);
1168                                 goto err_mmap;
1169                         }
1170
1171                 VHOST_LOG_CONFIG(INFO,
1172                         "guest memory region %u, size: 0x%" PRIx64 "\n"
1173                         "\t guest physical addr: 0x%" PRIx64 "\n"
1174                         "\t guest virtual  addr: 0x%" PRIx64 "\n"
1175                         "\t host  virtual  addr: 0x%" PRIx64 "\n"
1176                         "\t mmap addr : 0x%" PRIx64 "\n"
1177                         "\t mmap size : 0x%" PRIx64 "\n"
1178                         "\t mmap align: 0x%" PRIx64 "\n"
1179                         "\t mmap off  : 0x%" PRIx64 "\n",
1180                         i, reg->size,
1181                         reg->guest_phys_addr,
1182                         reg->guest_user_addr,
1183                         reg->host_user_addr,
1184                         (uint64_t)(uintptr_t)mmap_addr,
1185                         mmap_size,
1186                         alignment,
1187                         mmap_offset);
1188
1189                 if (dev->postcopy_listening) {
1190                         /*
1191                          * We haven't a better way right now than sharing
1192                          * DPDK's virtual address with Qemu, so that Qemu can
1193                          * retrieve the region offset when handling userfaults.
1194                          */
1195                         memory->regions[i].userspace_addr =
1196                                 reg->host_user_addr;
1197                 }
1198         }
1199         if (dev->postcopy_listening) {
1200                 /* Send the addresses back to qemu */
1201                 msg->fd_num = 0;
1202                 send_vhost_reply(main_fd, msg);
1203
1204                 /* Wait for qemu to acknolwedge it's got the addresses
1205                  * we've got to wait before we're allowed to generate faults.
1206                  */
1207                 VhostUserMsg ack_msg;
1208                 if (read_vhost_message(main_fd, &ack_msg) <= 0) {
1209                         VHOST_LOG_CONFIG(ERR,
1210                                 "Failed to read qemu ack on postcopy set-mem-table\n");
1211                         goto err_mmap;
1212                 }
1213
1214                 if (validate_msg_fds(&ack_msg, 0) != 0)
1215                         goto err_mmap;
1216
1217                 if (ack_msg.request.master != VHOST_USER_SET_MEM_TABLE) {
1218                         VHOST_LOG_CONFIG(ERR,
1219                                 "Bad qemu ack on postcopy set-mem-table (%d)\n",
1220                                 ack_msg.request.master);
1221                         goto err_mmap;
1222                 }
1223
1224                 /* Now userfault register and we can use the memory */
1225                 for (i = 0; i < memory->nregions; i++) {
1226 #ifdef RTE_LIBRTE_VHOST_POSTCOPY
1227                         reg = &dev->mem->regions[i];
1228                         struct uffdio_register reg_struct;
1229
1230                         /*
1231                          * Let's register all the mmap'ed area to ensure
1232                          * alignment on page boundary.
1233                          */
1234                         reg_struct.range.start =
1235                                 (uint64_t)(uintptr_t)reg->mmap_addr;
1236                         reg_struct.range.len = reg->mmap_size;
1237                         reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
1238
1239                         if (ioctl(dev->postcopy_ufd, UFFDIO_REGISTER,
1240                                                 &reg_struct)) {
1241                                 VHOST_LOG_CONFIG(ERR,
1242                                         "Failed to register ufd for region %d: (ufd = %d) %s\n",
1243                                         i, dev->postcopy_ufd,
1244                                         strerror(errno));
1245                                 goto err_mmap;
1246                         }
1247                         VHOST_LOG_CONFIG(INFO,
1248                                 "\t userfaultfd registered for range : "
1249                                 "%" PRIx64 " - %" PRIx64 "\n",
1250                                 (uint64_t)reg_struct.range.start,
1251                                 (uint64_t)reg_struct.range.start +
1252                                 (uint64_t)reg_struct.range.len - 1);
1253 #else
1254                         goto err_mmap;
1255 #endif
1256                 }
1257         }
1258
1259         for (i = 0; i < dev->nr_vring; i++) {
1260                 struct vhost_virtqueue *vq = dev->virtqueue[i];
1261
1262                 if (vq->desc || vq->avail || vq->used) {
1263                         /*
1264                          * If the memory table got updated, the ring addresses
1265                          * need to be translated again as virtual addresses have
1266                          * changed.
1267                          */
1268                         vring_invalidate(dev, vq);
1269
1270                         dev = translate_ring_addresses(dev, i);
1271                         if (!dev) {
1272                                 dev = *pdev;
1273                                 goto err_mmap;
1274                         }
1275
1276                         *pdev = dev;
1277                 }
1278         }
1279
1280         dump_guest_pages(dev);
1281
1282         return RTE_VHOST_MSG_RESULT_OK;
1283
1284 err_mmap:
1285         free_mem_region(dev);
1286         rte_free(dev->mem);
1287         dev->mem = NULL;
1288         return RTE_VHOST_MSG_RESULT_ERR;
1289 }
1290
1291 static bool
1292 vq_is_ready(struct virtio_net *dev, struct vhost_virtqueue *vq)
1293 {
1294         bool rings_ok;
1295
1296         if (!vq)
1297                 return false;
1298
1299         if (vq_is_packed(dev))
1300                 rings_ok = vq->desc_packed && vq->driver_event &&
1301                         vq->device_event;
1302         else
1303                 rings_ok = vq->desc && vq->avail && vq->used;
1304
1305         return rings_ok &&
1306                vq->kickfd != VIRTIO_UNINITIALIZED_EVENTFD &&
1307                vq->callfd != VIRTIO_UNINITIALIZED_EVENTFD;
1308 }
1309
1310 static int
1311 virtio_is_ready(struct virtio_net *dev)
1312 {
1313         struct vhost_virtqueue *vq;
1314         uint32_t i;
1315
1316         if (dev->nr_vring == 0)
1317                 return 0;
1318
1319         for (i = 0; i < dev->nr_vring; i++) {
1320                 vq = dev->virtqueue[i];
1321
1322                 if (!vq_is_ready(dev, vq))
1323                         return 0;
1324         }
1325
1326         VHOST_LOG_CONFIG(INFO,
1327                 "virtio is now ready for processing.\n");
1328         return 1;
1329 }
1330
1331 static void *
1332 inflight_mem_alloc(const char *name, size_t size, int *fd)
1333 {
1334         void *ptr;
1335         int mfd = -1;
1336         char fname[20] = "/tmp/memfd-XXXXXX";
1337
1338         *fd = -1;
1339 #ifdef MEMFD_SUPPORTED
1340         mfd = memfd_create(name, MFD_CLOEXEC);
1341 #else
1342         RTE_SET_USED(name);
1343 #endif
1344         if (mfd == -1) {
1345                 mfd = mkstemp(fname);
1346                 if (mfd == -1) {
1347                         VHOST_LOG_CONFIG(ERR,
1348                                 "failed to get inflight buffer fd\n");
1349                         return NULL;
1350                 }
1351
1352                 unlink(fname);
1353         }
1354
1355         if (ftruncate(mfd, size) == -1) {
1356                 VHOST_LOG_CONFIG(ERR,
1357                         "failed to alloc inflight buffer\n");
1358                 close(mfd);
1359                 return NULL;
1360         }
1361
1362         ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, mfd, 0);
1363         if (ptr == MAP_FAILED) {
1364                 VHOST_LOG_CONFIG(ERR,
1365                         "failed to mmap inflight buffer\n");
1366                 close(mfd);
1367                 return NULL;
1368         }
1369
1370         *fd = mfd;
1371         return ptr;
1372 }
1373
1374 static uint32_t
1375 get_pervq_shm_size_split(uint16_t queue_size)
1376 {
1377         return RTE_ALIGN_MUL_CEIL(sizeof(struct rte_vhost_inflight_desc_split) *
1378                                   queue_size + sizeof(uint64_t) +
1379                                   sizeof(uint16_t) * 4, INFLIGHT_ALIGNMENT);
1380 }
1381
1382 static uint32_t
1383 get_pervq_shm_size_packed(uint16_t queue_size)
1384 {
1385         return RTE_ALIGN_MUL_CEIL(sizeof(struct rte_vhost_inflight_desc_packed)
1386                                   * queue_size + sizeof(uint64_t) +
1387                                   sizeof(uint16_t) * 6 + sizeof(uint8_t) * 9,
1388                                   INFLIGHT_ALIGNMENT);
1389 }
1390
1391 static int
1392 vhost_user_get_inflight_fd(struct virtio_net **pdev,
1393                            VhostUserMsg *msg,
1394                            int main_fd __rte_unused)
1395 {
1396         struct rte_vhost_inflight_info_packed *inflight_packed;
1397         uint64_t pervq_inflight_size, mmap_size;
1398         uint16_t num_queues, queue_size;
1399         struct virtio_net *dev = *pdev;
1400         int fd, i, j;
1401         void *addr;
1402
1403         if (msg->size != sizeof(msg->payload.inflight)) {
1404                 VHOST_LOG_CONFIG(ERR,
1405                         "invalid get_inflight_fd message size is %d\n",
1406                         msg->size);
1407                 return RTE_VHOST_MSG_RESULT_ERR;
1408         }
1409
1410         if (dev->inflight_info == NULL) {
1411                 dev->inflight_info = calloc(1,
1412                                             sizeof(struct inflight_mem_info));
1413                 if (!dev->inflight_info) {
1414                         VHOST_LOG_CONFIG(ERR,
1415                                 "failed to alloc dev inflight area\n");
1416                         return RTE_VHOST_MSG_RESULT_ERR;
1417                 }
1418                 dev->inflight_info->fd = -1;
1419         }
1420
1421         num_queues = msg->payload.inflight.num_queues;
1422         queue_size = msg->payload.inflight.queue_size;
1423
1424         VHOST_LOG_CONFIG(INFO, "get_inflight_fd num_queues: %u\n",
1425                 msg->payload.inflight.num_queues);
1426         VHOST_LOG_CONFIG(INFO, "get_inflight_fd queue_size: %u\n",
1427                 msg->payload.inflight.queue_size);
1428
1429         if (vq_is_packed(dev))
1430                 pervq_inflight_size = get_pervq_shm_size_packed(queue_size);
1431         else
1432                 pervq_inflight_size = get_pervq_shm_size_split(queue_size);
1433
1434         mmap_size = num_queues * pervq_inflight_size;
1435         addr = inflight_mem_alloc("vhost-inflight", mmap_size, &fd);
1436         if (!addr) {
1437                 VHOST_LOG_CONFIG(ERR,
1438                         "failed to alloc vhost inflight area\n");
1439                         msg->payload.inflight.mmap_size = 0;
1440                 return RTE_VHOST_MSG_RESULT_ERR;
1441         }
1442         memset(addr, 0, mmap_size);
1443
1444         if (dev->inflight_info->addr) {
1445                 munmap(dev->inflight_info->addr, dev->inflight_info->size);
1446                 dev->inflight_info->addr = NULL;
1447         }
1448
1449         if (dev->inflight_info->fd >= 0) {
1450                 close(dev->inflight_info->fd);
1451                 dev->inflight_info->fd = -1;
1452         }
1453
1454         dev->inflight_info->addr = addr;
1455         dev->inflight_info->size = msg->payload.inflight.mmap_size = mmap_size;
1456         dev->inflight_info->fd = msg->fds[0] = fd;
1457         msg->payload.inflight.mmap_offset = 0;
1458         msg->fd_num = 1;
1459
1460         if (vq_is_packed(dev)) {
1461                 for (i = 0; i < num_queues; i++) {
1462                         inflight_packed =
1463                                 (struct rte_vhost_inflight_info_packed *)addr;
1464                         inflight_packed->used_wrap_counter = 1;
1465                         inflight_packed->old_used_wrap_counter = 1;
1466                         for (j = 0; j < queue_size; j++)
1467                                 inflight_packed->desc[j].next = j + 1;
1468                         addr = (void *)((char *)addr + pervq_inflight_size);
1469                 }
1470         }
1471
1472         VHOST_LOG_CONFIG(INFO,
1473                 "send inflight mmap_size: %"PRIu64"\n",
1474                 msg->payload.inflight.mmap_size);
1475         VHOST_LOG_CONFIG(INFO,
1476                 "send inflight mmap_offset: %"PRIu64"\n",
1477                 msg->payload.inflight.mmap_offset);
1478         VHOST_LOG_CONFIG(INFO,
1479                 "send inflight fd: %d\n", msg->fds[0]);
1480
1481         return RTE_VHOST_MSG_RESULT_REPLY;
1482 }
1483
1484 static int
1485 vhost_user_set_inflight_fd(struct virtio_net **pdev, VhostUserMsg *msg,
1486                            int main_fd __rte_unused)
1487 {
1488         uint64_t mmap_size, mmap_offset;
1489         uint16_t num_queues, queue_size;
1490         struct virtio_net *dev = *pdev;
1491         uint32_t pervq_inflight_size;
1492         struct vhost_virtqueue *vq;
1493         void *addr;
1494         int fd, i;
1495
1496         fd = msg->fds[0];
1497         if (msg->size != sizeof(msg->payload.inflight) || fd < 0) {
1498                 VHOST_LOG_CONFIG(ERR,
1499                         "invalid set_inflight_fd message size is %d,fd is %d\n",
1500                         msg->size, fd);
1501                 return RTE_VHOST_MSG_RESULT_ERR;
1502         }
1503
1504         mmap_size = msg->payload.inflight.mmap_size;
1505         mmap_offset = msg->payload.inflight.mmap_offset;
1506         num_queues = msg->payload.inflight.num_queues;
1507         queue_size = msg->payload.inflight.queue_size;
1508
1509         if (vq_is_packed(dev))
1510                 pervq_inflight_size = get_pervq_shm_size_packed(queue_size);
1511         else
1512                 pervq_inflight_size = get_pervq_shm_size_split(queue_size);
1513
1514         VHOST_LOG_CONFIG(INFO,
1515                 "set_inflight_fd mmap_size: %"PRIu64"\n", mmap_size);
1516         VHOST_LOG_CONFIG(INFO,
1517                 "set_inflight_fd mmap_offset: %"PRIu64"\n", mmap_offset);
1518         VHOST_LOG_CONFIG(INFO,
1519                 "set_inflight_fd num_queues: %u\n", num_queues);
1520         VHOST_LOG_CONFIG(INFO,
1521                 "set_inflight_fd queue_size: %u\n", queue_size);
1522         VHOST_LOG_CONFIG(INFO,
1523                 "set_inflight_fd fd: %d\n", fd);
1524         VHOST_LOG_CONFIG(INFO,
1525                 "set_inflight_fd pervq_inflight_size: %d\n",
1526                 pervq_inflight_size);
1527
1528         if (!dev->inflight_info) {
1529                 dev->inflight_info = calloc(1,
1530                                             sizeof(struct inflight_mem_info));
1531                 if (dev->inflight_info == NULL) {
1532                         VHOST_LOG_CONFIG(ERR,
1533                                 "failed to alloc dev inflight area\n");
1534                         return RTE_VHOST_MSG_RESULT_ERR;
1535                 }
1536                 dev->inflight_info->fd = -1;
1537         }
1538
1539         if (dev->inflight_info->addr) {
1540                 munmap(dev->inflight_info->addr, dev->inflight_info->size);
1541                 dev->inflight_info->addr = NULL;
1542         }
1543
1544         addr = mmap(0, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
1545                     fd, mmap_offset);
1546         if (addr == MAP_FAILED) {
1547                 VHOST_LOG_CONFIG(ERR, "failed to mmap share memory.\n");
1548                 return RTE_VHOST_MSG_RESULT_ERR;
1549         }
1550
1551         if (dev->inflight_info->fd >= 0) {
1552                 close(dev->inflight_info->fd);
1553                 dev->inflight_info->fd = -1;
1554         }
1555
1556         dev->inflight_info->fd = fd;
1557         dev->inflight_info->addr = addr;
1558         dev->inflight_info->size = mmap_size;
1559
1560         for (i = 0; i < num_queues; i++) {
1561                 vq = dev->virtqueue[i];
1562                 if (vq_is_packed(dev)) {
1563                         vq->inflight_packed = addr;
1564                         vq->inflight_packed->desc_num = queue_size;
1565                 } else {
1566                         vq->inflight_split = addr;
1567                         vq->inflight_split->desc_num = queue_size;
1568                 }
1569                 addr = (void *)((char *)addr + pervq_inflight_size);
1570         }
1571
1572         return RTE_VHOST_MSG_RESULT_OK;
1573 }
1574
1575 static int
1576 vhost_user_set_vring_call(struct virtio_net **pdev, struct VhostUserMsg *msg,
1577                         int main_fd __rte_unused)
1578 {
1579         struct virtio_net *dev = *pdev;
1580         struct vhost_vring_file file;
1581         struct vhost_virtqueue *vq;
1582         int expected_fds;
1583
1584         expected_fds = (msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK) ? 0 : 1;
1585         if (validate_msg_fds(msg, expected_fds) != 0)
1586                 return RTE_VHOST_MSG_RESULT_ERR;
1587
1588         file.index = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
1589         if (msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK)
1590                 file.fd = VIRTIO_INVALID_EVENTFD;
1591         else
1592                 file.fd = msg->fds[0];
1593         VHOST_LOG_CONFIG(INFO,
1594                 "vring call idx:%d file:%d\n", file.index, file.fd);
1595
1596         vq = dev->virtqueue[file.index];
1597         if (vq->callfd >= 0)
1598                 close(vq->callfd);
1599
1600         vq->callfd = file.fd;
1601
1602         return RTE_VHOST_MSG_RESULT_OK;
1603 }
1604
1605 static int vhost_user_set_vring_err(struct virtio_net **pdev __rte_unused,
1606                         struct VhostUserMsg *msg,
1607                         int main_fd __rte_unused)
1608 {
1609         int expected_fds;
1610
1611         expected_fds = (msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK) ? 0 : 1;
1612         if (validate_msg_fds(msg, expected_fds) != 0)
1613                 return RTE_VHOST_MSG_RESULT_ERR;
1614
1615         if (!(msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK))
1616                 close(msg->fds[0]);
1617         VHOST_LOG_CONFIG(INFO, "not implemented\n");
1618
1619         return RTE_VHOST_MSG_RESULT_OK;
1620 }
1621
1622 static int
1623 resubmit_desc_compare(const void *a, const void *b)
1624 {
1625         const struct rte_vhost_resubmit_desc *desc0 = a;
1626         const struct rte_vhost_resubmit_desc *desc1 = b;
1627
1628         if (desc1->counter > desc0->counter)
1629                 return 1;
1630
1631         return -1;
1632 }
1633
1634 static int
1635 vhost_check_queue_inflights_split(struct virtio_net *dev,
1636                                   struct vhost_virtqueue *vq)
1637 {
1638         uint16_t i;
1639         uint16_t resubmit_num = 0, last_io, num;
1640         struct vring_used *used = vq->used;
1641         struct rte_vhost_resubmit_info *resubmit;
1642         struct rte_vhost_inflight_info_split *inflight_split;
1643
1644         if (!(dev->protocol_features &
1645             (1ULL << VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)))
1646                 return RTE_VHOST_MSG_RESULT_OK;
1647
1648         /* The frontend may still not support the inflight feature
1649          * although we negotiate the protocol feature.
1650          */
1651         if ((!vq->inflight_split))
1652                 return RTE_VHOST_MSG_RESULT_OK;
1653
1654         if (!vq->inflight_split->version) {
1655                 vq->inflight_split->version = INFLIGHT_VERSION;
1656                 return RTE_VHOST_MSG_RESULT_OK;
1657         }
1658
1659         if (vq->resubmit_inflight)
1660                 return RTE_VHOST_MSG_RESULT_OK;
1661
1662         inflight_split = vq->inflight_split;
1663         vq->global_counter = 0;
1664         last_io = inflight_split->last_inflight_io;
1665
1666         if (inflight_split->used_idx != used->idx) {
1667                 inflight_split->desc[last_io].inflight = 0;
1668                 rte_smp_mb();
1669                 inflight_split->used_idx = used->idx;
1670         }
1671
1672         for (i = 0; i < inflight_split->desc_num; i++) {
1673                 if (inflight_split->desc[i].inflight == 1)
1674                         resubmit_num++;
1675         }
1676
1677         vq->last_avail_idx += resubmit_num;
1678
1679         if (resubmit_num) {
1680                 resubmit  = calloc(1, sizeof(struct rte_vhost_resubmit_info));
1681                 if (!resubmit) {
1682                         VHOST_LOG_CONFIG(ERR,
1683                                 "failed to allocate memory for resubmit info.\n");
1684                         return RTE_VHOST_MSG_RESULT_ERR;
1685                 }
1686
1687                 resubmit->resubmit_list = calloc(resubmit_num,
1688                         sizeof(struct rte_vhost_resubmit_desc));
1689                 if (!resubmit->resubmit_list) {
1690                         VHOST_LOG_CONFIG(ERR,
1691                                 "failed to allocate memory for inflight desc.\n");
1692                         free(resubmit);
1693                         return RTE_VHOST_MSG_RESULT_ERR;
1694                 }
1695
1696                 num = 0;
1697                 for (i = 0; i < vq->inflight_split->desc_num; i++) {
1698                         if (vq->inflight_split->desc[i].inflight == 1) {
1699                                 resubmit->resubmit_list[num].index = i;
1700                                 resubmit->resubmit_list[num].counter =
1701                                         inflight_split->desc[i].counter;
1702                                 num++;
1703                         }
1704                 }
1705                 resubmit->resubmit_num = num;
1706
1707                 if (resubmit->resubmit_num > 1)
1708                         qsort(resubmit->resubmit_list, resubmit->resubmit_num,
1709                               sizeof(struct rte_vhost_resubmit_desc),
1710                               resubmit_desc_compare);
1711
1712                 vq->global_counter = resubmit->resubmit_list[0].counter + 1;
1713                 vq->resubmit_inflight = resubmit;
1714         }
1715
1716         return RTE_VHOST_MSG_RESULT_OK;
1717 }
1718
1719 static int
1720 vhost_check_queue_inflights_packed(struct virtio_net *dev,
1721                                    struct vhost_virtqueue *vq)
1722 {
1723         uint16_t i;
1724         uint16_t resubmit_num = 0, old_used_idx, num;
1725         struct rte_vhost_resubmit_info *resubmit;
1726         struct rte_vhost_inflight_info_packed *inflight_packed;
1727
1728         if (!(dev->protocol_features &
1729             (1ULL << VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)))
1730                 return RTE_VHOST_MSG_RESULT_OK;
1731
1732         /* The frontend may still not support the inflight feature
1733          * although we negotiate the protocol feature.
1734          */
1735         if ((!vq->inflight_packed))
1736                 return RTE_VHOST_MSG_RESULT_OK;
1737
1738         if (!vq->inflight_packed->version) {
1739                 vq->inflight_packed->version = INFLIGHT_VERSION;
1740                 return RTE_VHOST_MSG_RESULT_OK;
1741         }
1742
1743         if (vq->resubmit_inflight)
1744                 return RTE_VHOST_MSG_RESULT_OK;
1745
1746         inflight_packed = vq->inflight_packed;
1747         vq->global_counter = 0;
1748         old_used_idx = inflight_packed->old_used_idx;
1749
1750         if (inflight_packed->used_idx != old_used_idx) {
1751                 if (inflight_packed->desc[old_used_idx].inflight == 0) {
1752                         inflight_packed->old_used_idx =
1753                                 inflight_packed->used_idx;
1754                         inflight_packed->old_used_wrap_counter =
1755                                 inflight_packed->used_wrap_counter;
1756                         inflight_packed->old_free_head =
1757                                 inflight_packed->free_head;
1758                 } else {
1759                         inflight_packed->used_idx =
1760                                 inflight_packed->old_used_idx;
1761                         inflight_packed->used_wrap_counter =
1762                                 inflight_packed->old_used_wrap_counter;
1763                         inflight_packed->free_head =
1764                                 inflight_packed->old_free_head;
1765                 }
1766         }
1767
1768         for (i = 0; i < inflight_packed->desc_num; i++) {
1769                 if (inflight_packed->desc[i].inflight == 1)
1770                         resubmit_num++;
1771         }
1772
1773         if (resubmit_num) {
1774                 resubmit = calloc(1, sizeof(struct rte_vhost_resubmit_info));
1775                 if (resubmit == NULL) {
1776                         VHOST_LOG_CONFIG(ERR,
1777                                 "failed to allocate memory for resubmit info.\n");
1778                         return RTE_VHOST_MSG_RESULT_ERR;
1779                 }
1780
1781                 resubmit->resubmit_list = calloc(resubmit_num,
1782                         sizeof(struct rte_vhost_resubmit_desc));
1783                 if (resubmit->resubmit_list == NULL) {
1784                         VHOST_LOG_CONFIG(ERR,
1785                                 "failed to allocate memory for resubmit desc.\n");
1786                         free(resubmit);
1787                         return RTE_VHOST_MSG_RESULT_ERR;
1788                 }
1789
1790                 num = 0;
1791                 for (i = 0; i < inflight_packed->desc_num; i++) {
1792                         if (vq->inflight_packed->desc[i].inflight == 1) {
1793                                 resubmit->resubmit_list[num].index = i;
1794                                 resubmit->resubmit_list[num].counter =
1795                                         inflight_packed->desc[i].counter;
1796                                 num++;
1797                         }
1798                 }
1799                 resubmit->resubmit_num = num;
1800
1801                 if (resubmit->resubmit_num > 1)
1802                         qsort(resubmit->resubmit_list, resubmit->resubmit_num,
1803                               sizeof(struct rte_vhost_resubmit_desc),
1804                               resubmit_desc_compare);
1805
1806                 vq->global_counter = resubmit->resubmit_list[0].counter + 1;
1807                 vq->resubmit_inflight = resubmit;
1808         }
1809
1810         return RTE_VHOST_MSG_RESULT_OK;
1811 }
1812
1813 static int
1814 vhost_user_set_vring_kick(struct virtio_net **pdev, struct VhostUserMsg *msg,
1815                         int main_fd __rte_unused)
1816 {
1817         struct virtio_net *dev = *pdev;
1818         struct vhost_vring_file file;
1819         struct vhost_virtqueue *vq;
1820         int expected_fds;
1821
1822         expected_fds = (msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK) ? 0 : 1;
1823         if (validate_msg_fds(msg, expected_fds) != 0)
1824                 return RTE_VHOST_MSG_RESULT_ERR;
1825
1826         file.index = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
1827         if (msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK)
1828                 file.fd = VIRTIO_INVALID_EVENTFD;
1829         else
1830                 file.fd = msg->fds[0];
1831         VHOST_LOG_CONFIG(INFO,
1832                 "vring kick idx:%d file:%d\n", file.index, file.fd);
1833
1834         /* Interpret ring addresses only when ring is started. */
1835         dev = translate_ring_addresses(dev, file.index);
1836         if (!dev)
1837                 return RTE_VHOST_MSG_RESULT_ERR;
1838
1839         *pdev = dev;
1840
1841         vq = dev->virtqueue[file.index];
1842
1843         /*
1844          * When VHOST_USER_F_PROTOCOL_FEATURES is not negotiated,
1845          * the ring starts already enabled. Otherwise, it is enabled via
1846          * the SET_VRING_ENABLE message.
1847          */
1848         if (!(dev->features & (1ULL << VHOST_USER_F_PROTOCOL_FEATURES))) {
1849                 vq->enabled = 1;
1850                 if (dev->notify_ops->vring_state_changed)
1851                         dev->notify_ops->vring_state_changed(
1852                                 dev->vid, file.index, 1);
1853         }
1854
1855         if (vq->kickfd >= 0)
1856                 close(vq->kickfd);
1857         vq->kickfd = file.fd;
1858
1859         if (vq_is_packed(dev)) {
1860                 if (vhost_check_queue_inflights_packed(dev, vq)) {
1861                         VHOST_LOG_CONFIG(ERR,
1862                                 "failed to inflights for vq: %d\n", file.index);
1863                         return RTE_VHOST_MSG_RESULT_ERR;
1864                 }
1865         } else {
1866                 if (vhost_check_queue_inflights_split(dev, vq)) {
1867                         VHOST_LOG_CONFIG(ERR,
1868                                 "failed to inflights for vq: %d\n", file.index);
1869                         return RTE_VHOST_MSG_RESULT_ERR;
1870                 }
1871         }
1872
1873         return RTE_VHOST_MSG_RESULT_OK;
1874 }
1875
1876 static void
1877 free_zmbufs(struct vhost_virtqueue *vq)
1878 {
1879         drain_zmbuf_list(vq);
1880
1881         rte_free(vq->zmbufs);
1882 }
1883
1884 /*
1885  * when virtio is stopped, qemu will send us the GET_VRING_BASE message.
1886  */
1887 static int
1888 vhost_user_get_vring_base(struct virtio_net **pdev,
1889                         struct VhostUserMsg *msg,
1890                         int main_fd __rte_unused)
1891 {
1892         struct virtio_net *dev = *pdev;
1893         struct vhost_virtqueue *vq = dev->virtqueue[msg->payload.state.index];
1894         uint64_t val;
1895
1896         if (validate_msg_fds(msg, 0) != 0)
1897                 return RTE_VHOST_MSG_RESULT_ERR;
1898
1899         /* We have to stop the queue (virtio) if it is running. */
1900         vhost_destroy_device_notify(dev);
1901
1902         dev->flags &= ~VIRTIO_DEV_READY;
1903         dev->flags &= ~VIRTIO_DEV_VDPA_CONFIGURED;
1904
1905         /* Here we are safe to get the indexes */
1906         if (vq_is_packed(dev)) {
1907                 /*
1908                  * Bit[0:14]: avail index
1909                  * Bit[15]: avail wrap counter
1910                  */
1911                 val = vq->last_avail_idx & 0x7fff;
1912                 val |= vq->avail_wrap_counter << 15;
1913                 msg->payload.state.num = val;
1914         } else {
1915                 msg->payload.state.num = vq->last_avail_idx;
1916         }
1917
1918         VHOST_LOG_CONFIG(INFO,
1919                 "vring base idx:%d file:%d\n", msg->payload.state.index,
1920                 msg->payload.state.num);
1921         /*
1922          * Based on current qemu vhost-user implementation, this message is
1923          * sent and only sent in vhost_vring_stop.
1924          * TODO: cleanup the vring, it isn't usable since here.
1925          */
1926         if (vq->kickfd >= 0)
1927                 close(vq->kickfd);
1928
1929         vq->kickfd = VIRTIO_UNINITIALIZED_EVENTFD;
1930
1931         if (vq->callfd >= 0)
1932                 close(vq->callfd);
1933
1934         vq->callfd = VIRTIO_UNINITIALIZED_EVENTFD;
1935
1936         vq->signalled_used_valid = false;
1937
1938         if (dev->dequeue_zero_copy)
1939                 free_zmbufs(vq);
1940         if (vq_is_packed(dev)) {
1941                 rte_free(vq->shadow_used_packed);
1942                 vq->shadow_used_packed = NULL;
1943         } else {
1944                 rte_free(vq->shadow_used_split);
1945                 vq->shadow_used_split = NULL;
1946         }
1947
1948         rte_free(vq->batch_copy_elems);
1949         vq->batch_copy_elems = NULL;
1950
1951         msg->size = sizeof(msg->payload.state);
1952         msg->fd_num = 0;
1953
1954         vring_invalidate(dev, vq);
1955
1956         return RTE_VHOST_MSG_RESULT_REPLY;
1957 }
1958
1959 /*
1960  * when virtio queues are ready to work, qemu will send us to
1961  * enable the virtio queue pair.
1962  */
1963 static int
1964 vhost_user_set_vring_enable(struct virtio_net **pdev,
1965                         struct VhostUserMsg *msg,
1966                         int main_fd __rte_unused)
1967 {
1968         struct virtio_net *dev = *pdev;
1969         int enable = (int)msg->payload.state.num;
1970         int index = (int)msg->payload.state.index;
1971         struct rte_vdpa_device *vdpa_dev;
1972
1973         if (validate_msg_fds(msg, 0) != 0)
1974                 return RTE_VHOST_MSG_RESULT_ERR;
1975
1976         VHOST_LOG_CONFIG(INFO,
1977                 "set queue enable: %d to qp idx: %d\n",
1978                 enable, index);
1979
1980         vdpa_dev = dev->vdpa_dev;
1981         if (vdpa_dev && vdpa_dev->ops->set_vring_state)
1982                 vdpa_dev->ops->set_vring_state(dev->vid, index, enable);
1983
1984         if (dev->notify_ops->vring_state_changed)
1985                 dev->notify_ops->vring_state_changed(dev->vid,
1986                                 index, enable);
1987
1988         /* On disable, rings have to be stopped being processed. */
1989         if (!enable && dev->dequeue_zero_copy)
1990                 drain_zmbuf_list(dev->virtqueue[index]);
1991
1992         dev->virtqueue[index]->enabled = enable;
1993
1994         return RTE_VHOST_MSG_RESULT_OK;
1995 }
1996
1997 static int
1998 vhost_user_get_protocol_features(struct virtio_net **pdev,
1999                         struct VhostUserMsg *msg,
2000                         int main_fd __rte_unused)
2001 {
2002         struct virtio_net *dev = *pdev;
2003         uint64_t features, protocol_features;
2004
2005         if (validate_msg_fds(msg, 0) != 0)
2006                 return RTE_VHOST_MSG_RESULT_ERR;
2007
2008         rte_vhost_driver_get_features(dev->ifname, &features);
2009         rte_vhost_driver_get_protocol_features(dev->ifname, &protocol_features);
2010
2011         msg->payload.u64 = protocol_features;
2012         msg->size = sizeof(msg->payload.u64);
2013         msg->fd_num = 0;
2014
2015         return RTE_VHOST_MSG_RESULT_REPLY;
2016 }
2017
2018 static int
2019 vhost_user_set_protocol_features(struct virtio_net **pdev,
2020                         struct VhostUserMsg *msg,
2021                         int main_fd __rte_unused)
2022 {
2023         struct virtio_net *dev = *pdev;
2024         uint64_t protocol_features = msg->payload.u64;
2025         uint64_t slave_protocol_features = 0;
2026
2027         if (validate_msg_fds(msg, 0) != 0)
2028                 return RTE_VHOST_MSG_RESULT_ERR;
2029
2030         rte_vhost_driver_get_protocol_features(dev->ifname,
2031                         &slave_protocol_features);
2032         if (protocol_features & ~slave_protocol_features) {
2033                 VHOST_LOG_CONFIG(ERR,
2034                         "(%d) received invalid protocol features.\n",
2035                         dev->vid);
2036                 return RTE_VHOST_MSG_RESULT_ERR;
2037         }
2038
2039         dev->protocol_features = protocol_features;
2040         VHOST_LOG_CONFIG(INFO,
2041                 "negotiated Vhost-user protocol features: 0x%" PRIx64 "\n",
2042                 dev->protocol_features);
2043
2044         return RTE_VHOST_MSG_RESULT_OK;
2045 }
2046
2047 static int
2048 vhost_user_set_log_base(struct virtio_net **pdev, struct VhostUserMsg *msg,
2049                         int main_fd __rte_unused)
2050 {
2051         struct virtio_net *dev = *pdev;
2052         int fd = msg->fds[0];
2053         uint64_t size, off;
2054         void *addr;
2055
2056         if (validate_msg_fds(msg, 1) != 0)
2057                 return RTE_VHOST_MSG_RESULT_ERR;
2058
2059         if (fd < 0) {
2060                 VHOST_LOG_CONFIG(ERR, "invalid log fd: %d\n", fd);
2061                 return RTE_VHOST_MSG_RESULT_ERR;
2062         }
2063
2064         if (msg->size != sizeof(VhostUserLog)) {
2065                 VHOST_LOG_CONFIG(ERR,
2066                         "invalid log base msg size: %"PRId32" != %d\n",
2067                         msg->size, (int)sizeof(VhostUserLog));
2068                 return RTE_VHOST_MSG_RESULT_ERR;
2069         }
2070
2071         size = msg->payload.log.mmap_size;
2072         off  = msg->payload.log.mmap_offset;
2073
2074         /* Check for mmap size and offset overflow. */
2075         if (off >= -size) {
2076                 VHOST_LOG_CONFIG(ERR,
2077                         "log offset %#"PRIx64" and log size %#"PRIx64" overflow\n",
2078                         off, size);
2079                 return RTE_VHOST_MSG_RESULT_ERR;
2080         }
2081
2082         VHOST_LOG_CONFIG(INFO,
2083                 "log mmap size: %"PRId64", offset: %"PRId64"\n",
2084                 size, off);
2085
2086         /*
2087          * mmap from 0 to workaround a hugepage mmap bug: mmap will
2088          * fail when offset is not page size aligned.
2089          */
2090         addr = mmap(0, size + off, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
2091         close(fd);
2092         if (addr == MAP_FAILED) {
2093                 VHOST_LOG_CONFIG(ERR, "mmap log base failed!\n");
2094                 return RTE_VHOST_MSG_RESULT_ERR;
2095         }
2096
2097         /*
2098          * Free previously mapped log memory on occasionally
2099          * multiple VHOST_USER_SET_LOG_BASE.
2100          */
2101         if (dev->log_addr) {
2102                 munmap((void *)(uintptr_t)dev->log_addr, dev->log_size);
2103         }
2104         dev->log_addr = (uint64_t)(uintptr_t)addr;
2105         dev->log_base = dev->log_addr + off;
2106         dev->log_size = size;
2107
2108         /*
2109          * The spec is not clear about it (yet), but QEMU doesn't expect
2110          * any payload in the reply.
2111          */
2112         msg->size = 0;
2113         msg->fd_num = 0;
2114
2115         return RTE_VHOST_MSG_RESULT_REPLY;
2116 }
2117
2118 static int vhost_user_set_log_fd(struct virtio_net **pdev __rte_unused,
2119                         struct VhostUserMsg *msg,
2120                         int main_fd __rte_unused)
2121 {
2122         if (validate_msg_fds(msg, 1) != 0)
2123                 return RTE_VHOST_MSG_RESULT_ERR;
2124
2125         close(msg->fds[0]);
2126         VHOST_LOG_CONFIG(INFO, "not implemented.\n");
2127
2128         return RTE_VHOST_MSG_RESULT_OK;
2129 }
2130
2131 /*
2132  * An rarp packet is constructed and broadcasted to notify switches about
2133  * the new location of the migrated VM, so that packets from outside will
2134  * not be lost after migration.
2135  *
2136  * However, we don't actually "send" a rarp packet here, instead, we set
2137  * a flag 'broadcast_rarp' to let rte_vhost_dequeue_burst() inject it.
2138  */
2139 static int
2140 vhost_user_send_rarp(struct virtio_net **pdev, struct VhostUserMsg *msg,
2141                         int main_fd __rte_unused)
2142 {
2143         struct virtio_net *dev = *pdev;
2144         uint8_t *mac = (uint8_t *)&msg->payload.u64;
2145         struct rte_vdpa_device *vdpa_dev;
2146
2147         if (validate_msg_fds(msg, 0) != 0)
2148                 return RTE_VHOST_MSG_RESULT_ERR;
2149
2150         VHOST_LOG_CONFIG(DEBUG,
2151                 ":: mac: %02x:%02x:%02x:%02x:%02x:%02x\n",
2152                 mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
2153         memcpy(dev->mac.addr_bytes, mac, 6);
2154
2155         /*
2156          * Set the flag to inject a RARP broadcast packet at
2157          * rte_vhost_dequeue_burst().
2158          *
2159          * __ATOMIC_RELEASE ordering is for making sure the mac is
2160          * copied before the flag is set.
2161          */
2162         __atomic_store_n(&dev->broadcast_rarp, 1, __ATOMIC_RELEASE);
2163         vdpa_dev = dev->vdpa_dev;
2164         if (vdpa_dev && vdpa_dev->ops->migration_done)
2165                 vdpa_dev->ops->migration_done(dev->vid);
2166
2167         return RTE_VHOST_MSG_RESULT_OK;
2168 }
2169
2170 static int
2171 vhost_user_net_set_mtu(struct virtio_net **pdev, struct VhostUserMsg *msg,
2172                         int main_fd __rte_unused)
2173 {
2174         struct virtio_net *dev = *pdev;
2175
2176         if (validate_msg_fds(msg, 0) != 0)
2177                 return RTE_VHOST_MSG_RESULT_ERR;
2178
2179         if (msg->payload.u64 < VIRTIO_MIN_MTU ||
2180                         msg->payload.u64 > VIRTIO_MAX_MTU) {
2181                 VHOST_LOG_CONFIG(ERR, "Invalid MTU size (%"PRIu64")\n",
2182                                 msg->payload.u64);
2183
2184                 return RTE_VHOST_MSG_RESULT_ERR;
2185         }
2186
2187         dev->mtu = msg->payload.u64;
2188
2189         return RTE_VHOST_MSG_RESULT_OK;
2190 }
2191
2192 static int
2193 vhost_user_set_req_fd(struct virtio_net **pdev, struct VhostUserMsg *msg,
2194                         int main_fd __rte_unused)
2195 {
2196         struct virtio_net *dev = *pdev;
2197         int fd = msg->fds[0];
2198
2199         if (validate_msg_fds(msg, 1) != 0)
2200                 return RTE_VHOST_MSG_RESULT_ERR;
2201
2202         if (fd < 0) {
2203                 VHOST_LOG_CONFIG(ERR,
2204                                 "Invalid file descriptor for slave channel (%d)\n",
2205                                 fd);
2206                 return RTE_VHOST_MSG_RESULT_ERR;
2207         }
2208
2209         if (dev->slave_req_fd >= 0)
2210                 close(dev->slave_req_fd);
2211
2212         dev->slave_req_fd = fd;
2213
2214         return RTE_VHOST_MSG_RESULT_OK;
2215 }
2216
2217 static int
2218 is_vring_iotlb_split(struct vhost_virtqueue *vq, struct vhost_iotlb_msg *imsg)
2219 {
2220         struct vhost_vring_addr *ra;
2221         uint64_t start, end, len;
2222
2223         start = imsg->iova;
2224         end = start + imsg->size;
2225
2226         ra = &vq->ring_addrs;
2227         len = sizeof(struct vring_desc) * vq->size;
2228         if (ra->desc_user_addr < end && (ra->desc_user_addr + len) > start)
2229                 return 1;
2230
2231         len = sizeof(struct vring_avail) + sizeof(uint16_t) * vq->size;
2232         if (ra->avail_user_addr < end && (ra->avail_user_addr + len) > start)
2233                 return 1;
2234
2235         len = sizeof(struct vring_used) +
2236                sizeof(struct vring_used_elem) * vq->size;
2237         if (ra->used_user_addr < end && (ra->used_user_addr + len) > start)
2238                 return 1;
2239
2240         if (ra->flags & (1 << VHOST_VRING_F_LOG)) {
2241                 len = sizeof(uint64_t);
2242                 if (ra->log_guest_addr < end &&
2243                     (ra->log_guest_addr + len) > start)
2244                         return 1;
2245         }
2246
2247         return 0;
2248 }
2249
2250 static int
2251 is_vring_iotlb_packed(struct vhost_virtqueue *vq, struct vhost_iotlb_msg *imsg)
2252 {
2253         struct vhost_vring_addr *ra;
2254         uint64_t start, end, len;
2255
2256         start = imsg->iova;
2257         end = start + imsg->size;
2258
2259         ra = &vq->ring_addrs;
2260         len = sizeof(struct vring_packed_desc) * vq->size;
2261         if (ra->desc_user_addr < end && (ra->desc_user_addr + len) > start)
2262                 return 1;
2263
2264         len = sizeof(struct vring_packed_desc_event);
2265         if (ra->avail_user_addr < end && (ra->avail_user_addr + len) > start)
2266                 return 1;
2267
2268         len = sizeof(struct vring_packed_desc_event);
2269         if (ra->used_user_addr < end && (ra->used_user_addr + len) > start)
2270                 return 1;
2271
2272         if (ra->flags & (1 << VHOST_VRING_F_LOG)) {
2273                 len = sizeof(uint64_t);
2274                 if (ra->log_guest_addr < end &&
2275                     (ra->log_guest_addr + len) > start)
2276                         return 1;
2277         }
2278
2279         return 0;
2280 }
2281
2282 static int is_vring_iotlb(struct virtio_net *dev,
2283                           struct vhost_virtqueue *vq,
2284                           struct vhost_iotlb_msg *imsg)
2285 {
2286         if (vq_is_packed(dev))
2287                 return is_vring_iotlb_packed(vq, imsg);
2288         else
2289                 return is_vring_iotlb_split(vq, imsg);
2290 }
2291
2292 static int
2293 vhost_user_iotlb_msg(struct virtio_net **pdev, struct VhostUserMsg *msg,
2294                         int main_fd __rte_unused)
2295 {
2296         struct virtio_net *dev = *pdev;
2297         struct vhost_iotlb_msg *imsg = &msg->payload.iotlb;
2298         uint16_t i;
2299         uint64_t vva, len;
2300
2301         if (validate_msg_fds(msg, 0) != 0)
2302                 return RTE_VHOST_MSG_RESULT_ERR;
2303
2304         switch (imsg->type) {
2305         case VHOST_IOTLB_UPDATE:
2306                 len = imsg->size;
2307                 vva = qva_to_vva(dev, imsg->uaddr, &len);
2308                 if (!vva)
2309                         return RTE_VHOST_MSG_RESULT_ERR;
2310
2311                 for (i = 0; i < dev->nr_vring; i++) {
2312                         struct vhost_virtqueue *vq = dev->virtqueue[i];
2313
2314                         vhost_user_iotlb_cache_insert(vq, imsg->iova, vva,
2315                                         len, imsg->perm);
2316
2317                         if (is_vring_iotlb(dev, vq, imsg))
2318                                 *pdev = dev = translate_ring_addresses(dev, i);
2319                 }
2320                 break;
2321         case VHOST_IOTLB_INVALIDATE:
2322                 for (i = 0; i < dev->nr_vring; i++) {
2323                         struct vhost_virtqueue *vq = dev->virtqueue[i];
2324
2325                         vhost_user_iotlb_cache_remove(vq, imsg->iova,
2326                                         imsg->size);
2327
2328                         if (is_vring_iotlb(dev, vq, imsg))
2329                                 vring_invalidate(dev, vq);
2330                 }
2331                 break;
2332         default:
2333                 VHOST_LOG_CONFIG(ERR, "Invalid IOTLB message type (%d)\n",
2334                                 imsg->type);
2335                 return RTE_VHOST_MSG_RESULT_ERR;
2336         }
2337
2338         return RTE_VHOST_MSG_RESULT_OK;
2339 }
2340
2341 static int
2342 vhost_user_set_postcopy_advise(struct virtio_net **pdev,
2343                         struct VhostUserMsg *msg,
2344                         int main_fd __rte_unused)
2345 {
2346         struct virtio_net *dev = *pdev;
2347 #ifdef RTE_LIBRTE_VHOST_POSTCOPY
2348         struct uffdio_api api_struct;
2349
2350         if (validate_msg_fds(msg, 0) != 0)
2351                 return RTE_VHOST_MSG_RESULT_ERR;
2352
2353         dev->postcopy_ufd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
2354
2355         if (dev->postcopy_ufd == -1) {
2356                 VHOST_LOG_CONFIG(ERR, "Userfaultfd not available: %s\n",
2357                         strerror(errno));
2358                 return RTE_VHOST_MSG_RESULT_ERR;
2359         }
2360         api_struct.api = UFFD_API;
2361         api_struct.features = 0;
2362         if (ioctl(dev->postcopy_ufd, UFFDIO_API, &api_struct)) {
2363                 VHOST_LOG_CONFIG(ERR, "UFFDIO_API ioctl failure: %s\n",
2364                         strerror(errno));
2365                 close(dev->postcopy_ufd);
2366                 dev->postcopy_ufd = -1;
2367                 return RTE_VHOST_MSG_RESULT_ERR;
2368         }
2369         msg->fds[0] = dev->postcopy_ufd;
2370         msg->fd_num = 1;
2371
2372         return RTE_VHOST_MSG_RESULT_REPLY;
2373 #else
2374         dev->postcopy_ufd = -1;
2375         msg->fd_num = 0;
2376
2377         return RTE_VHOST_MSG_RESULT_ERR;
2378 #endif
2379 }
2380
2381 static int
2382 vhost_user_set_postcopy_listen(struct virtio_net **pdev,
2383                         struct VhostUserMsg *msg __rte_unused,
2384                         int main_fd __rte_unused)
2385 {
2386         struct virtio_net *dev = *pdev;
2387
2388         if (validate_msg_fds(msg, 0) != 0)
2389                 return RTE_VHOST_MSG_RESULT_ERR;
2390
2391         if (dev->mem && dev->mem->nregions) {
2392                 VHOST_LOG_CONFIG(ERR,
2393                         "Regions already registered at postcopy-listen\n");
2394                 return RTE_VHOST_MSG_RESULT_ERR;
2395         }
2396         dev->postcopy_listening = 1;
2397
2398         return RTE_VHOST_MSG_RESULT_OK;
2399 }
2400
2401 static int
2402 vhost_user_postcopy_end(struct virtio_net **pdev, struct VhostUserMsg *msg,
2403                         int main_fd __rte_unused)
2404 {
2405         struct virtio_net *dev = *pdev;
2406
2407         if (validate_msg_fds(msg, 0) != 0)
2408                 return RTE_VHOST_MSG_RESULT_ERR;
2409
2410         dev->postcopy_listening = 0;
2411         if (dev->postcopy_ufd >= 0) {
2412                 close(dev->postcopy_ufd);
2413                 dev->postcopy_ufd = -1;
2414         }
2415
2416         msg->payload.u64 = 0;
2417         msg->size = sizeof(msg->payload.u64);
2418         msg->fd_num = 0;
2419
2420         return RTE_VHOST_MSG_RESULT_REPLY;
2421 }
2422
2423 typedef int (*vhost_message_handler_t)(struct virtio_net **pdev,
2424                                         struct VhostUserMsg *msg,
2425                                         int main_fd);
2426 static vhost_message_handler_t vhost_message_handlers[VHOST_USER_MAX] = {
2427         [VHOST_USER_NONE] = NULL,
2428         [VHOST_USER_GET_FEATURES] = vhost_user_get_features,
2429         [VHOST_USER_SET_FEATURES] = vhost_user_set_features,
2430         [VHOST_USER_SET_OWNER] = vhost_user_set_owner,
2431         [VHOST_USER_RESET_OWNER] = vhost_user_reset_owner,
2432         [VHOST_USER_SET_MEM_TABLE] = vhost_user_set_mem_table,
2433         [VHOST_USER_SET_LOG_BASE] = vhost_user_set_log_base,
2434         [VHOST_USER_SET_LOG_FD] = vhost_user_set_log_fd,
2435         [VHOST_USER_SET_VRING_NUM] = vhost_user_set_vring_num,
2436         [VHOST_USER_SET_VRING_ADDR] = vhost_user_set_vring_addr,
2437         [VHOST_USER_SET_VRING_BASE] = vhost_user_set_vring_base,
2438         [VHOST_USER_GET_VRING_BASE] = vhost_user_get_vring_base,
2439         [VHOST_USER_SET_VRING_KICK] = vhost_user_set_vring_kick,
2440         [VHOST_USER_SET_VRING_CALL] = vhost_user_set_vring_call,
2441         [VHOST_USER_SET_VRING_ERR] = vhost_user_set_vring_err,
2442         [VHOST_USER_GET_PROTOCOL_FEATURES] = vhost_user_get_protocol_features,
2443         [VHOST_USER_SET_PROTOCOL_FEATURES] = vhost_user_set_protocol_features,
2444         [VHOST_USER_GET_QUEUE_NUM] = vhost_user_get_queue_num,
2445         [VHOST_USER_SET_VRING_ENABLE] = vhost_user_set_vring_enable,
2446         [VHOST_USER_SEND_RARP] = vhost_user_send_rarp,
2447         [VHOST_USER_NET_SET_MTU] = vhost_user_net_set_mtu,
2448         [VHOST_USER_SET_SLAVE_REQ_FD] = vhost_user_set_req_fd,
2449         [VHOST_USER_IOTLB_MSG] = vhost_user_iotlb_msg,
2450         [VHOST_USER_POSTCOPY_ADVISE] = vhost_user_set_postcopy_advise,
2451         [VHOST_USER_POSTCOPY_LISTEN] = vhost_user_set_postcopy_listen,
2452         [VHOST_USER_POSTCOPY_END] = vhost_user_postcopy_end,
2453         [VHOST_USER_GET_INFLIGHT_FD] = vhost_user_get_inflight_fd,
2454         [VHOST_USER_SET_INFLIGHT_FD] = vhost_user_set_inflight_fd,
2455 };
2456
2457 /* return bytes# of read on success or negative val on failure. */
2458 static int
2459 read_vhost_message(int sockfd, struct VhostUserMsg *msg)
2460 {
2461         int ret;
2462
2463         ret = read_fd_message(sockfd, (char *)msg, VHOST_USER_HDR_SIZE,
2464                 msg->fds, VHOST_MEMORY_MAX_NREGIONS, &msg->fd_num);
2465         if (ret <= 0) {
2466                 return ret;
2467         } else if (ret != VHOST_USER_HDR_SIZE) {
2468                 VHOST_LOG_CONFIG(ERR, "Unexpected header size read\n");
2469                 close_msg_fds(msg);
2470                 return -1;
2471         }
2472
2473         if (msg->size) {
2474                 if (msg->size > sizeof(msg->payload)) {
2475                         VHOST_LOG_CONFIG(ERR,
2476                                 "invalid msg size: %d\n", msg->size);
2477                         return -1;
2478                 }
2479                 ret = read(sockfd, &msg->payload, msg->size);
2480                 if (ret <= 0)
2481                         return ret;
2482                 if (ret != (int)msg->size) {
2483                         VHOST_LOG_CONFIG(ERR,
2484                                 "read control message failed\n");
2485                         return -1;
2486                 }
2487         }
2488
2489         return ret;
2490 }
2491
2492 static int
2493 send_vhost_message(int sockfd, struct VhostUserMsg *msg)
2494 {
2495         if (!msg)
2496                 return 0;
2497
2498         return send_fd_message(sockfd, (char *)msg,
2499                 VHOST_USER_HDR_SIZE + msg->size, msg->fds, msg->fd_num);
2500 }
2501
2502 static int
2503 send_vhost_reply(int sockfd, struct VhostUserMsg *msg)
2504 {
2505         if (!msg)
2506                 return 0;
2507
2508         msg->flags &= ~VHOST_USER_VERSION_MASK;
2509         msg->flags &= ~VHOST_USER_NEED_REPLY;
2510         msg->flags |= VHOST_USER_VERSION;
2511         msg->flags |= VHOST_USER_REPLY_MASK;
2512
2513         return send_vhost_message(sockfd, msg);
2514 }
2515
2516 static int
2517 send_vhost_slave_message(struct virtio_net *dev, struct VhostUserMsg *msg)
2518 {
2519         int ret;
2520
2521         if (msg->flags & VHOST_USER_NEED_REPLY)
2522                 rte_spinlock_lock(&dev->slave_req_lock);
2523
2524         ret = send_vhost_message(dev->slave_req_fd, msg);
2525         if (ret < 0 && (msg->flags & VHOST_USER_NEED_REPLY))
2526                 rte_spinlock_unlock(&dev->slave_req_lock);
2527
2528         return ret;
2529 }
2530
2531 /*
2532  * Allocate a queue pair if it hasn't been allocated yet
2533  */
2534 static int
2535 vhost_user_check_and_alloc_queue_pair(struct virtio_net *dev,
2536                         struct VhostUserMsg *msg)
2537 {
2538         uint32_t vring_idx;
2539
2540         switch (msg->request.master) {
2541         case VHOST_USER_SET_VRING_KICK:
2542         case VHOST_USER_SET_VRING_CALL:
2543         case VHOST_USER_SET_VRING_ERR:
2544                 vring_idx = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
2545                 break;
2546         case VHOST_USER_SET_VRING_NUM:
2547         case VHOST_USER_SET_VRING_BASE:
2548         case VHOST_USER_SET_VRING_ENABLE:
2549                 vring_idx = msg->payload.state.index;
2550                 break;
2551         case VHOST_USER_SET_VRING_ADDR:
2552                 vring_idx = msg->payload.addr.index;
2553                 break;
2554         default:
2555                 return 0;
2556         }
2557
2558         if (vring_idx >= VHOST_MAX_VRING) {
2559                 VHOST_LOG_CONFIG(ERR,
2560                         "invalid vring index: %u\n", vring_idx);
2561                 return -1;
2562         }
2563
2564         if (dev->virtqueue[vring_idx])
2565                 return 0;
2566
2567         return alloc_vring_queue(dev, vring_idx);
2568 }
2569
2570 static void
2571 vhost_user_lock_all_queue_pairs(struct virtio_net *dev)
2572 {
2573         unsigned int i = 0;
2574         unsigned int vq_num = 0;
2575
2576         while (vq_num < dev->nr_vring) {
2577                 struct vhost_virtqueue *vq = dev->virtqueue[i];
2578
2579                 if (vq) {
2580                         rte_spinlock_lock(&vq->access_lock);
2581                         vq_num++;
2582                 }
2583                 i++;
2584         }
2585 }
2586
2587 static void
2588 vhost_user_unlock_all_queue_pairs(struct virtio_net *dev)
2589 {
2590         unsigned int i = 0;
2591         unsigned int vq_num = 0;
2592
2593         while (vq_num < dev->nr_vring) {
2594                 struct vhost_virtqueue *vq = dev->virtqueue[i];
2595
2596                 if (vq) {
2597                         rte_spinlock_unlock(&vq->access_lock);
2598                         vq_num++;
2599                 }
2600                 i++;
2601         }
2602 }
2603
2604 int
2605 vhost_user_msg_handler(int vid, int fd)
2606 {
2607         struct virtio_net *dev;
2608         struct VhostUserMsg msg;
2609         struct rte_vdpa_device *vdpa_dev;
2610         int ret;
2611         int unlock_required = 0;
2612         bool handled;
2613         int request;
2614
2615         dev = get_device(vid);
2616         if (dev == NULL)
2617                 return -1;
2618
2619         if (!dev->notify_ops) {
2620                 dev->notify_ops = vhost_driver_callback_get(dev->ifname);
2621                 if (!dev->notify_ops) {
2622                         VHOST_LOG_CONFIG(ERR,
2623                                 "failed to get callback ops for driver %s\n",
2624                                 dev->ifname);
2625                         return -1;
2626                 }
2627         }
2628
2629         ret = read_vhost_message(fd, &msg);
2630         if (ret <= 0) {
2631                 if (ret < 0)
2632                         VHOST_LOG_CONFIG(ERR,
2633                                 "vhost read message failed\n");
2634                 else
2635                         VHOST_LOG_CONFIG(INFO,
2636                                 "vhost peer closed\n");
2637
2638                 return -1;
2639         }
2640
2641         ret = 0;
2642         request = msg.request.master;
2643         if (request > VHOST_USER_NONE && request < VHOST_USER_MAX &&
2644                         vhost_message_str[request]) {
2645                 if (request != VHOST_USER_IOTLB_MSG)
2646                         VHOST_LOG_CONFIG(INFO, "read message %s\n",
2647                                 vhost_message_str[request]);
2648                 else
2649                         VHOST_LOG_CONFIG(DEBUG, "read message %s\n",
2650                                 vhost_message_str[request]);
2651         } else {
2652                 VHOST_LOG_CONFIG(DEBUG, "External request %d\n", request);
2653         }
2654
2655         ret = vhost_user_check_and_alloc_queue_pair(dev, &msg);
2656         if (ret < 0) {
2657                 VHOST_LOG_CONFIG(ERR,
2658                         "failed to alloc queue\n");
2659                 return -1;
2660         }
2661
2662         /*
2663          * Note: we don't lock all queues on VHOST_USER_GET_VRING_BASE
2664          * and VHOST_USER_RESET_OWNER, since it is sent when virtio stops
2665          * and device is destroyed. destroy_device waits for queues to be
2666          * inactive, so it is safe. Otherwise taking the access_lock
2667          * would cause a dead lock.
2668          */
2669         switch (request) {
2670         case VHOST_USER_SET_FEATURES:
2671         case VHOST_USER_SET_PROTOCOL_FEATURES:
2672         case VHOST_USER_SET_OWNER:
2673         case VHOST_USER_SET_MEM_TABLE:
2674         case VHOST_USER_SET_LOG_BASE:
2675         case VHOST_USER_SET_LOG_FD:
2676         case VHOST_USER_SET_VRING_NUM:
2677         case VHOST_USER_SET_VRING_ADDR:
2678         case VHOST_USER_SET_VRING_BASE:
2679         case VHOST_USER_SET_VRING_KICK:
2680         case VHOST_USER_SET_VRING_CALL:
2681         case VHOST_USER_SET_VRING_ERR:
2682         case VHOST_USER_SET_VRING_ENABLE:
2683         case VHOST_USER_SEND_RARP:
2684         case VHOST_USER_NET_SET_MTU:
2685         case VHOST_USER_SET_SLAVE_REQ_FD:
2686                 vhost_user_lock_all_queue_pairs(dev);
2687                 unlock_required = 1;
2688                 break;
2689         default:
2690                 break;
2691
2692         }
2693
2694         handled = false;
2695         if (dev->extern_ops.pre_msg_handle) {
2696                 ret = (*dev->extern_ops.pre_msg_handle)(dev->vid,
2697                                 (void *)&msg);
2698                 switch (ret) {
2699                 case RTE_VHOST_MSG_RESULT_REPLY:
2700                         send_vhost_reply(fd, &msg);
2701                         /* Fall-through */
2702                 case RTE_VHOST_MSG_RESULT_ERR:
2703                 case RTE_VHOST_MSG_RESULT_OK:
2704                         handled = true;
2705                         goto skip_to_post_handle;
2706                 case RTE_VHOST_MSG_RESULT_NOT_HANDLED:
2707                 default:
2708                         break;
2709                 }
2710         }
2711
2712         if (request > VHOST_USER_NONE && request < VHOST_USER_MAX) {
2713                 if (!vhost_message_handlers[request])
2714                         goto skip_to_post_handle;
2715                 ret = vhost_message_handlers[request](&dev, &msg, fd);
2716
2717                 switch (ret) {
2718                 case RTE_VHOST_MSG_RESULT_ERR:
2719                         VHOST_LOG_CONFIG(ERR,
2720                                 "Processing %s failed.\n",
2721                                 vhost_message_str[request]);
2722                         handled = true;
2723                         break;
2724                 case RTE_VHOST_MSG_RESULT_OK:
2725                         VHOST_LOG_CONFIG(DEBUG,
2726                                 "Processing %s succeeded.\n",
2727                                 vhost_message_str[request]);
2728                         handled = true;
2729                         break;
2730                 case RTE_VHOST_MSG_RESULT_REPLY:
2731                         VHOST_LOG_CONFIG(DEBUG,
2732                                 "Processing %s succeeded and needs reply.\n",
2733                                 vhost_message_str[request]);
2734                         send_vhost_reply(fd, &msg);
2735                         handled = true;
2736                         break;
2737                 default:
2738                         break;
2739                 }
2740         }
2741
2742 skip_to_post_handle:
2743         if (ret != RTE_VHOST_MSG_RESULT_ERR &&
2744                         dev->extern_ops.post_msg_handle) {
2745                 ret = (*dev->extern_ops.post_msg_handle)(dev->vid,
2746                                 (void *)&msg);
2747                 switch (ret) {
2748                 case RTE_VHOST_MSG_RESULT_REPLY:
2749                         send_vhost_reply(fd, &msg);
2750                         /* Fall-through */
2751                 case RTE_VHOST_MSG_RESULT_ERR:
2752                 case RTE_VHOST_MSG_RESULT_OK:
2753                         handled = true;
2754                 case RTE_VHOST_MSG_RESULT_NOT_HANDLED:
2755                 default:
2756                         break;
2757                 }
2758         }
2759
2760         if (unlock_required)
2761                 vhost_user_unlock_all_queue_pairs(dev);
2762
2763         /* If message was not handled at this stage, treat it as an error */
2764         if (!handled) {
2765                 VHOST_LOG_CONFIG(ERR,
2766                         "vhost message (req: %d) was not handled.\n", request);
2767                 close_msg_fds(&msg);
2768                 ret = RTE_VHOST_MSG_RESULT_ERR;
2769         }
2770
2771         /*
2772          * If the request required a reply that was already sent,
2773          * this optional reply-ack won't be sent as the
2774          * VHOST_USER_NEED_REPLY was cleared in send_vhost_reply().
2775          */
2776         if (msg.flags & VHOST_USER_NEED_REPLY) {
2777                 msg.payload.u64 = ret == RTE_VHOST_MSG_RESULT_ERR;
2778                 msg.size = sizeof(msg.payload.u64);
2779                 msg.fd_num = 0;
2780                 send_vhost_reply(fd, &msg);
2781         } else if (ret == RTE_VHOST_MSG_RESULT_ERR) {
2782                 VHOST_LOG_CONFIG(ERR,
2783                         "vhost message handling failed.\n");
2784                 return -1;
2785         }
2786
2787         if (!(dev->flags & VIRTIO_DEV_RUNNING) && virtio_is_ready(dev)) {
2788                 dev->flags |= VIRTIO_DEV_READY;
2789
2790                 if (!(dev->flags & VIRTIO_DEV_RUNNING)) {
2791                         if (dev->dequeue_zero_copy) {
2792                                 VHOST_LOG_CONFIG(INFO,
2793                                                 "dequeue zero copy is enabled\n");
2794                         }
2795
2796                         if (dev->notify_ops->new_device(dev->vid) == 0)
2797                                 dev->flags |= VIRTIO_DEV_RUNNING;
2798                 }
2799         }
2800
2801         vdpa_dev = dev->vdpa_dev;
2802         if (vdpa_dev && virtio_is_ready(dev) &&
2803                         !(dev->flags & VIRTIO_DEV_VDPA_CONFIGURED) &&
2804                         msg.request.master == VHOST_USER_SET_VRING_CALL) {
2805                 if (vdpa_dev->ops->dev_conf)
2806                         vdpa_dev->ops->dev_conf(dev->vid);
2807                 dev->flags |= VIRTIO_DEV_VDPA_CONFIGURED;
2808         }
2809
2810         return 0;
2811 }
2812
2813 static int process_slave_message_reply(struct virtio_net *dev,
2814                                        const struct VhostUserMsg *msg)
2815 {
2816         struct VhostUserMsg msg_reply;
2817         int ret;
2818
2819         if ((msg->flags & VHOST_USER_NEED_REPLY) == 0)
2820                 return 0;
2821
2822         ret = read_vhost_message(dev->slave_req_fd, &msg_reply);
2823         if (ret <= 0) {
2824                 if (ret < 0)
2825                         VHOST_LOG_CONFIG(ERR,
2826                                 "vhost read slave message reply failed\n");
2827                 else
2828                         VHOST_LOG_CONFIG(INFO,
2829                                 "vhost peer closed\n");
2830                 ret = -1;
2831                 goto out;
2832         }
2833
2834         ret = 0;
2835         if (msg_reply.request.slave != msg->request.slave) {
2836                 VHOST_LOG_CONFIG(ERR,
2837                         "Received unexpected msg type (%u), expected %u\n",
2838                         msg_reply.request.slave, msg->request.slave);
2839                 ret = -1;
2840                 goto out;
2841         }
2842
2843         ret = msg_reply.payload.u64 ? -1 : 0;
2844
2845 out:
2846         rte_spinlock_unlock(&dev->slave_req_lock);
2847         return ret;
2848 }
2849
2850 int
2851 vhost_user_iotlb_miss(struct virtio_net *dev, uint64_t iova, uint8_t perm)
2852 {
2853         int ret;
2854         struct VhostUserMsg msg = {
2855                 .request.slave = VHOST_USER_SLAVE_IOTLB_MSG,
2856                 .flags = VHOST_USER_VERSION,
2857                 .size = sizeof(msg.payload.iotlb),
2858                 .payload.iotlb = {
2859                         .iova = iova,
2860                         .perm = perm,
2861                         .type = VHOST_IOTLB_MISS,
2862                 },
2863         };
2864
2865         ret = send_vhost_message(dev->slave_req_fd, &msg);
2866         if (ret < 0) {
2867                 VHOST_LOG_CONFIG(ERR,
2868                                 "Failed to send IOTLB miss message (%d)\n",
2869                                 ret);
2870                 return ret;
2871         }
2872
2873         return 0;
2874 }
2875
2876 static int
2877 vhost_user_slave_config_change(struct virtio_net *dev, bool need_reply)
2878 {
2879         int ret;
2880         struct VhostUserMsg msg = {
2881                 .request.slave = VHOST_USER_SLAVE_CONFIG_CHANGE_MSG,
2882                 .flags = VHOST_USER_VERSION,
2883                 .size = 0,
2884         };
2885
2886         if (need_reply)
2887                 msg.flags |= VHOST_USER_NEED_REPLY;
2888
2889         ret = send_vhost_slave_message(dev, &msg);
2890         if (ret < 0) {
2891                 VHOST_LOG_CONFIG(ERR,
2892                                 "Failed to send config change (%d)\n",
2893                                 ret);
2894                 return ret;
2895         }
2896
2897         return process_slave_message_reply(dev, &msg);
2898 }
2899
2900 int
2901 rte_vhost_slave_config_change(int vid, bool need_reply)
2902 {
2903         struct virtio_net *dev;
2904
2905         dev = get_device(vid);
2906         if (!dev)
2907                 return -ENODEV;
2908
2909         return vhost_user_slave_config_change(dev, need_reply);
2910 }
2911
2912 static int vhost_user_slave_set_vring_host_notifier(struct virtio_net *dev,
2913                                                     int index, int fd,
2914                                                     uint64_t offset,
2915                                                     uint64_t size)
2916 {
2917         int ret;
2918         struct VhostUserMsg msg = {
2919                 .request.slave = VHOST_USER_SLAVE_VRING_HOST_NOTIFIER_MSG,
2920                 .flags = VHOST_USER_VERSION | VHOST_USER_NEED_REPLY,
2921                 .size = sizeof(msg.payload.area),
2922                 .payload.area = {
2923                         .u64 = index & VHOST_USER_VRING_IDX_MASK,
2924                         .size = size,
2925                         .offset = offset,
2926                 },
2927         };
2928
2929         if (fd < 0)
2930                 msg.payload.area.u64 |= VHOST_USER_VRING_NOFD_MASK;
2931         else {
2932                 msg.fds[0] = fd;
2933                 msg.fd_num = 1;
2934         }
2935
2936         ret = send_vhost_slave_message(dev, &msg);
2937         if (ret < 0) {
2938                 VHOST_LOG_CONFIG(ERR,
2939                         "Failed to set host notifier (%d)\n", ret);
2940                 return ret;
2941         }
2942
2943         return process_slave_message_reply(dev, &msg);
2944 }
2945
2946 int rte_vhost_host_notifier_ctrl(int vid, uint16_t qid, bool enable)
2947 {
2948         struct virtio_net *dev;
2949         struct rte_vdpa_device *vdpa_dev;
2950         int vfio_device_fd, ret = 0;
2951         uint64_t offset, size;
2952         unsigned int i, q_start, q_last;
2953
2954         dev = get_device(vid);
2955         if (!dev)
2956                 return -ENODEV;
2957
2958         vdpa_dev = dev->vdpa_dev;
2959         if (vdpa_dev == NULL)
2960                 return -ENODEV;
2961
2962         if (!(dev->features & (1ULL << VIRTIO_F_VERSION_1)) ||
2963             !(dev->features & (1ULL << VHOST_USER_F_PROTOCOL_FEATURES)) ||
2964             !(dev->protocol_features &
2965                         (1ULL << VHOST_USER_PROTOCOL_F_SLAVE_REQ)) ||
2966             !(dev->protocol_features &
2967                         (1ULL << VHOST_USER_PROTOCOL_F_SLAVE_SEND_FD)) ||
2968             !(dev->protocol_features &
2969                         (1ULL << VHOST_USER_PROTOCOL_F_HOST_NOTIFIER)))
2970                 return -ENOTSUP;
2971
2972         if (qid == RTE_VHOST_QUEUE_ALL) {
2973                 q_start = 0;
2974                 q_last = dev->nr_vring - 1;
2975         } else {
2976                 if (qid >= dev->nr_vring)
2977                         return -EINVAL;
2978                 q_start = qid;
2979                 q_last = qid;
2980         }
2981
2982         RTE_FUNC_PTR_OR_ERR_RET(vdpa_dev->ops->get_vfio_device_fd, -ENOTSUP);
2983         RTE_FUNC_PTR_OR_ERR_RET(vdpa_dev->ops->get_notify_area, -ENOTSUP);
2984
2985         vfio_device_fd = vdpa_dev->ops->get_vfio_device_fd(vid);
2986         if (vfio_device_fd < 0)
2987                 return -ENOTSUP;
2988
2989         if (enable) {
2990                 for (i = q_start; i <= q_last; i++) {
2991                         if (vdpa_dev->ops->get_notify_area(vid, i, &offset,
2992                                         &size) < 0) {
2993                                 ret = -ENOTSUP;
2994                                 goto disable;
2995                         }
2996
2997                         if (vhost_user_slave_set_vring_host_notifier(dev, i,
2998                                         vfio_device_fd, offset, size) < 0) {
2999                                 ret = -EFAULT;
3000                                 goto disable;
3001                         }
3002                 }
3003         } else {
3004 disable:
3005                 for (i = q_start; i <= q_last; i++) {
3006                         vhost_user_slave_set_vring_host_notifier(dev, i, -1,
3007                                         0, 0);
3008                 }
3009         }
3010
3011         return ret;
3012 }