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