crypto/mlx5: add maximum segments configuration
[dpdk.git] / lib / 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
1252         if (validate_msg_fds(msg, memory->nregions) != 0)
1253                 return RTE_VHOST_MSG_RESULT_ERR;
1254
1255         if (memory->nregions > VHOST_MEMORY_MAX_NREGIONS) {
1256                 VHOST_LOG_CONFIG(ERR,
1257                         "too many memory regions (%u)\n", memory->nregions);
1258                 goto close_msg_fds;
1259         }
1260
1261         if (dev->mem && !vhost_memory_changed(memory, dev->mem)) {
1262                 VHOST_LOG_CONFIG(INFO,
1263                         "(%d) memory regions not changed\n", dev->vid);
1264
1265                 close_msg_fds(msg);
1266
1267                 return RTE_VHOST_MSG_RESULT_OK;
1268         }
1269
1270         if (dev->mem) {
1271                 if (dev->flags & VIRTIO_DEV_VDPA_CONFIGURED) {
1272                         struct rte_vdpa_device *vdpa_dev = dev->vdpa_dev;
1273
1274                         if (vdpa_dev && vdpa_dev->ops->dev_close)
1275                                 vdpa_dev->ops->dev_close(dev->vid);
1276                         dev->flags &= ~VIRTIO_DEV_VDPA_CONFIGURED;
1277                 }
1278                 free_mem_region(dev);
1279                 rte_free(dev->mem);
1280                 dev->mem = NULL;
1281         }
1282
1283         /* Flush IOTLB cache as previous HVAs are now invalid */
1284         if (dev->features & (1ULL << VIRTIO_F_IOMMU_PLATFORM))
1285                 for (i = 0; i < dev->nr_vring; i++)
1286                         vhost_user_iotlb_flush_all(dev->virtqueue[i]);
1287
1288         /*
1289          * If VQ 0 has already been allocated, try to allocate on the same
1290          * NUMA node. It can be reallocated later in numa_realloc().
1291          */
1292         if (dev->nr_vring > 0)
1293                 numa_node = dev->virtqueue[0]->numa_node;
1294
1295         dev->nr_guest_pages = 0;
1296         if (dev->guest_pages == NULL) {
1297                 dev->max_guest_pages = 8;
1298                 dev->guest_pages = rte_zmalloc_socket(NULL,
1299                                         dev->max_guest_pages *
1300                                         sizeof(struct guest_page),
1301                                         RTE_CACHE_LINE_SIZE,
1302                                         numa_node);
1303                 if (dev->guest_pages == NULL) {
1304                         VHOST_LOG_CONFIG(ERR,
1305                                 "(%d) failed to allocate memory "
1306                                 "for dev->guest_pages\n",
1307                                 dev->vid);
1308                         goto close_msg_fds;
1309                 }
1310         }
1311
1312         dev->mem = rte_zmalloc_socket("vhost-mem-table", sizeof(struct rte_vhost_memory) +
1313                 sizeof(struct rte_vhost_mem_region) * memory->nregions, 0, numa_node);
1314         if (dev->mem == NULL) {
1315                 VHOST_LOG_CONFIG(ERR,
1316                         "(%d) failed to allocate memory for dev->mem\n",
1317                         dev->vid);
1318                 goto free_guest_pages;
1319         }
1320
1321         for (i = 0; i < memory->nregions; i++) {
1322                 reg = &dev->mem->regions[i];
1323
1324                 reg->guest_phys_addr = memory->regions[i].guest_phys_addr;
1325                 reg->guest_user_addr = memory->regions[i].userspace_addr;
1326                 reg->size            = memory->regions[i].memory_size;
1327                 reg->fd              = msg->fds[i];
1328
1329                 /*
1330                  * Assign invalid file descriptor value to avoid double
1331                  * closing on error path.
1332                  */
1333                 msg->fds[i] = -1;
1334
1335                 mmap_offset = memory->regions[i].mmap_offset;
1336
1337                 if (vhost_user_mmap_region(dev, reg, mmap_offset) < 0) {
1338                         VHOST_LOG_CONFIG(ERR, "Failed to mmap region %u\n", i);
1339                         goto free_mem_table;
1340                 }
1341
1342                 dev->mem->nregions++;
1343         }
1344
1345         if (vhost_user_postcopy_register(dev, main_fd, msg) < 0)
1346                 goto free_mem_table;
1347
1348         for (i = 0; i < dev->nr_vring; i++) {
1349                 struct vhost_virtqueue *vq = dev->virtqueue[i];
1350
1351                 if (!vq)
1352                         continue;
1353
1354                 if (vq->desc || vq->avail || vq->used) {
1355                         /*
1356                          * If the memory table got updated, the ring addresses
1357                          * need to be translated again as virtual addresses have
1358                          * changed.
1359                          */
1360                         vring_invalidate(dev, vq);
1361
1362                         dev = translate_ring_addresses(dev, i);
1363                         if (!dev) {
1364                                 dev = *pdev;
1365                                 goto free_mem_table;
1366                         }
1367
1368                         *pdev = dev;
1369                 }
1370         }
1371
1372         dump_guest_pages(dev);
1373
1374         return RTE_VHOST_MSG_RESULT_OK;
1375
1376 free_mem_table:
1377         free_mem_region(dev);
1378         rte_free(dev->mem);
1379         dev->mem = NULL;
1380 free_guest_pages:
1381         rte_free(dev->guest_pages);
1382         dev->guest_pages = NULL;
1383 close_msg_fds:
1384         close_msg_fds(msg);
1385         return RTE_VHOST_MSG_RESULT_ERR;
1386 }
1387
1388 static bool
1389 vq_is_ready(struct virtio_net *dev, struct vhost_virtqueue *vq)
1390 {
1391         bool rings_ok;
1392
1393         if (!vq)
1394                 return false;
1395
1396         if (vq_is_packed(dev))
1397                 rings_ok = vq->desc_packed && vq->driver_event &&
1398                         vq->device_event;
1399         else
1400                 rings_ok = vq->desc && vq->avail && vq->used;
1401
1402         return rings_ok &&
1403                vq->kickfd != VIRTIO_UNINITIALIZED_EVENTFD &&
1404                vq->callfd != VIRTIO_UNINITIALIZED_EVENTFD &&
1405                vq->enabled;
1406 }
1407
1408 #define VIRTIO_BUILTIN_NUM_VQS_TO_BE_READY 2u
1409
1410 static int
1411 virtio_is_ready(struct virtio_net *dev)
1412 {
1413         struct vhost_virtqueue *vq;
1414         uint32_t i, nr_vring = dev->nr_vring;
1415
1416         if (dev->flags & VIRTIO_DEV_READY)
1417                 return 1;
1418
1419         if (!dev->nr_vring)
1420                 return 0;
1421
1422         if (dev->flags & VIRTIO_DEV_BUILTIN_VIRTIO_NET) {
1423                 nr_vring = VIRTIO_BUILTIN_NUM_VQS_TO_BE_READY;
1424
1425                 if (dev->nr_vring < nr_vring)
1426                         return 0;
1427         }
1428
1429         for (i = 0; i < nr_vring; i++) {
1430                 vq = dev->virtqueue[i];
1431
1432                 if (!vq_is_ready(dev, vq))
1433                         return 0;
1434         }
1435
1436         /* If supported, ensure the frontend is really done with config */
1437         if (dev->protocol_features & (1ULL << VHOST_USER_PROTOCOL_F_STATUS))
1438                 if (!(dev->status & VIRTIO_DEVICE_STATUS_DRIVER_OK))
1439                         return 0;
1440
1441         dev->flags |= VIRTIO_DEV_READY;
1442
1443         if (!(dev->flags & VIRTIO_DEV_RUNNING))
1444                 VHOST_LOG_CONFIG(INFO,
1445                         "virtio is now ready for processing.\n");
1446         return 1;
1447 }
1448
1449 static void *
1450 inflight_mem_alloc(const char *name, size_t size, int *fd)
1451 {
1452         void *ptr;
1453         int mfd = -1;
1454         char fname[20] = "/tmp/memfd-XXXXXX";
1455
1456         *fd = -1;
1457 #ifdef MEMFD_SUPPORTED
1458         mfd = memfd_create(name, MFD_CLOEXEC);
1459 #else
1460         RTE_SET_USED(name);
1461 #endif
1462         if (mfd == -1) {
1463                 mfd = mkstemp(fname);
1464                 if (mfd == -1) {
1465                         VHOST_LOG_CONFIG(ERR,
1466                                 "failed to get inflight buffer fd\n");
1467                         return NULL;
1468                 }
1469
1470                 unlink(fname);
1471         }
1472
1473         if (ftruncate(mfd, size) == -1) {
1474                 VHOST_LOG_CONFIG(ERR,
1475                         "failed to alloc inflight buffer\n");
1476                 close(mfd);
1477                 return NULL;
1478         }
1479
1480         ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, mfd, 0);
1481         if (ptr == MAP_FAILED) {
1482                 VHOST_LOG_CONFIG(ERR,
1483                         "failed to mmap inflight buffer\n");
1484                 close(mfd);
1485                 return NULL;
1486         }
1487
1488         *fd = mfd;
1489         return ptr;
1490 }
1491
1492 static uint32_t
1493 get_pervq_shm_size_split(uint16_t queue_size)
1494 {
1495         return RTE_ALIGN_MUL_CEIL(sizeof(struct rte_vhost_inflight_desc_split) *
1496                                   queue_size + sizeof(uint64_t) +
1497                                   sizeof(uint16_t) * 4, INFLIGHT_ALIGNMENT);
1498 }
1499
1500 static uint32_t
1501 get_pervq_shm_size_packed(uint16_t queue_size)
1502 {
1503         return RTE_ALIGN_MUL_CEIL(sizeof(struct rte_vhost_inflight_desc_packed)
1504                                   * queue_size + sizeof(uint64_t) +
1505                                   sizeof(uint16_t) * 6 + sizeof(uint8_t) * 9,
1506                                   INFLIGHT_ALIGNMENT);
1507 }
1508
1509 static int
1510 vhost_user_get_inflight_fd(struct virtio_net **pdev,
1511                            VhostUserMsg *msg,
1512                            int main_fd __rte_unused)
1513 {
1514         struct rte_vhost_inflight_info_packed *inflight_packed;
1515         uint64_t pervq_inflight_size, mmap_size;
1516         uint16_t num_queues, queue_size;
1517         struct virtio_net *dev = *pdev;
1518         int fd, i, j;
1519         int numa_node = SOCKET_ID_ANY;
1520         void *addr;
1521
1522         if (msg->size != sizeof(msg->payload.inflight)) {
1523                 VHOST_LOG_CONFIG(ERR,
1524                         "invalid get_inflight_fd message size is %d\n",
1525                         msg->size);
1526                 return RTE_VHOST_MSG_RESULT_ERR;
1527         }
1528
1529         /*
1530          * If VQ 0 has already been allocated, try to allocate on the same
1531          * NUMA node. It can be reallocated later in numa_realloc().
1532          */
1533         if (dev->nr_vring > 0)
1534                 numa_node = dev->virtqueue[0]->numa_node;
1535
1536         if (dev->inflight_info == NULL) {
1537                 dev->inflight_info = rte_zmalloc_socket("inflight_info",
1538                                 sizeof(struct inflight_mem_info), 0, numa_node);
1539                 if (!dev->inflight_info) {
1540                         VHOST_LOG_CONFIG(ERR,
1541                                 "failed to alloc dev inflight area\n");
1542                         return RTE_VHOST_MSG_RESULT_ERR;
1543                 }
1544                 dev->inflight_info->fd = -1;
1545         }
1546
1547         num_queues = msg->payload.inflight.num_queues;
1548         queue_size = msg->payload.inflight.queue_size;
1549
1550         VHOST_LOG_CONFIG(INFO, "get_inflight_fd num_queues: %u\n",
1551                 msg->payload.inflight.num_queues);
1552         VHOST_LOG_CONFIG(INFO, "get_inflight_fd queue_size: %u\n",
1553                 msg->payload.inflight.queue_size);
1554
1555         if (vq_is_packed(dev))
1556                 pervq_inflight_size = get_pervq_shm_size_packed(queue_size);
1557         else
1558                 pervq_inflight_size = get_pervq_shm_size_split(queue_size);
1559
1560         mmap_size = num_queues * pervq_inflight_size;
1561         addr = inflight_mem_alloc("vhost-inflight", mmap_size, &fd);
1562         if (!addr) {
1563                 VHOST_LOG_CONFIG(ERR,
1564                         "failed to alloc vhost inflight area\n");
1565                         msg->payload.inflight.mmap_size = 0;
1566                 return RTE_VHOST_MSG_RESULT_ERR;
1567         }
1568         memset(addr, 0, mmap_size);
1569
1570         if (dev->inflight_info->addr) {
1571                 munmap(dev->inflight_info->addr, dev->inflight_info->size);
1572                 dev->inflight_info->addr = NULL;
1573         }
1574
1575         if (dev->inflight_info->fd >= 0) {
1576                 close(dev->inflight_info->fd);
1577                 dev->inflight_info->fd = -1;
1578         }
1579
1580         dev->inflight_info->addr = addr;
1581         dev->inflight_info->size = msg->payload.inflight.mmap_size = mmap_size;
1582         dev->inflight_info->fd = msg->fds[0] = fd;
1583         msg->payload.inflight.mmap_offset = 0;
1584         msg->fd_num = 1;
1585
1586         if (vq_is_packed(dev)) {
1587                 for (i = 0; i < num_queues; i++) {
1588                         inflight_packed =
1589                                 (struct rte_vhost_inflight_info_packed *)addr;
1590                         inflight_packed->used_wrap_counter = 1;
1591                         inflight_packed->old_used_wrap_counter = 1;
1592                         for (j = 0; j < queue_size; j++)
1593                                 inflight_packed->desc[j].next = j + 1;
1594                         addr = (void *)((char *)addr + pervq_inflight_size);
1595                 }
1596         }
1597
1598         VHOST_LOG_CONFIG(INFO,
1599                 "send inflight mmap_size: %"PRIu64"\n",
1600                 msg->payload.inflight.mmap_size);
1601         VHOST_LOG_CONFIG(INFO,
1602                 "send inflight mmap_offset: %"PRIu64"\n",
1603                 msg->payload.inflight.mmap_offset);
1604         VHOST_LOG_CONFIG(INFO,
1605                 "send inflight fd: %d\n", msg->fds[0]);
1606
1607         return RTE_VHOST_MSG_RESULT_REPLY;
1608 }
1609
1610 static int
1611 vhost_user_set_inflight_fd(struct virtio_net **pdev, VhostUserMsg *msg,
1612                            int main_fd __rte_unused)
1613 {
1614         uint64_t mmap_size, mmap_offset;
1615         uint16_t num_queues, queue_size;
1616         struct virtio_net *dev = *pdev;
1617         uint32_t pervq_inflight_size;
1618         struct vhost_virtqueue *vq;
1619         void *addr;
1620         int fd, i;
1621         int numa_node = SOCKET_ID_ANY;
1622
1623         fd = msg->fds[0];
1624         if (msg->size != sizeof(msg->payload.inflight) || fd < 0) {
1625                 VHOST_LOG_CONFIG(ERR,
1626                         "invalid set_inflight_fd message size is %d,fd is %d\n",
1627                         msg->size, fd);
1628                 return RTE_VHOST_MSG_RESULT_ERR;
1629         }
1630
1631         mmap_size = msg->payload.inflight.mmap_size;
1632         mmap_offset = msg->payload.inflight.mmap_offset;
1633         num_queues = msg->payload.inflight.num_queues;
1634         queue_size = msg->payload.inflight.queue_size;
1635
1636         if (vq_is_packed(dev))
1637                 pervq_inflight_size = get_pervq_shm_size_packed(queue_size);
1638         else
1639                 pervq_inflight_size = get_pervq_shm_size_split(queue_size);
1640
1641         VHOST_LOG_CONFIG(INFO,
1642                 "set_inflight_fd mmap_size: %"PRIu64"\n", mmap_size);
1643         VHOST_LOG_CONFIG(INFO,
1644                 "set_inflight_fd mmap_offset: %"PRIu64"\n", mmap_offset);
1645         VHOST_LOG_CONFIG(INFO,
1646                 "set_inflight_fd num_queues: %u\n", num_queues);
1647         VHOST_LOG_CONFIG(INFO,
1648                 "set_inflight_fd queue_size: %u\n", queue_size);
1649         VHOST_LOG_CONFIG(INFO,
1650                 "set_inflight_fd fd: %d\n", fd);
1651         VHOST_LOG_CONFIG(INFO,
1652                 "set_inflight_fd pervq_inflight_size: %d\n",
1653                 pervq_inflight_size);
1654
1655         /*
1656          * If VQ 0 has already been allocated, try to allocate on the same
1657          * NUMA node. It can be reallocated later in numa_realloc().
1658          */
1659         if (dev->nr_vring > 0)
1660                 numa_node = dev->virtqueue[0]->numa_node;
1661
1662         if (!dev->inflight_info) {
1663                 dev->inflight_info = rte_zmalloc_socket("inflight_info",
1664                                 sizeof(struct inflight_mem_info), 0, numa_node);
1665                 if (dev->inflight_info == NULL) {
1666                         VHOST_LOG_CONFIG(ERR,
1667                                 "failed to alloc dev inflight area\n");
1668                         return RTE_VHOST_MSG_RESULT_ERR;
1669                 }
1670                 dev->inflight_info->fd = -1;
1671         }
1672
1673         if (dev->inflight_info->addr) {
1674                 munmap(dev->inflight_info->addr, dev->inflight_info->size);
1675                 dev->inflight_info->addr = NULL;
1676         }
1677
1678         addr = mmap(0, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
1679                     fd, mmap_offset);
1680         if (addr == MAP_FAILED) {
1681                 VHOST_LOG_CONFIG(ERR, "failed to mmap share memory.\n");
1682                 return RTE_VHOST_MSG_RESULT_ERR;
1683         }
1684
1685         if (dev->inflight_info->fd >= 0) {
1686                 close(dev->inflight_info->fd);
1687                 dev->inflight_info->fd = -1;
1688         }
1689
1690         dev->inflight_info->fd = fd;
1691         dev->inflight_info->addr = addr;
1692         dev->inflight_info->size = mmap_size;
1693
1694         for (i = 0; i < num_queues; i++) {
1695                 vq = dev->virtqueue[i];
1696                 if (!vq)
1697                         continue;
1698
1699                 if (vq_is_packed(dev)) {
1700                         vq->inflight_packed = addr;
1701                         vq->inflight_packed->desc_num = queue_size;
1702                 } else {
1703                         vq->inflight_split = addr;
1704                         vq->inflight_split->desc_num = queue_size;
1705                 }
1706                 addr = (void *)((char *)addr + pervq_inflight_size);
1707         }
1708
1709         return RTE_VHOST_MSG_RESULT_OK;
1710 }
1711
1712 static int
1713 vhost_user_set_vring_call(struct virtio_net **pdev, struct VhostUserMsg *msg,
1714                         int main_fd __rte_unused)
1715 {
1716         struct virtio_net *dev = *pdev;
1717         struct vhost_vring_file file;
1718         struct vhost_virtqueue *vq;
1719         int expected_fds;
1720
1721         expected_fds = (msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK) ? 0 : 1;
1722         if (validate_msg_fds(msg, expected_fds) != 0)
1723                 return RTE_VHOST_MSG_RESULT_ERR;
1724
1725         file.index = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
1726         if (msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK)
1727                 file.fd = VIRTIO_INVALID_EVENTFD;
1728         else
1729                 file.fd = msg->fds[0];
1730         VHOST_LOG_CONFIG(INFO,
1731                 "vring call idx:%d file:%d\n", file.index, file.fd);
1732
1733         vq = dev->virtqueue[file.index];
1734
1735         if (vq->ready) {
1736                 vq->ready = false;
1737                 vhost_user_notify_queue_state(dev, file.index, 0);
1738         }
1739
1740         if (vq->callfd >= 0)
1741                 close(vq->callfd);
1742
1743         vq->callfd = file.fd;
1744
1745         return RTE_VHOST_MSG_RESULT_OK;
1746 }
1747
1748 static int vhost_user_set_vring_err(struct virtio_net **pdev __rte_unused,
1749                         struct VhostUserMsg *msg,
1750                         int main_fd __rte_unused)
1751 {
1752         int expected_fds;
1753
1754         expected_fds = (msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK) ? 0 : 1;
1755         if (validate_msg_fds(msg, expected_fds) != 0)
1756                 return RTE_VHOST_MSG_RESULT_ERR;
1757
1758         if (!(msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK))
1759                 close(msg->fds[0]);
1760         VHOST_LOG_CONFIG(INFO, "not implemented\n");
1761
1762         return RTE_VHOST_MSG_RESULT_OK;
1763 }
1764
1765 static int
1766 resubmit_desc_compare(const void *a, const void *b)
1767 {
1768         const struct rte_vhost_resubmit_desc *desc0 = a;
1769         const struct rte_vhost_resubmit_desc *desc1 = b;
1770
1771         if (desc1->counter > desc0->counter)
1772                 return 1;
1773
1774         return -1;
1775 }
1776
1777 static int
1778 vhost_check_queue_inflights_split(struct virtio_net *dev,
1779                                   struct vhost_virtqueue *vq)
1780 {
1781         uint16_t i;
1782         uint16_t resubmit_num = 0, last_io, num;
1783         struct vring_used *used = vq->used;
1784         struct rte_vhost_resubmit_info *resubmit;
1785         struct rte_vhost_inflight_info_split *inflight_split;
1786
1787         if (!(dev->protocol_features &
1788             (1ULL << VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)))
1789                 return RTE_VHOST_MSG_RESULT_OK;
1790
1791         /* The frontend may still not support the inflight feature
1792          * although we negotiate the protocol feature.
1793          */
1794         if ((!vq->inflight_split))
1795                 return RTE_VHOST_MSG_RESULT_OK;
1796
1797         if (!vq->inflight_split->version) {
1798                 vq->inflight_split->version = INFLIGHT_VERSION;
1799                 return RTE_VHOST_MSG_RESULT_OK;
1800         }
1801
1802         if (vq->resubmit_inflight)
1803                 return RTE_VHOST_MSG_RESULT_OK;
1804
1805         inflight_split = vq->inflight_split;
1806         vq->global_counter = 0;
1807         last_io = inflight_split->last_inflight_io;
1808
1809         if (inflight_split->used_idx != used->idx) {
1810                 inflight_split->desc[last_io].inflight = 0;
1811                 rte_atomic_thread_fence(__ATOMIC_SEQ_CST);
1812                 inflight_split->used_idx = used->idx;
1813         }
1814
1815         for (i = 0; i < inflight_split->desc_num; i++) {
1816                 if (inflight_split->desc[i].inflight == 1)
1817                         resubmit_num++;
1818         }
1819
1820         vq->last_avail_idx += resubmit_num;
1821
1822         if (resubmit_num) {
1823                 resubmit = rte_zmalloc_socket("resubmit", sizeof(struct rte_vhost_resubmit_info),
1824                                 0, vq->numa_node);
1825                 if (!resubmit) {
1826                         VHOST_LOG_CONFIG(ERR,
1827                                 "failed to allocate memory for resubmit info.\n");
1828                         return RTE_VHOST_MSG_RESULT_ERR;
1829                 }
1830
1831                 resubmit->resubmit_list = rte_zmalloc_socket("resubmit_list",
1832                                 resubmit_num * sizeof(struct rte_vhost_resubmit_desc),
1833                                 0, vq->numa_node);
1834                 if (!resubmit->resubmit_list) {
1835                         VHOST_LOG_CONFIG(ERR,
1836                                 "failed to allocate memory for inflight desc.\n");
1837                         rte_free(resubmit);
1838                         return RTE_VHOST_MSG_RESULT_ERR;
1839                 }
1840
1841                 num = 0;
1842                 for (i = 0; i < vq->inflight_split->desc_num; i++) {
1843                         if (vq->inflight_split->desc[i].inflight == 1) {
1844                                 resubmit->resubmit_list[num].index = i;
1845                                 resubmit->resubmit_list[num].counter =
1846                                         inflight_split->desc[i].counter;
1847                                 num++;
1848                         }
1849                 }
1850                 resubmit->resubmit_num = num;
1851
1852                 if (resubmit->resubmit_num > 1)
1853                         qsort(resubmit->resubmit_list, resubmit->resubmit_num,
1854                               sizeof(struct rte_vhost_resubmit_desc),
1855                               resubmit_desc_compare);
1856
1857                 vq->global_counter = resubmit->resubmit_list[0].counter + 1;
1858                 vq->resubmit_inflight = resubmit;
1859         }
1860
1861         return RTE_VHOST_MSG_RESULT_OK;
1862 }
1863
1864 static int
1865 vhost_check_queue_inflights_packed(struct virtio_net *dev,
1866                                    struct vhost_virtqueue *vq)
1867 {
1868         uint16_t i;
1869         uint16_t resubmit_num = 0, old_used_idx, num;
1870         struct rte_vhost_resubmit_info *resubmit;
1871         struct rte_vhost_inflight_info_packed *inflight_packed;
1872
1873         if (!(dev->protocol_features &
1874             (1ULL << VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)))
1875                 return RTE_VHOST_MSG_RESULT_OK;
1876
1877         /* The frontend may still not support the inflight feature
1878          * although we negotiate the protocol feature.
1879          */
1880         if ((!vq->inflight_packed))
1881                 return RTE_VHOST_MSG_RESULT_OK;
1882
1883         if (!vq->inflight_packed->version) {
1884                 vq->inflight_packed->version = INFLIGHT_VERSION;
1885                 return RTE_VHOST_MSG_RESULT_OK;
1886         }
1887
1888         if (vq->resubmit_inflight)
1889                 return RTE_VHOST_MSG_RESULT_OK;
1890
1891         inflight_packed = vq->inflight_packed;
1892         vq->global_counter = 0;
1893         old_used_idx = inflight_packed->old_used_idx;
1894
1895         if (inflight_packed->used_idx != old_used_idx) {
1896                 if (inflight_packed->desc[old_used_idx].inflight == 0) {
1897                         inflight_packed->old_used_idx =
1898                                 inflight_packed->used_idx;
1899                         inflight_packed->old_used_wrap_counter =
1900                                 inflight_packed->used_wrap_counter;
1901                         inflight_packed->old_free_head =
1902                                 inflight_packed->free_head;
1903                 } else {
1904                         inflight_packed->used_idx =
1905                                 inflight_packed->old_used_idx;
1906                         inflight_packed->used_wrap_counter =
1907                                 inflight_packed->old_used_wrap_counter;
1908                         inflight_packed->free_head =
1909                                 inflight_packed->old_free_head;
1910                 }
1911         }
1912
1913         for (i = 0; i < inflight_packed->desc_num; i++) {
1914                 if (inflight_packed->desc[i].inflight == 1)
1915                         resubmit_num++;
1916         }
1917
1918         if (resubmit_num) {
1919                 resubmit = rte_zmalloc_socket("resubmit", sizeof(struct rte_vhost_resubmit_info),
1920                                 0, vq->numa_node);
1921                 if (resubmit == NULL) {
1922                         VHOST_LOG_CONFIG(ERR,
1923                                 "failed to allocate memory for resubmit info.\n");
1924                         return RTE_VHOST_MSG_RESULT_ERR;
1925                 }
1926
1927                 resubmit->resubmit_list = rte_zmalloc_socket("resubmit_list",
1928                                 resubmit_num * sizeof(struct rte_vhost_resubmit_desc),
1929                                 0, vq->numa_node);
1930                 if (resubmit->resubmit_list == NULL) {
1931                         VHOST_LOG_CONFIG(ERR,
1932                                 "failed to allocate memory for resubmit desc.\n");
1933                         rte_free(resubmit);
1934                         return RTE_VHOST_MSG_RESULT_ERR;
1935                 }
1936
1937                 num = 0;
1938                 for (i = 0; i < inflight_packed->desc_num; i++) {
1939                         if (vq->inflight_packed->desc[i].inflight == 1) {
1940                                 resubmit->resubmit_list[num].index = i;
1941                                 resubmit->resubmit_list[num].counter =
1942                                         inflight_packed->desc[i].counter;
1943                                 num++;
1944                         }
1945                 }
1946                 resubmit->resubmit_num = num;
1947
1948                 if (resubmit->resubmit_num > 1)
1949                         qsort(resubmit->resubmit_list, resubmit->resubmit_num,
1950                               sizeof(struct rte_vhost_resubmit_desc),
1951                               resubmit_desc_compare);
1952
1953                 vq->global_counter = resubmit->resubmit_list[0].counter + 1;
1954                 vq->resubmit_inflight = resubmit;
1955         }
1956
1957         return RTE_VHOST_MSG_RESULT_OK;
1958 }
1959
1960 static int
1961 vhost_user_set_vring_kick(struct virtio_net **pdev, struct VhostUserMsg *msg,
1962                         int main_fd __rte_unused)
1963 {
1964         struct virtio_net *dev = *pdev;
1965         struct vhost_vring_file file;
1966         struct vhost_virtqueue *vq;
1967         int expected_fds;
1968
1969         expected_fds = (msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK) ? 0 : 1;
1970         if (validate_msg_fds(msg, expected_fds) != 0)
1971                 return RTE_VHOST_MSG_RESULT_ERR;
1972
1973         file.index = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
1974         if (msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK)
1975                 file.fd = VIRTIO_INVALID_EVENTFD;
1976         else
1977                 file.fd = msg->fds[0];
1978         VHOST_LOG_CONFIG(INFO,
1979                 "vring kick idx:%d file:%d\n", file.index, file.fd);
1980
1981         /* Interpret ring addresses only when ring is started. */
1982         dev = translate_ring_addresses(dev, file.index);
1983         if (!dev) {
1984                 if (file.fd != VIRTIO_INVALID_EVENTFD)
1985                         close(file.fd);
1986
1987                 return RTE_VHOST_MSG_RESULT_ERR;
1988         }
1989
1990         *pdev = dev;
1991
1992         vq = dev->virtqueue[file.index];
1993
1994         /*
1995          * When VHOST_USER_F_PROTOCOL_FEATURES is not negotiated,
1996          * the ring starts already enabled. Otherwise, it is enabled via
1997          * the SET_VRING_ENABLE message.
1998          */
1999         if (!(dev->features & (1ULL << VHOST_USER_F_PROTOCOL_FEATURES))) {
2000                 vq->enabled = true;
2001         }
2002
2003         if (vq->ready) {
2004                 vq->ready = false;
2005                 vhost_user_notify_queue_state(dev, file.index, 0);
2006         }
2007
2008         if (vq->kickfd >= 0)
2009                 close(vq->kickfd);
2010         vq->kickfd = file.fd;
2011
2012         if (vq_is_packed(dev)) {
2013                 if (vhost_check_queue_inflights_packed(dev, vq)) {
2014                         VHOST_LOG_CONFIG(ERR,
2015                                 "failed to inflights for vq: %d\n", file.index);
2016                         return RTE_VHOST_MSG_RESULT_ERR;
2017                 }
2018         } else {
2019                 if (vhost_check_queue_inflights_split(dev, vq)) {
2020                         VHOST_LOG_CONFIG(ERR,
2021                                 "failed to inflights for vq: %d\n", file.index);
2022                         return RTE_VHOST_MSG_RESULT_ERR;
2023                 }
2024         }
2025
2026         return RTE_VHOST_MSG_RESULT_OK;
2027 }
2028
2029 /*
2030  * when virtio is stopped, qemu will send us the GET_VRING_BASE message.
2031  */
2032 static int
2033 vhost_user_get_vring_base(struct virtio_net **pdev,
2034                         struct VhostUserMsg *msg,
2035                         int main_fd __rte_unused)
2036 {
2037         struct virtio_net *dev = *pdev;
2038         struct vhost_virtqueue *vq = dev->virtqueue[msg->payload.state.index];
2039         uint64_t val;
2040
2041         if (validate_msg_fds(msg, 0) != 0)
2042                 return RTE_VHOST_MSG_RESULT_ERR;
2043
2044         /* We have to stop the queue (virtio) if it is running. */
2045         vhost_destroy_device_notify(dev);
2046
2047         dev->flags &= ~VIRTIO_DEV_READY;
2048         dev->flags &= ~VIRTIO_DEV_VDPA_CONFIGURED;
2049
2050         /* Here we are safe to get the indexes */
2051         if (vq_is_packed(dev)) {
2052                 /*
2053                  * Bit[0:14]: avail index
2054                  * Bit[15]: avail wrap counter
2055                  */
2056                 val = vq->last_avail_idx & 0x7fff;
2057                 val |= vq->avail_wrap_counter << 15;
2058                 msg->payload.state.num = val;
2059         } else {
2060                 msg->payload.state.num = vq->last_avail_idx;
2061         }
2062
2063         VHOST_LOG_CONFIG(INFO,
2064                 "vring base idx:%d file:%d\n", msg->payload.state.index,
2065                 msg->payload.state.num);
2066         /*
2067          * Based on current qemu vhost-user implementation, this message is
2068          * sent and only sent in vhost_vring_stop.
2069          * TODO: cleanup the vring, it isn't usable since here.
2070          */
2071         if (vq->kickfd >= 0)
2072                 close(vq->kickfd);
2073
2074         vq->kickfd = VIRTIO_UNINITIALIZED_EVENTFD;
2075
2076         if (vq->callfd >= 0)
2077                 close(vq->callfd);
2078
2079         vq->callfd = VIRTIO_UNINITIALIZED_EVENTFD;
2080
2081         vq->signalled_used_valid = false;
2082
2083         if (vq_is_packed(dev)) {
2084                 rte_free(vq->shadow_used_packed);
2085                 vq->shadow_used_packed = NULL;
2086         } else {
2087                 rte_free(vq->shadow_used_split);
2088                 vq->shadow_used_split = NULL;
2089         }
2090
2091         rte_free(vq->batch_copy_elems);
2092         vq->batch_copy_elems = NULL;
2093
2094         rte_free(vq->log_cache);
2095         vq->log_cache = NULL;
2096
2097         msg->size = sizeof(msg->payload.state);
2098         msg->fd_num = 0;
2099
2100         vring_invalidate(dev, vq);
2101
2102         return RTE_VHOST_MSG_RESULT_REPLY;
2103 }
2104
2105 /*
2106  * when virtio queues are ready to work, qemu will send us to
2107  * enable the virtio queue pair.
2108  */
2109 static int
2110 vhost_user_set_vring_enable(struct virtio_net **pdev,
2111                         struct VhostUserMsg *msg,
2112                         int main_fd __rte_unused)
2113 {
2114         struct virtio_net *dev = *pdev;
2115         bool enable = !!msg->payload.state.num;
2116         int index = (int)msg->payload.state.index;
2117
2118         if (validate_msg_fds(msg, 0) != 0)
2119                 return RTE_VHOST_MSG_RESULT_ERR;
2120
2121         VHOST_LOG_CONFIG(INFO,
2122                 "set queue enable: %d to qp idx: %d\n",
2123                 enable, index);
2124
2125         if (enable && dev->virtqueue[index]->async_registered) {
2126                 if (dev->virtqueue[index]->async_pkts_inflight_n) {
2127                         VHOST_LOG_CONFIG(ERR, "failed to enable vring. "
2128                         "async inflight packets must be completed first\n");
2129                         return RTE_VHOST_MSG_RESULT_ERR;
2130                 }
2131         }
2132
2133         dev->virtqueue[index]->enabled = enable;
2134
2135         return RTE_VHOST_MSG_RESULT_OK;
2136 }
2137
2138 static int
2139 vhost_user_get_protocol_features(struct virtio_net **pdev,
2140                         struct VhostUserMsg *msg,
2141                         int main_fd __rte_unused)
2142 {
2143         struct virtio_net *dev = *pdev;
2144         uint64_t features, protocol_features;
2145
2146         if (validate_msg_fds(msg, 0) != 0)
2147                 return RTE_VHOST_MSG_RESULT_ERR;
2148
2149         rte_vhost_driver_get_features(dev->ifname, &features);
2150         rte_vhost_driver_get_protocol_features(dev->ifname, &protocol_features);
2151
2152         msg->payload.u64 = protocol_features;
2153         msg->size = sizeof(msg->payload.u64);
2154         msg->fd_num = 0;
2155
2156         return RTE_VHOST_MSG_RESULT_REPLY;
2157 }
2158
2159 static int
2160 vhost_user_set_protocol_features(struct virtio_net **pdev,
2161                         struct VhostUserMsg *msg,
2162                         int main_fd __rte_unused)
2163 {
2164         struct virtio_net *dev = *pdev;
2165         uint64_t protocol_features = msg->payload.u64;
2166         uint64_t slave_protocol_features = 0;
2167
2168         if (validate_msg_fds(msg, 0) != 0)
2169                 return RTE_VHOST_MSG_RESULT_ERR;
2170
2171         rte_vhost_driver_get_protocol_features(dev->ifname,
2172                         &slave_protocol_features);
2173         if (protocol_features & ~slave_protocol_features) {
2174                 VHOST_LOG_CONFIG(ERR,
2175                         "(%d) received invalid protocol features.\n",
2176                         dev->vid);
2177                 return RTE_VHOST_MSG_RESULT_ERR;
2178         }
2179
2180         dev->protocol_features = protocol_features;
2181         VHOST_LOG_CONFIG(INFO,
2182                 "negotiated Vhost-user protocol features: 0x%" PRIx64 "\n",
2183                 dev->protocol_features);
2184
2185         return RTE_VHOST_MSG_RESULT_OK;
2186 }
2187
2188 static int
2189 vhost_user_set_log_base(struct virtio_net **pdev, struct VhostUserMsg *msg,
2190                         int main_fd __rte_unused)
2191 {
2192         struct virtio_net *dev = *pdev;
2193         int fd = msg->fds[0];
2194         uint64_t size, off;
2195         void *addr;
2196         uint32_t i;
2197
2198         if (validate_msg_fds(msg, 1) != 0)
2199                 return RTE_VHOST_MSG_RESULT_ERR;
2200
2201         if (fd < 0) {
2202                 VHOST_LOG_CONFIG(ERR, "invalid log fd: %d\n", fd);
2203                 return RTE_VHOST_MSG_RESULT_ERR;
2204         }
2205
2206         if (msg->size != sizeof(VhostUserLog)) {
2207                 VHOST_LOG_CONFIG(ERR,
2208                         "invalid log base msg size: %"PRId32" != %d\n",
2209                         msg->size, (int)sizeof(VhostUserLog));
2210                 goto close_msg_fds;
2211         }
2212
2213         size = msg->payload.log.mmap_size;
2214         off  = msg->payload.log.mmap_offset;
2215
2216         /* Check for mmap size and offset overflow. */
2217         if (off >= -size) {
2218                 VHOST_LOG_CONFIG(ERR,
2219                         "log offset %#"PRIx64" and log size %#"PRIx64" overflow\n",
2220                         off, size);
2221                 goto close_msg_fds;
2222         }
2223
2224         VHOST_LOG_CONFIG(INFO,
2225                 "log mmap size: %"PRId64", offset: %"PRId64"\n",
2226                 size, off);
2227
2228         /*
2229          * mmap from 0 to workaround a hugepage mmap bug: mmap will
2230          * fail when offset is not page size aligned.
2231          */
2232         addr = mmap(0, size + off, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
2233         close(fd);
2234         if (addr == MAP_FAILED) {
2235                 VHOST_LOG_CONFIG(ERR, "mmap log base failed!\n");
2236                 return RTE_VHOST_MSG_RESULT_ERR;
2237         }
2238
2239         /*
2240          * Free previously mapped log memory on occasionally
2241          * multiple VHOST_USER_SET_LOG_BASE.
2242          */
2243         if (dev->log_addr) {
2244                 munmap((void *)(uintptr_t)dev->log_addr, dev->log_size);
2245         }
2246         dev->log_addr = (uint64_t)(uintptr_t)addr;
2247         dev->log_base = dev->log_addr + off;
2248         dev->log_size = size;
2249
2250         for (i = 0; i < dev->nr_vring; i++) {
2251                 struct vhost_virtqueue *vq = dev->virtqueue[i];
2252
2253                 rte_free(vq->log_cache);
2254                 vq->log_cache = NULL;
2255                 vq->log_cache_nb_elem = 0;
2256                 vq->log_cache = rte_malloc_socket("vq log cache",
2257                                 sizeof(struct log_cache_entry) * VHOST_LOG_CACHE_NR,
2258                                 0, vq->numa_node);
2259                 /*
2260                  * If log cache alloc fail, don't fail migration, but no
2261                  * caching will be done, which will impact performance
2262                  */
2263                 if (!vq->log_cache)
2264                         VHOST_LOG_CONFIG(ERR, "Failed to allocate VQ logging cache\n");
2265         }
2266
2267         /*
2268          * The spec is not clear about it (yet), but QEMU doesn't expect
2269          * any payload in the reply.
2270          */
2271         msg->size = 0;
2272         msg->fd_num = 0;
2273
2274         return RTE_VHOST_MSG_RESULT_REPLY;
2275
2276 close_msg_fds:
2277         close_msg_fds(msg);
2278         return RTE_VHOST_MSG_RESULT_ERR;
2279 }
2280
2281 static int vhost_user_set_log_fd(struct virtio_net **pdev __rte_unused,
2282                         struct VhostUserMsg *msg,
2283                         int main_fd __rte_unused)
2284 {
2285         if (validate_msg_fds(msg, 1) != 0)
2286                 return RTE_VHOST_MSG_RESULT_ERR;
2287
2288         close(msg->fds[0]);
2289         VHOST_LOG_CONFIG(INFO, "not implemented.\n");
2290
2291         return RTE_VHOST_MSG_RESULT_OK;
2292 }
2293
2294 /*
2295  * An rarp packet is constructed and broadcasted to notify switches about
2296  * the new location of the migrated VM, so that packets from outside will
2297  * not be lost after migration.
2298  *
2299  * However, we don't actually "send" a rarp packet here, instead, we set
2300  * a flag 'broadcast_rarp' to let rte_vhost_dequeue_burst() inject it.
2301  */
2302 static int
2303 vhost_user_send_rarp(struct virtio_net **pdev, struct VhostUserMsg *msg,
2304                         int main_fd __rte_unused)
2305 {
2306         struct virtio_net *dev = *pdev;
2307         uint8_t *mac = (uint8_t *)&msg->payload.u64;
2308         struct rte_vdpa_device *vdpa_dev;
2309
2310         if (validate_msg_fds(msg, 0) != 0)
2311                 return RTE_VHOST_MSG_RESULT_ERR;
2312
2313         VHOST_LOG_CONFIG(DEBUG,
2314                 ":: mac: %02x:%02x:%02x:%02x:%02x:%02x\n",
2315                 mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
2316         memcpy(dev->mac.addr_bytes, mac, 6);
2317
2318         /*
2319          * Set the flag to inject a RARP broadcast packet at
2320          * rte_vhost_dequeue_burst().
2321          *
2322          * __ATOMIC_RELEASE ordering is for making sure the mac is
2323          * copied before the flag is set.
2324          */
2325         __atomic_store_n(&dev->broadcast_rarp, 1, __ATOMIC_RELEASE);
2326         vdpa_dev = dev->vdpa_dev;
2327         if (vdpa_dev && vdpa_dev->ops->migration_done)
2328                 vdpa_dev->ops->migration_done(dev->vid);
2329
2330         return RTE_VHOST_MSG_RESULT_OK;
2331 }
2332
2333 static int
2334 vhost_user_net_set_mtu(struct virtio_net **pdev, struct VhostUserMsg *msg,
2335                         int main_fd __rte_unused)
2336 {
2337         struct virtio_net *dev = *pdev;
2338
2339         if (validate_msg_fds(msg, 0) != 0)
2340                 return RTE_VHOST_MSG_RESULT_ERR;
2341
2342         if (msg->payload.u64 < VIRTIO_MIN_MTU ||
2343                         msg->payload.u64 > VIRTIO_MAX_MTU) {
2344                 VHOST_LOG_CONFIG(ERR, "Invalid MTU size (%"PRIu64")\n",
2345                                 msg->payload.u64);
2346
2347                 return RTE_VHOST_MSG_RESULT_ERR;
2348         }
2349
2350         dev->mtu = msg->payload.u64;
2351
2352         return RTE_VHOST_MSG_RESULT_OK;
2353 }
2354
2355 static int
2356 vhost_user_set_req_fd(struct virtio_net **pdev, struct VhostUserMsg *msg,
2357                         int main_fd __rte_unused)
2358 {
2359         struct virtio_net *dev = *pdev;
2360         int fd = msg->fds[0];
2361
2362         if (validate_msg_fds(msg, 1) != 0)
2363                 return RTE_VHOST_MSG_RESULT_ERR;
2364
2365         if (fd < 0) {
2366                 VHOST_LOG_CONFIG(ERR,
2367                                 "Invalid file descriptor for slave channel (%d)\n",
2368                                 fd);
2369                 return RTE_VHOST_MSG_RESULT_ERR;
2370         }
2371
2372         if (dev->slave_req_fd >= 0)
2373                 close(dev->slave_req_fd);
2374
2375         dev->slave_req_fd = fd;
2376
2377         return RTE_VHOST_MSG_RESULT_OK;
2378 }
2379
2380 static int
2381 is_vring_iotlb_split(struct vhost_virtqueue *vq, struct vhost_iotlb_msg *imsg)
2382 {
2383         struct vhost_vring_addr *ra;
2384         uint64_t start, end, len;
2385
2386         start = imsg->iova;
2387         end = start + imsg->size;
2388
2389         ra = &vq->ring_addrs;
2390         len = sizeof(struct vring_desc) * vq->size;
2391         if (ra->desc_user_addr < end && (ra->desc_user_addr + len) > start)
2392                 return 1;
2393
2394         len = sizeof(struct vring_avail) + sizeof(uint16_t) * vq->size;
2395         if (ra->avail_user_addr < end && (ra->avail_user_addr + len) > start)
2396                 return 1;
2397
2398         len = sizeof(struct vring_used) +
2399                sizeof(struct vring_used_elem) * vq->size;
2400         if (ra->used_user_addr < end && (ra->used_user_addr + len) > start)
2401                 return 1;
2402
2403         if (ra->flags & (1 << VHOST_VRING_F_LOG)) {
2404                 len = sizeof(uint64_t);
2405                 if (ra->log_guest_addr < end &&
2406                     (ra->log_guest_addr + len) > start)
2407                         return 1;
2408         }
2409
2410         return 0;
2411 }
2412
2413 static int
2414 is_vring_iotlb_packed(struct vhost_virtqueue *vq, struct vhost_iotlb_msg *imsg)
2415 {
2416         struct vhost_vring_addr *ra;
2417         uint64_t start, end, len;
2418
2419         start = imsg->iova;
2420         end = start + imsg->size;
2421
2422         ra = &vq->ring_addrs;
2423         len = sizeof(struct vring_packed_desc) * vq->size;
2424         if (ra->desc_user_addr < end && (ra->desc_user_addr + len) > start)
2425                 return 1;
2426
2427         len = sizeof(struct vring_packed_desc_event);
2428         if (ra->avail_user_addr < end && (ra->avail_user_addr + len) > start)
2429                 return 1;
2430
2431         len = sizeof(struct vring_packed_desc_event);
2432         if (ra->used_user_addr < end && (ra->used_user_addr + len) > start)
2433                 return 1;
2434
2435         if (ra->flags & (1 << VHOST_VRING_F_LOG)) {
2436                 len = sizeof(uint64_t);
2437                 if (ra->log_guest_addr < end &&
2438                     (ra->log_guest_addr + len) > start)
2439                         return 1;
2440         }
2441
2442         return 0;
2443 }
2444
2445 static int is_vring_iotlb(struct virtio_net *dev,
2446                           struct vhost_virtqueue *vq,
2447                           struct vhost_iotlb_msg *imsg)
2448 {
2449         if (vq_is_packed(dev))
2450                 return is_vring_iotlb_packed(vq, imsg);
2451         else
2452                 return is_vring_iotlb_split(vq, imsg);
2453 }
2454
2455 static int
2456 vhost_user_iotlb_msg(struct virtio_net **pdev, struct VhostUserMsg *msg,
2457                         int main_fd __rte_unused)
2458 {
2459         struct virtio_net *dev = *pdev;
2460         struct vhost_iotlb_msg *imsg = &msg->payload.iotlb;
2461         uint16_t i;
2462         uint64_t vva, len;
2463
2464         if (validate_msg_fds(msg, 0) != 0)
2465                 return RTE_VHOST_MSG_RESULT_ERR;
2466
2467         switch (imsg->type) {
2468         case VHOST_IOTLB_UPDATE:
2469                 len = imsg->size;
2470                 vva = qva_to_vva(dev, imsg->uaddr, &len);
2471                 if (!vva)
2472                         return RTE_VHOST_MSG_RESULT_ERR;
2473
2474                 for (i = 0; i < dev->nr_vring; i++) {
2475                         struct vhost_virtqueue *vq = dev->virtqueue[i];
2476
2477                         if (!vq)
2478                                 continue;
2479
2480                         vhost_user_iotlb_cache_insert(vq, imsg->iova, vva,
2481                                         len, imsg->perm);
2482
2483                         if (is_vring_iotlb(dev, vq, imsg))
2484                                 *pdev = dev = translate_ring_addresses(dev, i);
2485                 }
2486                 break;
2487         case VHOST_IOTLB_INVALIDATE:
2488                 for (i = 0; i < dev->nr_vring; i++) {
2489                         struct vhost_virtqueue *vq = dev->virtqueue[i];
2490
2491                         if (!vq)
2492                                 continue;
2493
2494                         vhost_user_iotlb_cache_remove(vq, imsg->iova,
2495                                         imsg->size);
2496
2497                         if (is_vring_iotlb(dev, vq, imsg))
2498                                 vring_invalidate(dev, vq);
2499                 }
2500                 break;
2501         default:
2502                 VHOST_LOG_CONFIG(ERR, "Invalid IOTLB message type (%d)\n",
2503                                 imsg->type);
2504                 return RTE_VHOST_MSG_RESULT_ERR;
2505         }
2506
2507         return RTE_VHOST_MSG_RESULT_OK;
2508 }
2509
2510 static int
2511 vhost_user_set_postcopy_advise(struct virtio_net **pdev,
2512                         struct VhostUserMsg *msg,
2513                         int main_fd __rte_unused)
2514 {
2515         struct virtio_net *dev = *pdev;
2516 #ifdef RTE_LIBRTE_VHOST_POSTCOPY
2517         struct uffdio_api api_struct;
2518
2519         if (validate_msg_fds(msg, 0) != 0)
2520                 return RTE_VHOST_MSG_RESULT_ERR;
2521
2522         dev->postcopy_ufd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
2523
2524         if (dev->postcopy_ufd == -1) {
2525                 VHOST_LOG_CONFIG(ERR, "Userfaultfd not available: %s\n",
2526                         strerror(errno));
2527                 return RTE_VHOST_MSG_RESULT_ERR;
2528         }
2529         api_struct.api = UFFD_API;
2530         api_struct.features = 0;
2531         if (ioctl(dev->postcopy_ufd, UFFDIO_API, &api_struct)) {
2532                 VHOST_LOG_CONFIG(ERR, "UFFDIO_API ioctl failure: %s\n",
2533                         strerror(errno));
2534                 close(dev->postcopy_ufd);
2535                 dev->postcopy_ufd = -1;
2536                 return RTE_VHOST_MSG_RESULT_ERR;
2537         }
2538         msg->fds[0] = dev->postcopy_ufd;
2539         msg->fd_num = 1;
2540
2541         return RTE_VHOST_MSG_RESULT_REPLY;
2542 #else
2543         dev->postcopy_ufd = -1;
2544         msg->fd_num = 0;
2545
2546         return RTE_VHOST_MSG_RESULT_ERR;
2547 #endif
2548 }
2549
2550 static int
2551 vhost_user_set_postcopy_listen(struct virtio_net **pdev,
2552                         struct VhostUserMsg *msg __rte_unused,
2553                         int main_fd __rte_unused)
2554 {
2555         struct virtio_net *dev = *pdev;
2556
2557         if (validate_msg_fds(msg, 0) != 0)
2558                 return RTE_VHOST_MSG_RESULT_ERR;
2559
2560         if (dev->mem && dev->mem->nregions) {
2561                 VHOST_LOG_CONFIG(ERR,
2562                         "Regions already registered at postcopy-listen\n");
2563                 return RTE_VHOST_MSG_RESULT_ERR;
2564         }
2565         dev->postcopy_listening = 1;
2566
2567         return RTE_VHOST_MSG_RESULT_OK;
2568 }
2569
2570 static int
2571 vhost_user_postcopy_end(struct virtio_net **pdev, struct VhostUserMsg *msg,
2572                         int main_fd __rte_unused)
2573 {
2574         struct virtio_net *dev = *pdev;
2575
2576         if (validate_msg_fds(msg, 0) != 0)
2577                 return RTE_VHOST_MSG_RESULT_ERR;
2578
2579         dev->postcopy_listening = 0;
2580         if (dev->postcopy_ufd >= 0) {
2581                 close(dev->postcopy_ufd);
2582                 dev->postcopy_ufd = -1;
2583         }
2584
2585         msg->payload.u64 = 0;
2586         msg->size = sizeof(msg->payload.u64);
2587         msg->fd_num = 0;
2588
2589         return RTE_VHOST_MSG_RESULT_REPLY;
2590 }
2591
2592 static int
2593 vhost_user_get_status(struct virtio_net **pdev, struct VhostUserMsg *msg,
2594                       int main_fd __rte_unused)
2595 {
2596         struct virtio_net *dev = *pdev;
2597
2598         if (validate_msg_fds(msg, 0) != 0)
2599                 return RTE_VHOST_MSG_RESULT_ERR;
2600
2601         msg->payload.u64 = dev->status;
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_set_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         /* As per Virtio specification, the device status is 8bits long */
2618         if (msg->payload.u64 > UINT8_MAX) {
2619                 VHOST_LOG_CONFIG(ERR, "Invalid VHOST_USER_SET_STATUS payload 0x%" PRIx64 "\n",
2620                                 msg->payload.u64);
2621                 return RTE_VHOST_MSG_RESULT_ERR;
2622         }
2623
2624         dev->status = msg->payload.u64;
2625
2626         if ((dev->status & VIRTIO_DEVICE_STATUS_FEATURES_OK) &&
2627             (dev->flags & VIRTIO_DEV_FEATURES_FAILED)) {
2628                 VHOST_LOG_CONFIG(ERR, "FEATURES_OK bit is set but feature negotiation failed\n");
2629                 /*
2630                  * Clear the bit to let the driver know about the feature
2631                  * negotiation failure
2632                  */
2633                 dev->status &= ~VIRTIO_DEVICE_STATUS_FEATURES_OK;
2634         }
2635
2636         VHOST_LOG_CONFIG(INFO, "New device status(0x%08x):\n"
2637                         "\t-RESET: %u\n"
2638                         "\t-ACKNOWLEDGE: %u\n"
2639                         "\t-DRIVER: %u\n"
2640                         "\t-FEATURES_OK: %u\n"
2641                         "\t-DRIVER_OK: %u\n"
2642                         "\t-DEVICE_NEED_RESET: %u\n"
2643                         "\t-FAILED: %u\n",
2644                         dev->status,
2645                         (dev->status == VIRTIO_DEVICE_STATUS_RESET),
2646                         !!(dev->status & VIRTIO_DEVICE_STATUS_ACK),
2647                         !!(dev->status & VIRTIO_DEVICE_STATUS_DRIVER),
2648                         !!(dev->status & VIRTIO_DEVICE_STATUS_FEATURES_OK),
2649                         !!(dev->status & VIRTIO_DEVICE_STATUS_DRIVER_OK),
2650                         !!(dev->status & VIRTIO_DEVICE_STATUS_DEV_NEED_RESET),
2651                         !!(dev->status & VIRTIO_DEVICE_STATUS_FAILED));
2652
2653         return RTE_VHOST_MSG_RESULT_OK;
2654 }
2655
2656 typedef int (*vhost_message_handler_t)(struct virtio_net **pdev,
2657                                         struct VhostUserMsg *msg,
2658                                         int main_fd);
2659 static vhost_message_handler_t vhost_message_handlers[VHOST_USER_MAX] = {
2660         [VHOST_USER_NONE] = NULL,
2661         [VHOST_USER_GET_FEATURES] = vhost_user_get_features,
2662         [VHOST_USER_SET_FEATURES] = vhost_user_set_features,
2663         [VHOST_USER_SET_OWNER] = vhost_user_set_owner,
2664         [VHOST_USER_RESET_OWNER] = vhost_user_reset_owner,
2665         [VHOST_USER_SET_MEM_TABLE] = vhost_user_set_mem_table,
2666         [VHOST_USER_SET_LOG_BASE] = vhost_user_set_log_base,
2667         [VHOST_USER_SET_LOG_FD] = vhost_user_set_log_fd,
2668         [VHOST_USER_SET_VRING_NUM] = vhost_user_set_vring_num,
2669         [VHOST_USER_SET_VRING_ADDR] = vhost_user_set_vring_addr,
2670         [VHOST_USER_SET_VRING_BASE] = vhost_user_set_vring_base,
2671         [VHOST_USER_GET_VRING_BASE] = vhost_user_get_vring_base,
2672         [VHOST_USER_SET_VRING_KICK] = vhost_user_set_vring_kick,
2673         [VHOST_USER_SET_VRING_CALL] = vhost_user_set_vring_call,
2674         [VHOST_USER_SET_VRING_ERR] = vhost_user_set_vring_err,
2675         [VHOST_USER_GET_PROTOCOL_FEATURES] = vhost_user_get_protocol_features,
2676         [VHOST_USER_SET_PROTOCOL_FEATURES] = vhost_user_set_protocol_features,
2677         [VHOST_USER_GET_QUEUE_NUM] = vhost_user_get_queue_num,
2678         [VHOST_USER_SET_VRING_ENABLE] = vhost_user_set_vring_enable,
2679         [VHOST_USER_SEND_RARP] = vhost_user_send_rarp,
2680         [VHOST_USER_NET_SET_MTU] = vhost_user_net_set_mtu,
2681         [VHOST_USER_SET_SLAVE_REQ_FD] = vhost_user_set_req_fd,
2682         [VHOST_USER_IOTLB_MSG] = vhost_user_iotlb_msg,
2683         [VHOST_USER_POSTCOPY_ADVISE] = vhost_user_set_postcopy_advise,
2684         [VHOST_USER_POSTCOPY_LISTEN] = vhost_user_set_postcopy_listen,
2685         [VHOST_USER_POSTCOPY_END] = vhost_user_postcopy_end,
2686         [VHOST_USER_GET_INFLIGHT_FD] = vhost_user_get_inflight_fd,
2687         [VHOST_USER_SET_INFLIGHT_FD] = vhost_user_set_inflight_fd,
2688         [VHOST_USER_SET_STATUS] = vhost_user_set_status,
2689         [VHOST_USER_GET_STATUS] = vhost_user_get_status,
2690 };
2691
2692 /* return bytes# of read on success or negative val on failure. */
2693 static int
2694 read_vhost_message(int sockfd, struct VhostUserMsg *msg)
2695 {
2696         int ret;
2697
2698         ret = read_fd_message(sockfd, (char *)msg, VHOST_USER_HDR_SIZE,
2699                 msg->fds, VHOST_MEMORY_MAX_NREGIONS, &msg->fd_num);
2700         if (ret <= 0) {
2701                 return ret;
2702         } else if (ret != VHOST_USER_HDR_SIZE) {
2703                 VHOST_LOG_CONFIG(ERR, "Unexpected header size read\n");
2704                 close_msg_fds(msg);
2705                 return -1;
2706         }
2707
2708         if (msg->size) {
2709                 if (msg->size > sizeof(msg->payload)) {
2710                         VHOST_LOG_CONFIG(ERR,
2711                                 "invalid msg size: %d\n", msg->size);
2712                         return -1;
2713                 }
2714                 ret = read(sockfd, &msg->payload, msg->size);
2715                 if (ret <= 0)
2716                         return ret;
2717                 if (ret != (int)msg->size) {
2718                         VHOST_LOG_CONFIG(ERR,
2719                                 "read control message failed\n");
2720                         return -1;
2721                 }
2722         }
2723
2724         return ret;
2725 }
2726
2727 static int
2728 send_vhost_message(int sockfd, struct VhostUserMsg *msg)
2729 {
2730         if (!msg)
2731                 return 0;
2732
2733         return send_fd_message(sockfd, (char *)msg,
2734                 VHOST_USER_HDR_SIZE + msg->size, msg->fds, msg->fd_num);
2735 }
2736
2737 static int
2738 send_vhost_reply(int sockfd, struct VhostUserMsg *msg)
2739 {
2740         if (!msg)
2741                 return 0;
2742
2743         msg->flags &= ~VHOST_USER_VERSION_MASK;
2744         msg->flags &= ~VHOST_USER_NEED_REPLY;
2745         msg->flags |= VHOST_USER_VERSION;
2746         msg->flags |= VHOST_USER_REPLY_MASK;
2747
2748         return send_vhost_message(sockfd, msg);
2749 }
2750
2751 static int
2752 send_vhost_slave_message(struct virtio_net *dev, struct VhostUserMsg *msg)
2753 {
2754         int ret;
2755
2756         if (msg->flags & VHOST_USER_NEED_REPLY)
2757                 rte_spinlock_lock(&dev->slave_req_lock);
2758
2759         ret = send_vhost_message(dev->slave_req_fd, msg);
2760         if (ret < 0 && (msg->flags & VHOST_USER_NEED_REPLY))
2761                 rte_spinlock_unlock(&dev->slave_req_lock);
2762
2763         return ret;
2764 }
2765
2766 /*
2767  * Allocate a queue pair if it hasn't been allocated yet
2768  */
2769 static int
2770 vhost_user_check_and_alloc_queue_pair(struct virtio_net *dev,
2771                         struct VhostUserMsg *msg)
2772 {
2773         uint32_t vring_idx;
2774
2775         switch (msg->request.master) {
2776         case VHOST_USER_SET_VRING_KICK:
2777         case VHOST_USER_SET_VRING_CALL:
2778         case VHOST_USER_SET_VRING_ERR:
2779                 vring_idx = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
2780                 break;
2781         case VHOST_USER_SET_VRING_NUM:
2782         case VHOST_USER_SET_VRING_BASE:
2783         case VHOST_USER_SET_VRING_ENABLE:
2784                 vring_idx = msg->payload.state.index;
2785                 break;
2786         case VHOST_USER_SET_VRING_ADDR:
2787                 vring_idx = msg->payload.addr.index;
2788                 break;
2789         default:
2790                 return 0;
2791         }
2792
2793         if (vring_idx >= VHOST_MAX_VRING) {
2794                 VHOST_LOG_CONFIG(ERR,
2795                         "invalid vring index: %u\n", vring_idx);
2796                 return -1;
2797         }
2798
2799         if (dev->virtqueue[vring_idx])
2800                 return 0;
2801
2802         return alloc_vring_queue(dev, vring_idx);
2803 }
2804
2805 static void
2806 vhost_user_lock_all_queue_pairs(struct virtio_net *dev)
2807 {
2808         unsigned int i = 0;
2809         unsigned int vq_num = 0;
2810
2811         while (vq_num < dev->nr_vring) {
2812                 struct vhost_virtqueue *vq = dev->virtqueue[i];
2813
2814                 if (vq) {
2815                         rte_spinlock_lock(&vq->access_lock);
2816                         vq_num++;
2817                 }
2818                 i++;
2819         }
2820 }
2821
2822 static void
2823 vhost_user_unlock_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_unlock(&vq->access_lock);
2833                         vq_num++;
2834                 }
2835                 i++;
2836         }
2837 }
2838
2839 int
2840 vhost_user_msg_handler(int vid, int fd)
2841 {
2842         struct virtio_net *dev;
2843         struct VhostUserMsg msg;
2844         struct rte_vdpa_device *vdpa_dev;
2845         int ret;
2846         int unlock_required = 0;
2847         bool handled;
2848         int request;
2849         uint32_t i;
2850
2851         dev = get_device(vid);
2852         if (dev == NULL)
2853                 return -1;
2854
2855         if (!dev->notify_ops) {
2856                 dev->notify_ops = vhost_driver_callback_get(dev->ifname);
2857                 if (!dev->notify_ops) {
2858                         VHOST_LOG_CONFIG(ERR,
2859                                 "failed to get callback ops for driver %s\n",
2860                                 dev->ifname);
2861                         return -1;
2862                 }
2863         }
2864
2865         ret = read_vhost_message(fd, &msg);
2866         if (ret <= 0) {
2867                 if (ret < 0)
2868                         VHOST_LOG_CONFIG(ERR,
2869                                 "vhost read message failed\n");
2870                 else
2871                         VHOST_LOG_CONFIG(INFO,
2872                                 "vhost peer closed\n");
2873
2874                 return -1;
2875         }
2876
2877         ret = 0;
2878         request = msg.request.master;
2879         if (request > VHOST_USER_NONE && request < VHOST_USER_MAX &&
2880                         vhost_message_str[request]) {
2881                 if (request != VHOST_USER_IOTLB_MSG)
2882                         VHOST_LOG_CONFIG(INFO, "read message %s\n",
2883                                 vhost_message_str[request]);
2884                 else
2885                         VHOST_LOG_CONFIG(DEBUG, "read message %s\n",
2886                                 vhost_message_str[request]);
2887         } else {
2888                 VHOST_LOG_CONFIG(DEBUG, "External request %d\n", request);
2889         }
2890
2891         ret = vhost_user_check_and_alloc_queue_pair(dev, &msg);
2892         if (ret < 0) {
2893                 VHOST_LOG_CONFIG(ERR,
2894                         "failed to alloc queue\n");
2895                 return -1;
2896         }
2897
2898         /*
2899          * Note: we don't lock all queues on VHOST_USER_GET_VRING_BASE
2900          * and VHOST_USER_RESET_OWNER, since it is sent when virtio stops
2901          * and device is destroyed. destroy_device waits for queues to be
2902          * inactive, so it is safe. Otherwise taking the access_lock
2903          * would cause a dead lock.
2904          */
2905         switch (request) {
2906         case VHOST_USER_SET_FEATURES:
2907         case VHOST_USER_SET_PROTOCOL_FEATURES:
2908         case VHOST_USER_SET_OWNER:
2909         case VHOST_USER_SET_MEM_TABLE:
2910         case VHOST_USER_SET_LOG_BASE:
2911         case VHOST_USER_SET_LOG_FD:
2912         case VHOST_USER_SET_VRING_NUM:
2913         case VHOST_USER_SET_VRING_ADDR:
2914         case VHOST_USER_SET_VRING_BASE:
2915         case VHOST_USER_SET_VRING_KICK:
2916         case VHOST_USER_SET_VRING_CALL:
2917         case VHOST_USER_SET_VRING_ERR:
2918         case VHOST_USER_SET_VRING_ENABLE:
2919         case VHOST_USER_SEND_RARP:
2920         case VHOST_USER_NET_SET_MTU:
2921         case VHOST_USER_SET_SLAVE_REQ_FD:
2922                 if (!(dev->flags & VIRTIO_DEV_VDPA_CONFIGURED)) {
2923                         vhost_user_lock_all_queue_pairs(dev);
2924                         unlock_required = 1;
2925                 }
2926                 break;
2927         default:
2928                 break;
2929
2930         }
2931
2932         handled = false;
2933         if (dev->extern_ops.pre_msg_handle) {
2934                 ret = (*dev->extern_ops.pre_msg_handle)(dev->vid,
2935                                 (void *)&msg);
2936                 switch (ret) {
2937                 case RTE_VHOST_MSG_RESULT_REPLY:
2938                         send_vhost_reply(fd, &msg);
2939                         /* Fall-through */
2940                 case RTE_VHOST_MSG_RESULT_ERR:
2941                 case RTE_VHOST_MSG_RESULT_OK:
2942                         handled = true;
2943                         goto skip_to_post_handle;
2944                 case RTE_VHOST_MSG_RESULT_NOT_HANDLED:
2945                 default:
2946                         break;
2947                 }
2948         }
2949
2950         if (request > VHOST_USER_NONE && request < VHOST_USER_MAX) {
2951                 if (!vhost_message_handlers[request])
2952                         goto skip_to_post_handle;
2953                 ret = vhost_message_handlers[request](&dev, &msg, fd);
2954
2955                 switch (ret) {
2956                 case RTE_VHOST_MSG_RESULT_ERR:
2957                         VHOST_LOG_CONFIG(ERR,
2958                                 "Processing %s failed.\n",
2959                                 vhost_message_str[request]);
2960                         handled = true;
2961                         break;
2962                 case RTE_VHOST_MSG_RESULT_OK:
2963                         VHOST_LOG_CONFIG(DEBUG,
2964                                 "Processing %s succeeded.\n",
2965                                 vhost_message_str[request]);
2966                         handled = true;
2967                         break;
2968                 case RTE_VHOST_MSG_RESULT_REPLY:
2969                         VHOST_LOG_CONFIG(DEBUG,
2970                                 "Processing %s succeeded and needs reply.\n",
2971                                 vhost_message_str[request]);
2972                         send_vhost_reply(fd, &msg);
2973                         handled = true;
2974                         break;
2975                 default:
2976                         break;
2977                 }
2978         }
2979
2980 skip_to_post_handle:
2981         if (ret != RTE_VHOST_MSG_RESULT_ERR &&
2982                         dev->extern_ops.post_msg_handle) {
2983                 ret = (*dev->extern_ops.post_msg_handle)(dev->vid,
2984                                 (void *)&msg);
2985                 switch (ret) {
2986                 case RTE_VHOST_MSG_RESULT_REPLY:
2987                         send_vhost_reply(fd, &msg);
2988                         /* Fall-through */
2989                 case RTE_VHOST_MSG_RESULT_ERR:
2990                 case RTE_VHOST_MSG_RESULT_OK:
2991                         handled = true;
2992                 case RTE_VHOST_MSG_RESULT_NOT_HANDLED:
2993                 default:
2994                         break;
2995                 }
2996         }
2997
2998         if (unlock_required)
2999                 vhost_user_unlock_all_queue_pairs(dev);
3000
3001         /* If message was not handled at this stage, treat it as an error */
3002         if (!handled) {
3003                 VHOST_LOG_CONFIG(ERR,
3004                         "vhost message (req: %d) was not handled.\n", request);
3005                 close_msg_fds(&msg);
3006                 ret = RTE_VHOST_MSG_RESULT_ERR;
3007         }
3008
3009         /*
3010          * If the request required a reply that was already sent,
3011          * this optional reply-ack won't be sent as the
3012          * VHOST_USER_NEED_REPLY was cleared in send_vhost_reply().
3013          */
3014         if (msg.flags & VHOST_USER_NEED_REPLY) {
3015                 msg.payload.u64 = ret == RTE_VHOST_MSG_RESULT_ERR;
3016                 msg.size = sizeof(msg.payload.u64);
3017                 msg.fd_num = 0;
3018                 send_vhost_reply(fd, &msg);
3019         } else if (ret == RTE_VHOST_MSG_RESULT_ERR) {
3020                 VHOST_LOG_CONFIG(ERR,
3021                         "vhost message handling failed.\n");
3022                 return -1;
3023         }
3024
3025         for (i = 0; i < dev->nr_vring; i++) {
3026                 struct vhost_virtqueue *vq = dev->virtqueue[i];
3027                 bool cur_ready = vq_is_ready(dev, vq);
3028
3029                 if (cur_ready != (vq && vq->ready)) {
3030                         vq->ready = cur_ready;
3031                         vhost_user_notify_queue_state(dev, i, cur_ready);
3032                 }
3033         }
3034
3035
3036         if (!virtio_is_ready(dev))
3037                 goto out;
3038
3039         /*
3040          * Virtio is now ready. If not done already, it is time
3041          * to notify the application it can process the rings and
3042          * configure the vDPA device if present.
3043          */
3044
3045         if (!(dev->flags & VIRTIO_DEV_RUNNING)) {
3046                 if (dev->notify_ops->new_device(dev->vid) == 0)
3047                         dev->flags |= VIRTIO_DEV_RUNNING;
3048         }
3049
3050         vdpa_dev = dev->vdpa_dev;
3051         if (!vdpa_dev)
3052                 goto out;
3053
3054         if (!(dev->flags & VIRTIO_DEV_VDPA_CONFIGURED)) {
3055                 if (vdpa_dev->ops->dev_conf(dev->vid))
3056                         VHOST_LOG_CONFIG(ERR,
3057                                          "Failed to configure vDPA device\n");
3058                 else
3059                         dev->flags |= VIRTIO_DEV_VDPA_CONFIGURED;
3060         }
3061
3062 out:
3063         return 0;
3064 }
3065
3066 static int process_slave_message_reply(struct virtio_net *dev,
3067                                        const struct VhostUserMsg *msg)
3068 {
3069         struct VhostUserMsg msg_reply;
3070         int ret;
3071
3072         if ((msg->flags & VHOST_USER_NEED_REPLY) == 0)
3073                 return 0;
3074
3075         ret = read_vhost_message(dev->slave_req_fd, &msg_reply);
3076         if (ret <= 0) {
3077                 if (ret < 0)
3078                         VHOST_LOG_CONFIG(ERR,
3079                                 "vhost read slave message reply failed\n");
3080                 else
3081                         VHOST_LOG_CONFIG(INFO,
3082                                 "vhost peer closed\n");
3083                 ret = -1;
3084                 goto out;
3085         }
3086
3087         ret = 0;
3088         if (msg_reply.request.slave != msg->request.slave) {
3089                 VHOST_LOG_CONFIG(ERR,
3090                         "Received unexpected msg type (%u), expected %u\n",
3091                         msg_reply.request.slave, msg->request.slave);
3092                 ret = -1;
3093                 goto out;
3094         }
3095
3096         ret = msg_reply.payload.u64 ? -1 : 0;
3097
3098 out:
3099         rte_spinlock_unlock(&dev->slave_req_lock);
3100         return ret;
3101 }
3102
3103 int
3104 vhost_user_iotlb_miss(struct virtio_net *dev, uint64_t iova, uint8_t perm)
3105 {
3106         int ret;
3107         struct VhostUserMsg msg = {
3108                 .request.slave = VHOST_USER_SLAVE_IOTLB_MSG,
3109                 .flags = VHOST_USER_VERSION,
3110                 .size = sizeof(msg.payload.iotlb),
3111                 .payload.iotlb = {
3112                         .iova = iova,
3113                         .perm = perm,
3114                         .type = VHOST_IOTLB_MISS,
3115                 },
3116         };
3117
3118         ret = send_vhost_message(dev->slave_req_fd, &msg);
3119         if (ret < 0) {
3120                 VHOST_LOG_CONFIG(ERR,
3121                                 "Failed to send IOTLB miss message (%d)\n",
3122                                 ret);
3123                 return ret;
3124         }
3125
3126         return 0;
3127 }
3128
3129 static int
3130 vhost_user_slave_config_change(struct virtio_net *dev, bool need_reply)
3131 {
3132         int ret;
3133         struct VhostUserMsg msg = {
3134                 .request.slave = VHOST_USER_SLAVE_CONFIG_CHANGE_MSG,
3135                 .flags = VHOST_USER_VERSION,
3136                 .size = 0,
3137         };
3138
3139         if (need_reply)
3140                 msg.flags |= VHOST_USER_NEED_REPLY;
3141
3142         ret = send_vhost_slave_message(dev, &msg);
3143         if (ret < 0) {
3144                 VHOST_LOG_CONFIG(ERR,
3145                                 "Failed to send config change (%d)\n",
3146                                 ret);
3147                 return ret;
3148         }
3149
3150         return process_slave_message_reply(dev, &msg);
3151 }
3152
3153 int
3154 rte_vhost_slave_config_change(int vid, bool need_reply)
3155 {
3156         struct virtio_net *dev;
3157
3158         dev = get_device(vid);
3159         if (!dev)
3160                 return -ENODEV;
3161
3162         return vhost_user_slave_config_change(dev, need_reply);
3163 }
3164
3165 static int vhost_user_slave_set_vring_host_notifier(struct virtio_net *dev,
3166                                                     int index, int fd,
3167                                                     uint64_t offset,
3168                                                     uint64_t size)
3169 {
3170         int ret;
3171         struct VhostUserMsg msg = {
3172                 .request.slave = VHOST_USER_SLAVE_VRING_HOST_NOTIFIER_MSG,
3173                 .flags = VHOST_USER_VERSION | VHOST_USER_NEED_REPLY,
3174                 .size = sizeof(msg.payload.area),
3175                 .payload.area = {
3176                         .u64 = index & VHOST_USER_VRING_IDX_MASK,
3177                         .size = size,
3178                         .offset = offset,
3179                 },
3180         };
3181
3182         if (fd < 0)
3183                 msg.payload.area.u64 |= VHOST_USER_VRING_NOFD_MASK;
3184         else {
3185                 msg.fds[0] = fd;
3186                 msg.fd_num = 1;
3187         }
3188
3189         ret = send_vhost_slave_message(dev, &msg);
3190         if (ret < 0) {
3191                 VHOST_LOG_CONFIG(ERR,
3192                         "Failed to set host notifier (%d)\n", ret);
3193                 return ret;
3194         }
3195
3196         return process_slave_message_reply(dev, &msg);
3197 }
3198
3199 int rte_vhost_host_notifier_ctrl(int vid, uint16_t qid, bool enable)
3200 {
3201         struct virtio_net *dev;
3202         struct rte_vdpa_device *vdpa_dev;
3203         int vfio_device_fd, ret = 0;
3204         uint64_t offset, size;
3205         unsigned int i, q_start, q_last;
3206
3207         dev = get_device(vid);
3208         if (!dev)
3209                 return -ENODEV;
3210
3211         vdpa_dev = dev->vdpa_dev;
3212         if (vdpa_dev == NULL)
3213                 return -ENODEV;
3214
3215         if (!(dev->features & (1ULL << VIRTIO_F_VERSION_1)) ||
3216             !(dev->features & (1ULL << VHOST_USER_F_PROTOCOL_FEATURES)) ||
3217             !(dev->protocol_features &
3218                         (1ULL << VHOST_USER_PROTOCOL_F_SLAVE_REQ)) ||
3219             !(dev->protocol_features &
3220                         (1ULL << VHOST_USER_PROTOCOL_F_SLAVE_SEND_FD)) ||
3221             !(dev->protocol_features &
3222                         (1ULL << VHOST_USER_PROTOCOL_F_HOST_NOTIFIER)))
3223                 return -ENOTSUP;
3224
3225         if (qid == RTE_VHOST_QUEUE_ALL) {
3226                 q_start = 0;
3227                 q_last = dev->nr_vring - 1;
3228         } else {
3229                 if (qid >= dev->nr_vring)
3230                         return -EINVAL;
3231                 q_start = qid;
3232                 q_last = qid;
3233         }
3234
3235         RTE_FUNC_PTR_OR_ERR_RET(vdpa_dev->ops->get_vfio_device_fd, -ENOTSUP);
3236         RTE_FUNC_PTR_OR_ERR_RET(vdpa_dev->ops->get_notify_area, -ENOTSUP);
3237
3238         vfio_device_fd = vdpa_dev->ops->get_vfio_device_fd(vid);
3239         if (vfio_device_fd < 0)
3240                 return -ENOTSUP;
3241
3242         if (enable) {
3243                 for (i = q_start; i <= q_last; i++) {
3244                         if (vdpa_dev->ops->get_notify_area(vid, i, &offset,
3245                                         &size) < 0) {
3246                                 ret = -ENOTSUP;
3247                                 goto disable;
3248                         }
3249
3250                         if (vhost_user_slave_set_vring_host_notifier(dev, i,
3251                                         vfio_device_fd, offset, size) < 0) {
3252                                 ret = -EFAULT;
3253                                 goto disable;
3254                         }
3255                 }
3256         } else {
3257 disable:
3258                 for (i = q_start; i <= q_last; i++) {
3259                         vhost_user_slave_set_vring_host_notifier(dev, i, -1,
3260                                         0, 0);
3261                 }
3262         }
3263
3264         return ret;
3265 }