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