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