build: use static deps for pkg-config libs.private
[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
41 #include <rte_common.h>
42 #include <rte_malloc.h>
43 #include <rte_log.h>
44
45 #include "iotlb.h"
46 #include "vhost.h"
47 #include "vhost_user.h"
48
49 #define VIRTIO_MIN_MTU 68
50 #define VIRTIO_MAX_MTU 65535
51
52 static const char *vhost_message_str[VHOST_USER_MAX] = {
53         [VHOST_USER_NONE] = "VHOST_USER_NONE",
54         [VHOST_USER_GET_FEATURES] = "VHOST_USER_GET_FEATURES",
55         [VHOST_USER_SET_FEATURES] = "VHOST_USER_SET_FEATURES",
56         [VHOST_USER_SET_OWNER] = "VHOST_USER_SET_OWNER",
57         [VHOST_USER_RESET_OWNER] = "VHOST_USER_RESET_OWNER",
58         [VHOST_USER_SET_MEM_TABLE] = "VHOST_USER_SET_MEM_TABLE",
59         [VHOST_USER_SET_LOG_BASE] = "VHOST_USER_SET_LOG_BASE",
60         [VHOST_USER_SET_LOG_FD] = "VHOST_USER_SET_LOG_FD",
61         [VHOST_USER_SET_VRING_NUM] = "VHOST_USER_SET_VRING_NUM",
62         [VHOST_USER_SET_VRING_ADDR] = "VHOST_USER_SET_VRING_ADDR",
63         [VHOST_USER_SET_VRING_BASE] = "VHOST_USER_SET_VRING_BASE",
64         [VHOST_USER_GET_VRING_BASE] = "VHOST_USER_GET_VRING_BASE",
65         [VHOST_USER_SET_VRING_KICK] = "VHOST_USER_SET_VRING_KICK",
66         [VHOST_USER_SET_VRING_CALL] = "VHOST_USER_SET_VRING_CALL",
67         [VHOST_USER_SET_VRING_ERR]  = "VHOST_USER_SET_VRING_ERR",
68         [VHOST_USER_GET_PROTOCOL_FEATURES]  = "VHOST_USER_GET_PROTOCOL_FEATURES",
69         [VHOST_USER_SET_PROTOCOL_FEATURES]  = "VHOST_USER_SET_PROTOCOL_FEATURES",
70         [VHOST_USER_GET_QUEUE_NUM]  = "VHOST_USER_GET_QUEUE_NUM",
71         [VHOST_USER_SET_VRING_ENABLE]  = "VHOST_USER_SET_VRING_ENABLE",
72         [VHOST_USER_SEND_RARP]  = "VHOST_USER_SEND_RARP",
73         [VHOST_USER_NET_SET_MTU]  = "VHOST_USER_NET_SET_MTU",
74         [VHOST_USER_SET_SLAVE_REQ_FD]  = "VHOST_USER_SET_SLAVE_REQ_FD",
75         [VHOST_USER_IOTLB_MSG]  = "VHOST_USER_IOTLB_MSG",
76         [VHOST_USER_CRYPTO_CREATE_SESS] = "VHOST_USER_CRYPTO_CREATE_SESS",
77         [VHOST_USER_CRYPTO_CLOSE_SESS] = "VHOST_USER_CRYPTO_CLOSE_SESS",
78         [VHOST_USER_POSTCOPY_ADVISE]  = "VHOST_USER_POSTCOPY_ADVISE",
79         [VHOST_USER_POSTCOPY_LISTEN]  = "VHOST_USER_POSTCOPY_LISTEN",
80         [VHOST_USER_POSTCOPY_END]  = "VHOST_USER_POSTCOPY_END",
81 };
82
83 static int send_vhost_reply(int sockfd, struct VhostUserMsg *msg);
84 static int read_vhost_message(int sockfd, struct VhostUserMsg *msg);
85
86 static uint64_t
87 get_blk_size(int fd)
88 {
89         struct stat stat;
90         int ret;
91
92         ret = fstat(fd, &stat);
93         return ret == -1 ? (uint64_t)-1 : (uint64_t)stat.st_blksize;
94 }
95
96 static void
97 free_mem_region(struct virtio_net *dev)
98 {
99         uint32_t i;
100         struct rte_vhost_mem_region *reg;
101
102         if (!dev || !dev->mem)
103                 return;
104
105         for (i = 0; i < dev->mem->nregions; i++) {
106                 reg = &dev->mem->regions[i];
107                 if (reg->host_user_addr) {
108                         munmap(reg->mmap_addr, reg->mmap_size);
109                         close(reg->fd);
110                 }
111         }
112 }
113
114 void
115 vhost_backend_cleanup(struct virtio_net *dev)
116 {
117         if (dev->mem) {
118                 free_mem_region(dev);
119                 rte_free(dev->mem);
120                 dev->mem = NULL;
121         }
122
123         free(dev->guest_pages);
124         dev->guest_pages = NULL;
125
126         if (dev->log_addr) {
127                 munmap((void *)(uintptr_t)dev->log_addr, dev->log_size);
128                 dev->log_addr = 0;
129         }
130
131         if (dev->slave_req_fd >= 0) {
132                 close(dev->slave_req_fd);
133                 dev->slave_req_fd = -1;
134         }
135
136         if (dev->postcopy_ufd >= 0) {
137                 close(dev->postcopy_ufd);
138                 dev->postcopy_ufd = -1;
139         }
140
141         dev->postcopy_listening = 0;
142 }
143
144 /*
145  * This function just returns success at the moment unless
146  * the device hasn't been initialised.
147  */
148 static int
149 vhost_user_set_owner(struct virtio_net **pdev __rte_unused,
150                         struct VhostUserMsg *msg __rte_unused,
151                         int main_fd __rte_unused)
152 {
153         return VH_RESULT_OK;
154 }
155
156 static int
157 vhost_user_reset_owner(struct virtio_net **pdev,
158                         struct VhostUserMsg *msg __rte_unused,
159                         int main_fd __rte_unused)
160 {
161         struct virtio_net *dev = *pdev;
162         vhost_destroy_device_notify(dev);
163
164         cleanup_device(dev, 0);
165         reset_device(dev);
166         return VH_RESULT_OK;
167 }
168
169 /*
170  * The features that we support are requested.
171  */
172 static int
173 vhost_user_get_features(struct virtio_net **pdev, struct VhostUserMsg *msg,
174                         int main_fd __rte_unused)
175 {
176         struct virtio_net *dev = *pdev;
177         uint64_t features = 0;
178
179         rte_vhost_driver_get_features(dev->ifname, &features);
180
181         msg->payload.u64 = features;
182         msg->size = sizeof(msg->payload.u64);
183         msg->fd_num = 0;
184
185         return VH_RESULT_REPLY;
186 }
187
188 /*
189  * The queue number that we support are requested.
190  */
191 static int
192 vhost_user_get_queue_num(struct virtio_net **pdev, struct VhostUserMsg *msg,
193                         int main_fd __rte_unused)
194 {
195         struct virtio_net *dev = *pdev;
196         uint32_t queue_num = 0;
197
198         rte_vhost_driver_get_queue_num(dev->ifname, &queue_num);
199
200         msg->payload.u64 = (uint64_t)queue_num;
201         msg->size = sizeof(msg->payload.u64);
202         msg->fd_num = 0;
203
204         return VH_RESULT_REPLY;
205 }
206
207 /*
208  * We receive the negotiated features supported by us and the virtio device.
209  */
210 static int
211 vhost_user_set_features(struct virtio_net **pdev, struct VhostUserMsg *msg,
212                         int main_fd __rte_unused)
213 {
214         struct virtio_net *dev = *pdev;
215         uint64_t features = msg->payload.u64;
216         uint64_t vhost_features = 0;
217         struct rte_vdpa_device *vdpa_dev;
218         int did = -1;
219
220         rte_vhost_driver_get_features(dev->ifname, &vhost_features);
221         if (features & ~vhost_features) {
222                 RTE_LOG(ERR, VHOST_CONFIG,
223                         "(%d) received invalid negotiated features.\n",
224                         dev->vid);
225                 return VH_RESULT_ERR;
226         }
227
228         if (dev->flags & VIRTIO_DEV_RUNNING) {
229                 if (dev->features == features)
230                         return VH_RESULT_OK;
231
232                 /*
233                  * Error out if master tries to change features while device is
234                  * in running state. The exception being VHOST_F_LOG_ALL, which
235                  * is enabled when the live-migration starts.
236                  */
237                 if ((dev->features ^ features) & ~(1ULL << VHOST_F_LOG_ALL)) {
238                         RTE_LOG(ERR, VHOST_CONFIG,
239                                 "(%d) features changed while device is running.\n",
240                                 dev->vid);
241                         return VH_RESULT_ERR;
242                 }
243
244                 if (dev->notify_ops->features_changed)
245                         dev->notify_ops->features_changed(dev->vid, features);
246         }
247
248         dev->features = features;
249         if (dev->features &
250                 ((1 << VIRTIO_NET_F_MRG_RXBUF) | (1ULL << VIRTIO_F_VERSION_1))) {
251                 dev->vhost_hlen = sizeof(struct virtio_net_hdr_mrg_rxbuf);
252         } else {
253                 dev->vhost_hlen = sizeof(struct virtio_net_hdr);
254         }
255         VHOST_LOG_DEBUG(VHOST_CONFIG,
256                 "(%d) mergeable RX buffers %s, virtio 1 %s\n",
257                 dev->vid,
258                 (dev->features & (1 << VIRTIO_NET_F_MRG_RXBUF)) ? "on" : "off",
259                 (dev->features & (1ULL << VIRTIO_F_VERSION_1)) ? "on" : "off");
260
261         if ((dev->flags & VIRTIO_DEV_BUILTIN_VIRTIO_NET) &&
262             !(dev->features & (1ULL << VIRTIO_NET_F_MQ))) {
263                 /*
264                  * Remove all but first queue pair if MQ hasn't been
265                  * negotiated. This is safe because the device is not
266                  * running at this stage.
267                  */
268                 while (dev->nr_vring > 2) {
269                         struct vhost_virtqueue *vq;
270
271                         vq = dev->virtqueue[--dev->nr_vring];
272                         if (!vq)
273                                 continue;
274
275                         dev->virtqueue[dev->nr_vring] = NULL;
276                         cleanup_vq(vq, 1);
277                         free_vq(dev, vq);
278                 }
279         }
280
281         did = dev->vdpa_dev_id;
282         vdpa_dev = rte_vdpa_get_device(did);
283         if (vdpa_dev && vdpa_dev->ops->set_features)
284                 vdpa_dev->ops->set_features(dev->vid);
285
286         return VH_RESULT_OK;
287 }
288
289 /*
290  * The virtio device sends us the size of the descriptor ring.
291  */
292 static int
293 vhost_user_set_vring_num(struct virtio_net **pdev,
294                         struct VhostUserMsg *msg,
295                         int main_fd __rte_unused)
296 {
297         struct virtio_net *dev = *pdev;
298         struct vhost_virtqueue *vq = dev->virtqueue[msg->payload.state.index];
299
300         vq->size = msg->payload.state.num;
301
302         /* VIRTIO 1.0, 2.4 Virtqueues says:
303          *
304          *   Queue Size value is always a power of 2. The maximum Queue Size
305          *   value is 32768.
306          */
307         if ((vq->size & (vq->size - 1)) || vq->size > 32768) {
308                 RTE_LOG(ERR, VHOST_CONFIG,
309                         "invalid virtqueue size %u\n", vq->size);
310                 return VH_RESULT_ERR;
311         }
312
313         if (dev->dequeue_zero_copy) {
314                 vq->nr_zmbuf = 0;
315                 vq->last_zmbuf_idx = 0;
316                 vq->zmbuf_size = vq->size;
317                 vq->zmbufs = rte_zmalloc(NULL, vq->zmbuf_size *
318                                          sizeof(struct zcopy_mbuf), 0);
319                 if (vq->zmbufs == NULL) {
320                         RTE_LOG(WARNING, VHOST_CONFIG,
321                                 "failed to allocate mem for zero copy; "
322                                 "zero copy is force disabled\n");
323                         dev->dequeue_zero_copy = 0;
324                 }
325                 TAILQ_INIT(&vq->zmbuf_list);
326         }
327
328         if (vq_is_packed(dev)) {
329                 vq->shadow_used_packed = rte_malloc(NULL,
330                                 vq->size *
331                                 sizeof(struct vring_used_elem_packed),
332                                 RTE_CACHE_LINE_SIZE);
333                 if (!vq->shadow_used_packed) {
334                         RTE_LOG(ERR, VHOST_CONFIG,
335                                         "failed to allocate memory for shadow used ring.\n");
336                         return VH_RESULT_ERR;
337                 }
338
339         } else {
340                 vq->shadow_used_split = rte_malloc(NULL,
341                                 vq->size * sizeof(struct vring_used_elem),
342                                 RTE_CACHE_LINE_SIZE);
343                 if (!vq->shadow_used_split) {
344                         RTE_LOG(ERR, VHOST_CONFIG,
345                                         "failed to allocate memory for shadow used ring.\n");
346                         return VH_RESULT_ERR;
347                 }
348         }
349
350         vq->batch_copy_elems = rte_malloc(NULL,
351                                 vq->size * sizeof(struct batch_copy_elem),
352                                 RTE_CACHE_LINE_SIZE);
353         if (!vq->batch_copy_elems) {
354                 RTE_LOG(ERR, VHOST_CONFIG,
355                         "failed to allocate memory for batching copy.\n");
356                 return VH_RESULT_ERR;
357         }
358
359         return VH_RESULT_OK;
360 }
361
362 /*
363  * Reallocate virtio_dev and vhost_virtqueue data structure to make them on the
364  * same numa node as the memory of vring descriptor.
365  */
366 #ifdef RTE_LIBRTE_VHOST_NUMA
367 static struct virtio_net*
368 numa_realloc(struct virtio_net *dev, int index)
369 {
370         int oldnode, newnode;
371         struct virtio_net *old_dev;
372         struct vhost_virtqueue *old_vq, *vq;
373         struct zcopy_mbuf *new_zmbuf;
374         struct vring_used_elem *new_shadow_used_split;
375         struct vring_used_elem_packed *new_shadow_used_packed;
376         struct batch_copy_elem *new_batch_copy_elems;
377         int ret;
378
379         old_dev = dev;
380         vq = old_vq = dev->virtqueue[index];
381
382         ret = get_mempolicy(&newnode, NULL, 0, old_vq->desc,
383                             MPOL_F_NODE | MPOL_F_ADDR);
384
385         /* check if we need to reallocate vq */
386         ret |= get_mempolicy(&oldnode, NULL, 0, old_vq,
387                              MPOL_F_NODE | MPOL_F_ADDR);
388         if (ret) {
389                 RTE_LOG(ERR, VHOST_CONFIG,
390                         "Unable to get vq numa information.\n");
391                 return dev;
392         }
393         if (oldnode != newnode) {
394                 RTE_LOG(INFO, VHOST_CONFIG,
395                         "reallocate vq from %d to %d node\n", oldnode, newnode);
396                 vq = rte_malloc_socket(NULL, sizeof(*vq), 0, newnode);
397                 if (!vq)
398                         return dev;
399
400                 memcpy(vq, old_vq, sizeof(*vq));
401                 TAILQ_INIT(&vq->zmbuf_list);
402
403                 if (dev->dequeue_zero_copy) {
404                         new_zmbuf = rte_malloc_socket(NULL, vq->zmbuf_size *
405                                         sizeof(struct zcopy_mbuf), 0, newnode);
406                         if (new_zmbuf) {
407                                 rte_free(vq->zmbufs);
408                                 vq->zmbufs = new_zmbuf;
409                         }
410                 }
411
412                 if (vq_is_packed(dev)) {
413                         new_shadow_used_packed = rte_malloc_socket(NULL,
414                                         vq->size *
415                                         sizeof(struct vring_used_elem_packed),
416                                         RTE_CACHE_LINE_SIZE,
417                                         newnode);
418                         if (new_shadow_used_packed) {
419                                 rte_free(vq->shadow_used_packed);
420                                 vq->shadow_used_packed = new_shadow_used_packed;
421                         }
422                 } else {
423                         new_shadow_used_split = rte_malloc_socket(NULL,
424                                         vq->size *
425                                         sizeof(struct vring_used_elem),
426                                         RTE_CACHE_LINE_SIZE,
427                                         newnode);
428                         if (new_shadow_used_split) {
429                                 rte_free(vq->shadow_used_split);
430                                 vq->shadow_used_split = new_shadow_used_split;
431                         }
432                 }
433
434                 new_batch_copy_elems = rte_malloc_socket(NULL,
435                         vq->size * sizeof(struct batch_copy_elem),
436                         RTE_CACHE_LINE_SIZE,
437                         newnode);
438                 if (new_batch_copy_elems) {
439                         rte_free(vq->batch_copy_elems);
440                         vq->batch_copy_elems = new_batch_copy_elems;
441                 }
442
443                 rte_free(old_vq);
444         }
445
446         /* check if we need to reallocate dev */
447         ret = get_mempolicy(&oldnode, NULL, 0, old_dev,
448                             MPOL_F_NODE | MPOL_F_ADDR);
449         if (ret) {
450                 RTE_LOG(ERR, VHOST_CONFIG,
451                         "Unable to get dev numa information.\n");
452                 goto out;
453         }
454         if (oldnode != newnode) {
455                 RTE_LOG(INFO, VHOST_CONFIG,
456                         "reallocate dev from %d to %d node\n",
457                         oldnode, newnode);
458                 dev = rte_malloc_socket(NULL, sizeof(*dev), 0, newnode);
459                 if (!dev) {
460                         dev = old_dev;
461                         goto out;
462                 }
463
464                 memcpy(dev, old_dev, sizeof(*dev));
465                 rte_free(old_dev);
466         }
467
468 out:
469         dev->virtqueue[index] = vq;
470         vhost_devices[dev->vid] = dev;
471
472         if (old_vq != vq)
473                 vhost_user_iotlb_init(dev, index);
474
475         return dev;
476 }
477 #else
478 static struct virtio_net*
479 numa_realloc(struct virtio_net *dev, int index __rte_unused)
480 {
481         return dev;
482 }
483 #endif
484
485 /* Converts QEMU virtual address to Vhost virtual address. */
486 static uint64_t
487 qva_to_vva(struct virtio_net *dev, uint64_t qva, uint64_t *len)
488 {
489         struct rte_vhost_mem_region *r;
490         uint32_t i;
491
492         if (unlikely(!dev || !dev->mem))
493                 goto out_error;
494
495         /* Find the region where the address lives. */
496         for (i = 0; i < dev->mem->nregions; i++) {
497                 r = &dev->mem->regions[i];
498
499                 if (qva >= r->guest_user_addr &&
500                     qva <  r->guest_user_addr + r->size) {
501
502                         if (unlikely(*len > r->guest_user_addr + r->size - qva))
503                                 *len = r->guest_user_addr + r->size - qva;
504
505                         return qva - r->guest_user_addr +
506                                r->host_user_addr;
507                 }
508         }
509 out_error:
510         *len = 0;
511
512         return 0;
513 }
514
515
516 /*
517  * Converts ring address to Vhost virtual address.
518  * If IOMMU is enabled, the ring address is a guest IO virtual address,
519  * else it is a QEMU virtual address.
520  */
521 static uint64_t
522 ring_addr_to_vva(struct virtio_net *dev, struct vhost_virtqueue *vq,
523                 uint64_t ra, uint64_t *size)
524 {
525         if (dev->features & (1ULL << VIRTIO_F_IOMMU_PLATFORM)) {
526                 uint64_t vva;
527
528                 vva = vhost_user_iotlb_cache_find(vq, ra,
529                                         size, VHOST_ACCESS_RW);
530                 if (!vva)
531                         vhost_user_iotlb_miss(dev, ra, VHOST_ACCESS_RW);
532
533                 return vva;
534         }
535
536         return qva_to_vva(dev, ra, size);
537 }
538
539 static struct virtio_net *
540 translate_ring_addresses(struct virtio_net *dev, int vq_index)
541 {
542         struct vhost_virtqueue *vq = dev->virtqueue[vq_index];
543         struct vhost_vring_addr *addr = &vq->ring_addrs;
544         uint64_t len;
545
546         if (vq_is_packed(dev)) {
547                 len = sizeof(struct vring_packed_desc) * vq->size;
548                 vq->desc_packed = (struct vring_packed_desc *)(uintptr_t)
549                         ring_addr_to_vva(dev, vq, addr->desc_user_addr, &len);
550                 vq->log_guest_addr = 0;
551                 if (vq->desc_packed == NULL ||
552                                 len != sizeof(struct vring_packed_desc) *
553                                 vq->size) {
554                         RTE_LOG(DEBUG, VHOST_CONFIG,
555                                 "(%d) failed to map desc_packed ring.\n",
556                                 dev->vid);
557                         return dev;
558                 }
559
560                 dev = numa_realloc(dev, vq_index);
561                 vq = dev->virtqueue[vq_index];
562                 addr = &vq->ring_addrs;
563
564                 len = sizeof(struct vring_packed_desc_event);
565                 vq->driver_event = (struct vring_packed_desc_event *)
566                                         (uintptr_t)ring_addr_to_vva(dev,
567                                         vq, addr->avail_user_addr, &len);
568                 if (vq->driver_event == NULL ||
569                                 len != sizeof(struct vring_packed_desc_event)) {
570                         RTE_LOG(DEBUG, VHOST_CONFIG,
571                                 "(%d) failed to find driver area address.\n",
572                                 dev->vid);
573                         return dev;
574                 }
575
576                 len = sizeof(struct vring_packed_desc_event);
577                 vq->device_event = (struct vring_packed_desc_event *)
578                                         (uintptr_t)ring_addr_to_vva(dev,
579                                         vq, addr->used_user_addr, &len);
580                 if (vq->device_event == NULL ||
581                                 len != sizeof(struct vring_packed_desc_event)) {
582                         RTE_LOG(DEBUG, VHOST_CONFIG,
583                                 "(%d) failed to find device area address.\n",
584                                 dev->vid);
585                         return dev;
586                 }
587
588                 return dev;
589         }
590
591         /* The addresses are converted from QEMU virtual to Vhost virtual. */
592         if (vq->desc && vq->avail && vq->used)
593                 return dev;
594
595         len = sizeof(struct vring_desc) * vq->size;
596         vq->desc = (struct vring_desc *)(uintptr_t)ring_addr_to_vva(dev,
597                         vq, addr->desc_user_addr, &len);
598         if (vq->desc == 0 || len != sizeof(struct vring_desc) * vq->size) {
599                 RTE_LOG(DEBUG, VHOST_CONFIG,
600                         "(%d) failed to map desc ring.\n",
601                         dev->vid);
602                 return dev;
603         }
604
605         dev = numa_realloc(dev, vq_index);
606         vq = dev->virtqueue[vq_index];
607         addr = &vq->ring_addrs;
608
609         len = sizeof(struct vring_avail) + sizeof(uint16_t) * vq->size;
610         vq->avail = (struct vring_avail *)(uintptr_t)ring_addr_to_vva(dev,
611                         vq, addr->avail_user_addr, &len);
612         if (vq->avail == 0 ||
613                         len != sizeof(struct vring_avail) +
614                         sizeof(uint16_t) * vq->size) {
615                 RTE_LOG(DEBUG, VHOST_CONFIG,
616                         "(%d) failed to map avail ring.\n",
617                         dev->vid);
618                 return dev;
619         }
620
621         len = sizeof(struct vring_used) +
622                 sizeof(struct vring_used_elem) * vq->size;
623         vq->used = (struct vring_used *)(uintptr_t)ring_addr_to_vva(dev,
624                         vq, addr->used_user_addr, &len);
625         if (vq->used == 0 || len != sizeof(struct vring_used) +
626                         sizeof(struct vring_used_elem) * vq->size) {
627                 RTE_LOG(DEBUG, VHOST_CONFIG,
628                         "(%d) failed to map used ring.\n",
629                         dev->vid);
630                 return dev;
631         }
632
633         if (vq->last_used_idx != vq->used->idx) {
634                 RTE_LOG(WARNING, VHOST_CONFIG,
635                         "last_used_idx (%u) and vq->used->idx (%u) mismatches; "
636                         "some packets maybe resent for Tx and dropped for Rx\n",
637                         vq->last_used_idx, vq->used->idx);
638                 vq->last_used_idx  = vq->used->idx;
639                 vq->last_avail_idx = vq->used->idx;
640         }
641
642         vq->log_guest_addr = addr->log_guest_addr;
643
644         VHOST_LOG_DEBUG(VHOST_CONFIG, "(%d) mapped address desc: %p\n",
645                         dev->vid, vq->desc);
646         VHOST_LOG_DEBUG(VHOST_CONFIG, "(%d) mapped address avail: %p\n",
647                         dev->vid, vq->avail);
648         VHOST_LOG_DEBUG(VHOST_CONFIG, "(%d) mapped address used: %p\n",
649                         dev->vid, vq->used);
650         VHOST_LOG_DEBUG(VHOST_CONFIG, "(%d) log_guest_addr: %" PRIx64 "\n",
651                         dev->vid, vq->log_guest_addr);
652
653         return dev;
654 }
655
656 /*
657  * The virtio device sends us the desc, used and avail ring addresses.
658  * This function then converts these to our address space.
659  */
660 static int
661 vhost_user_set_vring_addr(struct virtio_net **pdev, struct VhostUserMsg *msg,
662                         int main_fd __rte_unused)
663 {
664         struct virtio_net *dev = *pdev;
665         struct vhost_virtqueue *vq;
666         struct vhost_vring_addr *addr = &msg->payload.addr;
667
668         if (dev->mem == NULL)
669                 return VH_RESULT_ERR;
670
671         /* addr->index refers to the queue index. The txq 1, rxq is 0. */
672         vq = dev->virtqueue[msg->payload.addr.index];
673
674         /*
675          * Rings addresses should not be interpreted as long as the ring is not
676          * started and enabled
677          */
678         memcpy(&vq->ring_addrs, addr, sizeof(*addr));
679
680         vring_invalidate(dev, vq);
681
682         if (vq->enabled && (dev->features &
683                                 (1ULL << VHOST_USER_F_PROTOCOL_FEATURES))) {
684                 dev = translate_ring_addresses(dev, msg->payload.addr.index);
685                 if (!dev)
686                         return VH_RESULT_ERR;
687
688                 *pdev = dev;
689         }
690
691         return VH_RESULT_OK;
692 }
693
694 /*
695  * The virtio device sends us the available ring last used index.
696  */
697 static int
698 vhost_user_set_vring_base(struct virtio_net **pdev,
699                         struct VhostUserMsg *msg,
700                         int main_fd __rte_unused)
701 {
702         struct virtio_net *dev = *pdev;
703         struct vhost_virtqueue *vq = dev->virtqueue[msg->payload.state.index];
704         uint64_t val = msg->payload.state.num;
705
706         if (vq_is_packed(dev)) {
707                 /*
708                  * Bit[0:14]: avail index
709                  * Bit[15]: avail wrap counter
710                  */
711                 vq->last_avail_idx = val & 0x7fff;
712                 vq->avail_wrap_counter = !!(val & (0x1 << 15));
713                 /*
714                  * Set used index to same value as available one, as
715                  * their values should be the same since ring processing
716                  * was stopped at get time.
717                  */
718                 vq->last_used_idx = vq->last_avail_idx;
719                 vq->used_wrap_counter = vq->avail_wrap_counter;
720         } else {
721                 vq->last_used_idx = msg->payload.state.num;
722                 vq->last_avail_idx = msg->payload.state.num;
723         }
724
725         return VH_RESULT_OK;
726 }
727
728 static int
729 add_one_guest_page(struct virtio_net *dev, uint64_t guest_phys_addr,
730                    uint64_t host_phys_addr, uint64_t size)
731 {
732         struct guest_page *page, *last_page;
733
734         if (dev->nr_guest_pages == dev->max_guest_pages) {
735                 dev->max_guest_pages *= 2;
736                 dev->guest_pages = realloc(dev->guest_pages,
737                                         dev->max_guest_pages * sizeof(*page));
738                 if (!dev->guest_pages) {
739                         RTE_LOG(ERR, VHOST_CONFIG, "cannot realloc guest_pages\n");
740                         return -1;
741                 }
742         }
743
744         if (dev->nr_guest_pages > 0) {
745                 last_page = &dev->guest_pages[dev->nr_guest_pages - 1];
746                 /* merge if the two pages are continuous */
747                 if (host_phys_addr == last_page->host_phys_addr +
748                                       last_page->size) {
749                         last_page->size += size;
750                         return 0;
751                 }
752         }
753
754         page = &dev->guest_pages[dev->nr_guest_pages++];
755         page->guest_phys_addr = guest_phys_addr;
756         page->host_phys_addr  = host_phys_addr;
757         page->size = size;
758
759         return 0;
760 }
761
762 static int
763 add_guest_pages(struct virtio_net *dev, struct rte_vhost_mem_region *reg,
764                 uint64_t page_size)
765 {
766         uint64_t reg_size = reg->size;
767         uint64_t host_user_addr  = reg->host_user_addr;
768         uint64_t guest_phys_addr = reg->guest_phys_addr;
769         uint64_t host_phys_addr;
770         uint64_t size;
771
772         host_phys_addr = rte_mem_virt2iova((void *)(uintptr_t)host_user_addr);
773         size = page_size - (guest_phys_addr & (page_size - 1));
774         size = RTE_MIN(size, reg_size);
775
776         if (add_one_guest_page(dev, guest_phys_addr, host_phys_addr, size) < 0)
777                 return -1;
778
779         host_user_addr  += size;
780         guest_phys_addr += size;
781         reg_size -= size;
782
783         while (reg_size > 0) {
784                 size = RTE_MIN(reg_size, page_size);
785                 host_phys_addr = rte_mem_virt2iova((void *)(uintptr_t)
786                                                   host_user_addr);
787                 if (add_one_guest_page(dev, guest_phys_addr, host_phys_addr,
788                                 size) < 0)
789                         return -1;
790
791                 host_user_addr  += size;
792                 guest_phys_addr += size;
793                 reg_size -= size;
794         }
795
796         return 0;
797 }
798
799 #ifdef RTE_LIBRTE_VHOST_DEBUG
800 /* TODO: enable it only in debug mode? */
801 static void
802 dump_guest_pages(struct virtio_net *dev)
803 {
804         uint32_t i;
805         struct guest_page *page;
806
807         for (i = 0; i < dev->nr_guest_pages; i++) {
808                 page = &dev->guest_pages[i];
809
810                 RTE_LOG(INFO, VHOST_CONFIG,
811                         "guest physical page region %u\n"
812                         "\t guest_phys_addr: %" PRIx64 "\n"
813                         "\t host_phys_addr : %" PRIx64 "\n"
814                         "\t size           : %" PRIx64 "\n",
815                         i,
816                         page->guest_phys_addr,
817                         page->host_phys_addr,
818                         page->size);
819         }
820 }
821 #else
822 #define dump_guest_pages(dev)
823 #endif
824
825 static bool
826 vhost_memory_changed(struct VhostUserMemory *new,
827                      struct rte_vhost_memory *old)
828 {
829         uint32_t i;
830
831         if (new->nregions != old->nregions)
832                 return true;
833
834         for (i = 0; i < new->nregions; ++i) {
835                 VhostUserMemoryRegion *new_r = &new->regions[i];
836                 struct rte_vhost_mem_region *old_r = &old->regions[i];
837
838                 if (new_r->guest_phys_addr != old_r->guest_phys_addr)
839                         return true;
840                 if (new_r->memory_size != old_r->size)
841                         return true;
842                 if (new_r->userspace_addr != old_r->guest_user_addr)
843                         return true;
844         }
845
846         return false;
847 }
848
849 static int
850 vhost_user_set_mem_table(struct virtio_net **pdev, struct VhostUserMsg *msg,
851                         int main_fd)
852 {
853         struct virtio_net *dev = *pdev;
854         struct VhostUserMemory *memory = &msg->payload.memory;
855         struct rte_vhost_mem_region *reg;
856         void *mmap_addr;
857         uint64_t mmap_size;
858         uint64_t mmap_offset;
859         uint64_t alignment;
860         uint32_t i;
861         int populate;
862         int fd;
863
864         if (memory->nregions > VHOST_MEMORY_MAX_NREGIONS) {
865                 RTE_LOG(ERR, VHOST_CONFIG,
866                         "too many memory regions (%u)\n", memory->nregions);
867                 return VH_RESULT_ERR;
868         }
869
870         if (dev->mem && !vhost_memory_changed(memory, dev->mem)) {
871                 RTE_LOG(INFO, VHOST_CONFIG,
872                         "(%d) memory regions not changed\n", dev->vid);
873
874                 for (i = 0; i < memory->nregions; i++)
875                         close(msg->fds[i]);
876
877                 return VH_RESULT_OK;
878         }
879
880         if (dev->mem) {
881                 free_mem_region(dev);
882                 rte_free(dev->mem);
883                 dev->mem = NULL;
884         }
885
886         /* Flush IOTLB cache as previous HVAs are now invalid */
887         if (dev->features & (1ULL << VIRTIO_F_IOMMU_PLATFORM))
888                 for (i = 0; i < dev->nr_vring; i++)
889                         vhost_user_iotlb_flush_all(dev->virtqueue[i]);
890
891         dev->nr_guest_pages = 0;
892         if (!dev->guest_pages) {
893                 dev->max_guest_pages = 8;
894                 dev->guest_pages = malloc(dev->max_guest_pages *
895                                                 sizeof(struct guest_page));
896                 if (dev->guest_pages == NULL) {
897                         RTE_LOG(ERR, VHOST_CONFIG,
898                                 "(%d) failed to allocate memory "
899                                 "for dev->guest_pages\n",
900                                 dev->vid);
901                         return VH_RESULT_ERR;
902                 }
903         }
904
905         dev->mem = rte_zmalloc("vhost-mem-table", sizeof(struct rte_vhost_memory) +
906                 sizeof(struct rte_vhost_mem_region) * memory->nregions, 0);
907         if (dev->mem == NULL) {
908                 RTE_LOG(ERR, VHOST_CONFIG,
909                         "(%d) failed to allocate memory for dev->mem\n",
910                         dev->vid);
911                 return VH_RESULT_ERR;
912         }
913         dev->mem->nregions = memory->nregions;
914
915         for (i = 0; i < memory->nregions; i++) {
916                 fd  = msg->fds[i];
917                 reg = &dev->mem->regions[i];
918
919                 reg->guest_phys_addr = memory->regions[i].guest_phys_addr;
920                 reg->guest_user_addr = memory->regions[i].userspace_addr;
921                 reg->size            = memory->regions[i].memory_size;
922                 reg->fd              = fd;
923
924                 mmap_offset = memory->regions[i].mmap_offset;
925
926                 /* Check for memory_size + mmap_offset overflow */
927                 if (mmap_offset >= -reg->size) {
928                         RTE_LOG(ERR, VHOST_CONFIG,
929                                 "mmap_offset (%#"PRIx64") and memory_size "
930                                 "(%#"PRIx64") overflow\n",
931                                 mmap_offset, reg->size);
932                         goto err_mmap;
933                 }
934
935                 mmap_size = reg->size + mmap_offset;
936
937                 /* mmap() without flag of MAP_ANONYMOUS, should be called
938                  * with length argument aligned with hugepagesz at older
939                  * longterm version Linux, like 2.6.32 and 3.2.72, or
940                  * mmap() will fail with EINVAL.
941                  *
942                  * to avoid failure, make sure in caller to keep length
943                  * aligned.
944                  */
945                 alignment = get_blk_size(fd);
946                 if (alignment == (uint64_t)-1) {
947                         RTE_LOG(ERR, VHOST_CONFIG,
948                                 "couldn't get hugepage size through fstat\n");
949                         goto err_mmap;
950                 }
951                 mmap_size = RTE_ALIGN_CEIL(mmap_size, alignment);
952
953                 populate = (dev->dequeue_zero_copy) ? MAP_POPULATE : 0;
954                 mmap_addr = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE,
955                                  MAP_SHARED | populate, fd, 0);
956
957                 if (mmap_addr == MAP_FAILED) {
958                         RTE_LOG(ERR, VHOST_CONFIG,
959                                 "mmap region %u failed.\n", i);
960                         goto err_mmap;
961                 }
962
963                 reg->mmap_addr = mmap_addr;
964                 reg->mmap_size = mmap_size;
965                 reg->host_user_addr = (uint64_t)(uintptr_t)mmap_addr +
966                                       mmap_offset;
967
968                 if (dev->dequeue_zero_copy)
969                         if (add_guest_pages(dev, reg, alignment) < 0) {
970                                 RTE_LOG(ERR, VHOST_CONFIG,
971                                         "adding guest pages to region %u failed.\n",
972                                         i);
973                                 goto err_mmap;
974                         }
975
976                 RTE_LOG(INFO, VHOST_CONFIG,
977                         "guest memory region %u, size: 0x%" PRIx64 "\n"
978                         "\t guest physical addr: 0x%" PRIx64 "\n"
979                         "\t guest virtual  addr: 0x%" PRIx64 "\n"
980                         "\t host  virtual  addr: 0x%" PRIx64 "\n"
981                         "\t mmap addr : 0x%" PRIx64 "\n"
982                         "\t mmap size : 0x%" PRIx64 "\n"
983                         "\t mmap align: 0x%" PRIx64 "\n"
984                         "\t mmap off  : 0x%" PRIx64 "\n",
985                         i, reg->size,
986                         reg->guest_phys_addr,
987                         reg->guest_user_addr,
988                         reg->host_user_addr,
989                         (uint64_t)(uintptr_t)mmap_addr,
990                         mmap_size,
991                         alignment,
992                         mmap_offset);
993
994                 if (dev->postcopy_listening) {
995                         /*
996                          * We haven't a better way right now than sharing
997                          * DPDK's virtual address with Qemu, so that Qemu can
998                          * retrieve the region offset when handling userfaults.
999                          */
1000                         memory->regions[i].userspace_addr =
1001                                 reg->host_user_addr;
1002                 }
1003         }
1004         if (dev->postcopy_listening) {
1005                 /* Send the addresses back to qemu */
1006                 msg->fd_num = 0;
1007                 send_vhost_reply(main_fd, msg);
1008
1009                 /* Wait for qemu to acknolwedge it's got the addresses
1010                  * we've got to wait before we're allowed to generate faults.
1011                  */
1012                 VhostUserMsg ack_msg;
1013                 if (read_vhost_message(main_fd, &ack_msg) <= 0) {
1014                         RTE_LOG(ERR, VHOST_CONFIG,
1015                                 "Failed to read qemu ack on postcopy set-mem-table\n");
1016                         goto err_mmap;
1017                 }
1018                 if (ack_msg.request.master != VHOST_USER_SET_MEM_TABLE) {
1019                         RTE_LOG(ERR, VHOST_CONFIG,
1020                                 "Bad qemu ack on postcopy set-mem-table (%d)\n",
1021                                 ack_msg.request.master);
1022                         goto err_mmap;
1023                 }
1024
1025                 /* Now userfault register and we can use the memory */
1026                 for (i = 0; i < memory->nregions; i++) {
1027 #ifdef RTE_LIBRTE_VHOST_POSTCOPY
1028                         reg = &dev->mem->regions[i];
1029                         struct uffdio_register reg_struct;
1030
1031                         /*
1032                          * Let's register all the mmap'ed area to ensure
1033                          * alignment on page boundary.
1034                          */
1035                         reg_struct.range.start =
1036                                 (uint64_t)(uintptr_t)reg->mmap_addr;
1037                         reg_struct.range.len = reg->mmap_size;
1038                         reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
1039
1040                         if (ioctl(dev->postcopy_ufd, UFFDIO_REGISTER,
1041                                                 &reg_struct)) {
1042                                 RTE_LOG(ERR, VHOST_CONFIG,
1043                                         "Failed to register ufd for region %d: (ufd = %d) %s\n",
1044                                         i, dev->postcopy_ufd,
1045                                         strerror(errno));
1046                                 goto err_mmap;
1047                         }
1048                         RTE_LOG(INFO, VHOST_CONFIG,
1049                                 "\t userfaultfd registered for range : %llx - %llx\n",
1050                                 reg_struct.range.start,
1051                                 reg_struct.range.start +
1052                                 reg_struct.range.len - 1);
1053 #else
1054                         goto err_mmap;
1055 #endif
1056                 }
1057         }
1058
1059         for (i = 0; i < dev->nr_vring; i++) {
1060                 struct vhost_virtqueue *vq = dev->virtqueue[i];
1061
1062                 if (vq->desc || vq->avail || vq->used) {
1063                         /*
1064                          * If the memory table got updated, the ring addresses
1065                          * need to be translated again as virtual addresses have
1066                          * changed.
1067                          */
1068                         vring_invalidate(dev, vq);
1069
1070                         dev = translate_ring_addresses(dev, i);
1071                         if (!dev) {
1072                                 dev = *pdev;
1073                                 goto err_mmap;
1074                         }
1075
1076                         *pdev = dev;
1077                 }
1078         }
1079
1080         dump_guest_pages(dev);
1081
1082         return VH_RESULT_OK;
1083
1084 err_mmap:
1085         free_mem_region(dev);
1086         rte_free(dev->mem);
1087         dev->mem = NULL;
1088         return VH_RESULT_ERR;
1089 }
1090
1091 static bool
1092 vq_is_ready(struct virtio_net *dev, struct vhost_virtqueue *vq)
1093 {
1094         bool rings_ok;
1095
1096         if (!vq)
1097                 return false;
1098
1099         if (vq_is_packed(dev))
1100                 rings_ok = !!vq->desc_packed;
1101         else
1102                 rings_ok = vq->desc && vq->avail && vq->used;
1103
1104         return rings_ok &&
1105                vq->kickfd != VIRTIO_UNINITIALIZED_EVENTFD &&
1106                vq->callfd != VIRTIO_UNINITIALIZED_EVENTFD;
1107 }
1108
1109 static int
1110 virtio_is_ready(struct virtio_net *dev)
1111 {
1112         struct vhost_virtqueue *vq;
1113         uint32_t i;
1114
1115         if (dev->nr_vring == 0)
1116                 return 0;
1117
1118         for (i = 0; i < dev->nr_vring; i++) {
1119                 vq = dev->virtqueue[i];
1120
1121                 if (!vq_is_ready(dev, vq))
1122                         return 0;
1123         }
1124
1125         RTE_LOG(INFO, VHOST_CONFIG,
1126                 "virtio is now ready for processing.\n");
1127         return 1;
1128 }
1129
1130 static int
1131 vhost_user_set_vring_call(struct virtio_net **pdev, struct VhostUserMsg *msg,
1132                         int main_fd __rte_unused)
1133 {
1134         struct virtio_net *dev = *pdev;
1135         struct vhost_vring_file file;
1136         struct vhost_virtqueue *vq;
1137
1138         file.index = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
1139         if (msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK)
1140                 file.fd = VIRTIO_INVALID_EVENTFD;
1141         else
1142                 file.fd = msg->fds[0];
1143         RTE_LOG(INFO, VHOST_CONFIG,
1144                 "vring call idx:%d file:%d\n", file.index, file.fd);
1145
1146         vq = dev->virtqueue[file.index];
1147         if (vq->callfd >= 0)
1148                 close(vq->callfd);
1149
1150         vq->callfd = file.fd;
1151
1152         return VH_RESULT_OK;
1153 }
1154
1155 static int vhost_user_set_vring_err(struct virtio_net **pdev __rte_unused,
1156                         struct VhostUserMsg *msg,
1157                         int main_fd __rte_unused)
1158 {
1159         if (!(msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK))
1160                 close(msg->fds[0]);
1161         RTE_LOG(INFO, VHOST_CONFIG, "not implemented\n");
1162
1163         return VH_RESULT_OK;
1164 }
1165
1166 static int
1167 vhost_user_set_vring_kick(struct virtio_net **pdev, struct VhostUserMsg *msg,
1168                         int main_fd __rte_unused)
1169 {
1170         struct virtio_net *dev = *pdev;
1171         struct vhost_vring_file file;
1172         struct vhost_virtqueue *vq;
1173
1174         file.index = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
1175         if (msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK)
1176                 file.fd = VIRTIO_INVALID_EVENTFD;
1177         else
1178                 file.fd = msg->fds[0];
1179         RTE_LOG(INFO, VHOST_CONFIG,
1180                 "vring kick idx:%d file:%d\n", file.index, file.fd);
1181
1182         /* Interpret ring addresses only when ring is started. */
1183         dev = translate_ring_addresses(dev, file.index);
1184         if (!dev)
1185                 return VH_RESULT_ERR;
1186
1187         *pdev = dev;
1188
1189         vq = dev->virtqueue[file.index];
1190
1191         /*
1192          * When VHOST_USER_F_PROTOCOL_FEATURES is not negotiated,
1193          * the ring starts already enabled. Otherwise, it is enabled via
1194          * the SET_VRING_ENABLE message.
1195          */
1196         if (!(dev->features & (1ULL << VHOST_USER_F_PROTOCOL_FEATURES)))
1197                 vq->enabled = 1;
1198
1199         if (vq->kickfd >= 0)
1200                 close(vq->kickfd);
1201         vq->kickfd = file.fd;
1202
1203         return VH_RESULT_OK;
1204 }
1205
1206 static void
1207 free_zmbufs(struct vhost_virtqueue *vq)
1208 {
1209         struct zcopy_mbuf *zmbuf, *next;
1210
1211         for (zmbuf = TAILQ_FIRST(&vq->zmbuf_list);
1212              zmbuf != NULL; zmbuf = next) {
1213                 next = TAILQ_NEXT(zmbuf, next);
1214
1215                 rte_pktmbuf_free(zmbuf->mbuf);
1216                 TAILQ_REMOVE(&vq->zmbuf_list, zmbuf, next);
1217         }
1218
1219         rte_free(vq->zmbufs);
1220 }
1221
1222 /*
1223  * when virtio is stopped, qemu will send us the GET_VRING_BASE message.
1224  */
1225 static int
1226 vhost_user_get_vring_base(struct virtio_net **pdev,
1227                         struct VhostUserMsg *msg,
1228                         int main_fd __rte_unused)
1229 {
1230         struct virtio_net *dev = *pdev;
1231         struct vhost_virtqueue *vq = dev->virtqueue[msg->payload.state.index];
1232         uint64_t val;
1233
1234         /* We have to stop the queue (virtio) if it is running. */
1235         vhost_destroy_device_notify(dev);
1236
1237         dev->flags &= ~VIRTIO_DEV_READY;
1238         dev->flags &= ~VIRTIO_DEV_VDPA_CONFIGURED;
1239
1240         /* Here we are safe to get the indexes */
1241         if (vq_is_packed(dev)) {
1242                 /*
1243                  * Bit[0:14]: avail index
1244                  * Bit[15]: avail wrap counter
1245                  */
1246                 val = vq->last_avail_idx & 0x7fff;
1247                 val |= vq->avail_wrap_counter << 15;
1248                 msg->payload.state.num = val;
1249         } else {
1250                 msg->payload.state.num = vq->last_avail_idx;
1251         }
1252
1253         RTE_LOG(INFO, VHOST_CONFIG,
1254                 "vring base idx:%d file:%d\n", msg->payload.state.index,
1255                 msg->payload.state.num);
1256         /*
1257          * Based on current qemu vhost-user implementation, this message is
1258          * sent and only sent in vhost_vring_stop.
1259          * TODO: cleanup the vring, it isn't usable since here.
1260          */
1261         if (vq->kickfd >= 0)
1262                 close(vq->kickfd);
1263
1264         vq->kickfd = VIRTIO_UNINITIALIZED_EVENTFD;
1265
1266         if (vq->callfd >= 0)
1267                 close(vq->callfd);
1268
1269         vq->callfd = VIRTIO_UNINITIALIZED_EVENTFD;
1270
1271         if (dev->dequeue_zero_copy)
1272                 free_zmbufs(vq);
1273         if (vq_is_packed(dev)) {
1274                 rte_free(vq->shadow_used_packed);
1275                 vq->shadow_used_packed = NULL;
1276         } else {
1277                 rte_free(vq->shadow_used_split);
1278                 vq->shadow_used_split = NULL;
1279         }
1280
1281         rte_free(vq->batch_copy_elems);
1282         vq->batch_copy_elems = NULL;
1283
1284         msg->size = sizeof(msg->payload.state);
1285         msg->fd_num = 0;
1286
1287         return VH_RESULT_REPLY;
1288 }
1289
1290 /*
1291  * when virtio queues are ready to work, qemu will send us to
1292  * enable the virtio queue pair.
1293  */
1294 static int
1295 vhost_user_set_vring_enable(struct virtio_net **pdev,
1296                         struct VhostUserMsg *msg,
1297                         int main_fd __rte_unused)
1298 {
1299         struct virtio_net *dev = *pdev;
1300         int enable = (int)msg->payload.state.num;
1301         int index = (int)msg->payload.state.index;
1302         struct rte_vdpa_device *vdpa_dev;
1303         int did = -1;
1304
1305         RTE_LOG(INFO, VHOST_CONFIG,
1306                 "set queue enable: %d to qp idx: %d\n",
1307                 enable, index);
1308
1309         did = dev->vdpa_dev_id;
1310         vdpa_dev = rte_vdpa_get_device(did);
1311         if (vdpa_dev && vdpa_dev->ops->set_vring_state)
1312                 vdpa_dev->ops->set_vring_state(dev->vid, index, enable);
1313
1314         if (dev->notify_ops->vring_state_changed)
1315                 dev->notify_ops->vring_state_changed(dev->vid,
1316                                 index, enable);
1317
1318         dev->virtqueue[index]->enabled = enable;
1319
1320         return VH_RESULT_OK;
1321 }
1322
1323 static int
1324 vhost_user_get_protocol_features(struct virtio_net **pdev,
1325                         struct VhostUserMsg *msg,
1326                         int main_fd __rte_unused)
1327 {
1328         struct virtio_net *dev = *pdev;
1329         uint64_t features, protocol_features;
1330
1331         rte_vhost_driver_get_features(dev->ifname, &features);
1332         rte_vhost_driver_get_protocol_features(dev->ifname, &protocol_features);
1333
1334         /*
1335          * REPLY_ACK protocol feature is only mandatory for now
1336          * for IOMMU feature. If IOMMU is explicitly disabled by the
1337          * application, disable also REPLY_ACK feature for older buggy
1338          * Qemu versions (from v2.7.0 to v2.9.0).
1339          */
1340         if (!(features & (1ULL << VIRTIO_F_IOMMU_PLATFORM)))
1341                 protocol_features &= ~(1ULL << VHOST_USER_PROTOCOL_F_REPLY_ACK);
1342
1343         msg->payload.u64 = protocol_features;
1344         msg->size = sizeof(msg->payload.u64);
1345         msg->fd_num = 0;
1346
1347         return VH_RESULT_REPLY;
1348 }
1349
1350 static int
1351 vhost_user_set_protocol_features(struct virtio_net **pdev,
1352                         struct VhostUserMsg *msg,
1353                         int main_fd __rte_unused)
1354 {
1355         struct virtio_net *dev = *pdev;
1356         uint64_t protocol_features = msg->payload.u64;
1357         uint64_t slave_protocol_features = 0;
1358
1359         rte_vhost_driver_get_protocol_features(dev->ifname,
1360                         &slave_protocol_features);
1361         if (protocol_features & ~slave_protocol_features) {
1362                 RTE_LOG(ERR, VHOST_CONFIG,
1363                         "(%d) received invalid protocol features.\n",
1364                         dev->vid);
1365                 return VH_RESULT_ERR;
1366         }
1367
1368         dev->protocol_features = protocol_features;
1369
1370         return VH_RESULT_OK;
1371 }
1372
1373 static int
1374 vhost_user_set_log_base(struct virtio_net **pdev, struct VhostUserMsg *msg,
1375                         int main_fd __rte_unused)
1376 {
1377         struct virtio_net *dev = *pdev;
1378         int fd = msg->fds[0];
1379         uint64_t size, off;
1380         void *addr;
1381
1382         if (fd < 0) {
1383                 RTE_LOG(ERR, VHOST_CONFIG, "invalid log fd: %d\n", fd);
1384                 return VH_RESULT_ERR;
1385         }
1386
1387         if (msg->size != sizeof(VhostUserLog)) {
1388                 RTE_LOG(ERR, VHOST_CONFIG,
1389                         "invalid log base msg size: %"PRId32" != %d\n",
1390                         msg->size, (int)sizeof(VhostUserLog));
1391                 return VH_RESULT_ERR;
1392         }
1393
1394         size = msg->payload.log.mmap_size;
1395         off  = msg->payload.log.mmap_offset;
1396
1397         /* Don't allow mmap_offset to point outside the mmap region */
1398         if (off > size) {
1399                 RTE_LOG(ERR, VHOST_CONFIG,
1400                         "log offset %#"PRIx64" exceeds log size %#"PRIx64"\n",
1401                         off, size);
1402                 return VH_RESULT_ERR;
1403         }
1404
1405         RTE_LOG(INFO, VHOST_CONFIG,
1406                 "log mmap size: %"PRId64", offset: %"PRId64"\n",
1407                 size, off);
1408
1409         /*
1410          * mmap from 0 to workaround a hugepage mmap bug: mmap will
1411          * fail when offset is not page size aligned.
1412          */
1413         addr = mmap(0, size + off, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
1414         close(fd);
1415         if (addr == MAP_FAILED) {
1416                 RTE_LOG(ERR, VHOST_CONFIG, "mmap log base failed!\n");
1417                 return VH_RESULT_ERR;
1418         }
1419
1420         /*
1421          * Free previously mapped log memory on occasionally
1422          * multiple VHOST_USER_SET_LOG_BASE.
1423          */
1424         if (dev->log_addr) {
1425                 munmap((void *)(uintptr_t)dev->log_addr, dev->log_size);
1426         }
1427         dev->log_addr = (uint64_t)(uintptr_t)addr;
1428         dev->log_base = dev->log_addr + off;
1429         dev->log_size = size;
1430
1431         /*
1432          * The spec is not clear about it (yet), but QEMU doesn't expect
1433          * any payload in the reply.
1434          */
1435         msg->size = 0;
1436         msg->fd_num = 0;
1437
1438         return VH_RESULT_REPLY;
1439 }
1440
1441 static int vhost_user_set_log_fd(struct virtio_net **pdev __rte_unused,
1442                         struct VhostUserMsg *msg,
1443                         int main_fd __rte_unused)
1444 {
1445         close(msg->fds[0]);
1446         RTE_LOG(INFO, VHOST_CONFIG, "not implemented.\n");
1447
1448         return VH_RESULT_OK;
1449 }
1450
1451 /*
1452  * An rarp packet is constructed and broadcasted to notify switches about
1453  * the new location of the migrated VM, so that packets from outside will
1454  * not be lost after migration.
1455  *
1456  * However, we don't actually "send" a rarp packet here, instead, we set
1457  * a flag 'broadcast_rarp' to let rte_vhost_dequeue_burst() inject it.
1458  */
1459 static int
1460 vhost_user_send_rarp(struct virtio_net **pdev, struct VhostUserMsg *msg,
1461                         int main_fd __rte_unused)
1462 {
1463         struct virtio_net *dev = *pdev;
1464         uint8_t *mac = (uint8_t *)&msg->payload.u64;
1465         struct rte_vdpa_device *vdpa_dev;
1466         int did = -1;
1467
1468         RTE_LOG(DEBUG, VHOST_CONFIG,
1469                 ":: mac: %02x:%02x:%02x:%02x:%02x:%02x\n",
1470                 mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
1471         memcpy(dev->mac.addr_bytes, mac, 6);
1472
1473         /*
1474          * Set the flag to inject a RARP broadcast packet at
1475          * rte_vhost_dequeue_burst().
1476          *
1477          * rte_smp_wmb() is for making sure the mac is copied
1478          * before the flag is set.
1479          */
1480         rte_smp_wmb();
1481         rte_atomic16_set(&dev->broadcast_rarp, 1);
1482         did = dev->vdpa_dev_id;
1483         vdpa_dev = rte_vdpa_get_device(did);
1484         if (vdpa_dev && vdpa_dev->ops->migration_done)
1485                 vdpa_dev->ops->migration_done(dev->vid);
1486
1487         return VH_RESULT_OK;
1488 }
1489
1490 static int
1491 vhost_user_net_set_mtu(struct virtio_net **pdev, struct VhostUserMsg *msg,
1492                         int main_fd __rte_unused)
1493 {
1494         struct virtio_net *dev = *pdev;
1495         if (msg->payload.u64 < VIRTIO_MIN_MTU ||
1496                         msg->payload.u64 > VIRTIO_MAX_MTU) {
1497                 RTE_LOG(ERR, VHOST_CONFIG, "Invalid MTU size (%"PRIu64")\n",
1498                                 msg->payload.u64);
1499
1500                 return VH_RESULT_ERR;
1501         }
1502
1503         dev->mtu = msg->payload.u64;
1504
1505         return VH_RESULT_OK;
1506 }
1507
1508 static int
1509 vhost_user_set_req_fd(struct virtio_net **pdev, struct VhostUserMsg *msg,
1510                         int main_fd __rte_unused)
1511 {
1512         struct virtio_net *dev = *pdev;
1513         int fd = msg->fds[0];
1514
1515         if (fd < 0) {
1516                 RTE_LOG(ERR, VHOST_CONFIG,
1517                                 "Invalid file descriptor for slave channel (%d)\n",
1518                                 fd);
1519                 return VH_RESULT_ERR;
1520         }
1521
1522         dev->slave_req_fd = fd;
1523
1524         return VH_RESULT_OK;
1525 }
1526
1527 static int
1528 is_vring_iotlb_update(struct vhost_virtqueue *vq, struct vhost_iotlb_msg *imsg)
1529 {
1530         struct vhost_vring_addr *ra;
1531         uint64_t start, end;
1532
1533         start = imsg->iova;
1534         end = start + imsg->size;
1535
1536         ra = &vq->ring_addrs;
1537         if (ra->desc_user_addr >= start && ra->desc_user_addr < end)
1538                 return 1;
1539         if (ra->avail_user_addr >= start && ra->avail_user_addr < end)
1540                 return 1;
1541         if (ra->used_user_addr >= start && ra->used_user_addr < end)
1542                 return 1;
1543
1544         return 0;
1545 }
1546
1547 static int
1548 is_vring_iotlb_invalidate(struct vhost_virtqueue *vq,
1549                                 struct vhost_iotlb_msg *imsg)
1550 {
1551         uint64_t istart, iend, vstart, vend;
1552
1553         istart = imsg->iova;
1554         iend = istart + imsg->size - 1;
1555
1556         vstart = (uintptr_t)vq->desc;
1557         vend = vstart + sizeof(struct vring_desc) * vq->size - 1;
1558         if (vstart <= iend && istart <= vend)
1559                 return 1;
1560
1561         vstart = (uintptr_t)vq->avail;
1562         vend = vstart + sizeof(struct vring_avail);
1563         vend += sizeof(uint16_t) * vq->size - 1;
1564         if (vstart <= iend && istart <= vend)
1565                 return 1;
1566
1567         vstart = (uintptr_t)vq->used;
1568         vend = vstart + sizeof(struct vring_used);
1569         vend += sizeof(struct vring_used_elem) * vq->size - 1;
1570         if (vstart <= iend && istart <= vend)
1571                 return 1;
1572
1573         return 0;
1574 }
1575
1576 static int
1577 vhost_user_iotlb_msg(struct virtio_net **pdev, struct VhostUserMsg *msg,
1578                         int main_fd __rte_unused)
1579 {
1580         struct virtio_net *dev = *pdev;
1581         struct vhost_iotlb_msg *imsg = &msg->payload.iotlb;
1582         uint16_t i;
1583         uint64_t vva, len;
1584
1585         switch (imsg->type) {
1586         case VHOST_IOTLB_UPDATE:
1587                 len = imsg->size;
1588                 vva = qva_to_vva(dev, imsg->uaddr, &len);
1589                 if (!vva)
1590                         return VH_RESULT_ERR;
1591
1592                 for (i = 0; i < dev->nr_vring; i++) {
1593                         struct vhost_virtqueue *vq = dev->virtqueue[i];
1594
1595                         vhost_user_iotlb_cache_insert(vq, imsg->iova, vva,
1596                                         len, imsg->perm);
1597
1598                         if (is_vring_iotlb_update(vq, imsg))
1599                                 *pdev = dev = translate_ring_addresses(dev, i);
1600                 }
1601                 break;
1602         case VHOST_IOTLB_INVALIDATE:
1603                 for (i = 0; i < dev->nr_vring; i++) {
1604                         struct vhost_virtqueue *vq = dev->virtqueue[i];
1605
1606                         vhost_user_iotlb_cache_remove(vq, imsg->iova,
1607                                         imsg->size);
1608
1609                         if (is_vring_iotlb_invalidate(vq, imsg))
1610                                 vring_invalidate(dev, vq);
1611                 }
1612                 break;
1613         default:
1614                 RTE_LOG(ERR, VHOST_CONFIG, "Invalid IOTLB message type (%d)\n",
1615                                 imsg->type);
1616                 return VH_RESULT_ERR;
1617         }
1618
1619         return VH_RESULT_OK;
1620 }
1621
1622 static int
1623 vhost_user_set_postcopy_advise(struct virtio_net **pdev,
1624                         struct VhostUserMsg *msg,
1625                         int main_fd __rte_unused)
1626 {
1627         struct virtio_net *dev = *pdev;
1628 #ifdef RTE_LIBRTE_VHOST_POSTCOPY
1629         struct uffdio_api api_struct;
1630
1631         dev->postcopy_ufd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
1632
1633         if (dev->postcopy_ufd == -1) {
1634                 RTE_LOG(ERR, VHOST_CONFIG, "Userfaultfd not available: %s\n",
1635                         strerror(errno));
1636                 return VH_RESULT_ERR;
1637         }
1638         api_struct.api = UFFD_API;
1639         api_struct.features = 0;
1640         if (ioctl(dev->postcopy_ufd, UFFDIO_API, &api_struct)) {
1641                 RTE_LOG(ERR, VHOST_CONFIG, "UFFDIO_API ioctl failure: %s\n",
1642                         strerror(errno));
1643                 close(dev->postcopy_ufd);
1644                 dev->postcopy_ufd = -1;
1645                 return VH_RESULT_ERR;
1646         }
1647         msg->fds[0] = dev->postcopy_ufd;
1648         msg->fd_num = 1;
1649
1650         return VH_RESULT_REPLY;
1651 #else
1652         dev->postcopy_ufd = -1;
1653         msg->fd_num = 0;
1654
1655         return VH_RESULT_ERR;
1656 #endif
1657 }
1658
1659 static int
1660 vhost_user_set_postcopy_listen(struct virtio_net **pdev,
1661                         struct VhostUserMsg *msg __rte_unused,
1662                         int main_fd __rte_unused)
1663 {
1664         struct virtio_net *dev = *pdev;
1665
1666         if (dev->mem && dev->mem->nregions) {
1667                 RTE_LOG(ERR, VHOST_CONFIG,
1668                         "Regions already registered at postcopy-listen\n");
1669                 return VH_RESULT_ERR;
1670         }
1671         dev->postcopy_listening = 1;
1672
1673         return VH_RESULT_OK;
1674 }
1675
1676 static int
1677 vhost_user_postcopy_end(struct virtio_net **pdev, struct VhostUserMsg *msg,
1678                         int main_fd __rte_unused)
1679 {
1680         struct virtio_net *dev = *pdev;
1681
1682         dev->postcopy_listening = 0;
1683         if (dev->postcopy_ufd >= 0) {
1684                 close(dev->postcopy_ufd);
1685                 dev->postcopy_ufd = -1;
1686         }
1687
1688         msg->payload.u64 = 0;
1689         msg->size = sizeof(msg->payload.u64);
1690         msg->fd_num = 0;
1691
1692         return VH_RESULT_REPLY;
1693 }
1694
1695 typedef int (*vhost_message_handler_t)(struct virtio_net **pdev,
1696                                         struct VhostUserMsg *msg,
1697                                         int main_fd);
1698 static vhost_message_handler_t vhost_message_handlers[VHOST_USER_MAX] = {
1699         [VHOST_USER_NONE] = NULL,
1700         [VHOST_USER_GET_FEATURES] = vhost_user_get_features,
1701         [VHOST_USER_SET_FEATURES] = vhost_user_set_features,
1702         [VHOST_USER_SET_OWNER] = vhost_user_set_owner,
1703         [VHOST_USER_RESET_OWNER] = vhost_user_reset_owner,
1704         [VHOST_USER_SET_MEM_TABLE] = vhost_user_set_mem_table,
1705         [VHOST_USER_SET_LOG_BASE] = vhost_user_set_log_base,
1706         [VHOST_USER_SET_LOG_FD] = vhost_user_set_log_fd,
1707         [VHOST_USER_SET_VRING_NUM] = vhost_user_set_vring_num,
1708         [VHOST_USER_SET_VRING_ADDR] = vhost_user_set_vring_addr,
1709         [VHOST_USER_SET_VRING_BASE] = vhost_user_set_vring_base,
1710         [VHOST_USER_GET_VRING_BASE] = vhost_user_get_vring_base,
1711         [VHOST_USER_SET_VRING_KICK] = vhost_user_set_vring_kick,
1712         [VHOST_USER_SET_VRING_CALL] = vhost_user_set_vring_call,
1713         [VHOST_USER_SET_VRING_ERR] = vhost_user_set_vring_err,
1714         [VHOST_USER_GET_PROTOCOL_FEATURES] = vhost_user_get_protocol_features,
1715         [VHOST_USER_SET_PROTOCOL_FEATURES] = vhost_user_set_protocol_features,
1716         [VHOST_USER_GET_QUEUE_NUM] = vhost_user_get_queue_num,
1717         [VHOST_USER_SET_VRING_ENABLE] = vhost_user_set_vring_enable,
1718         [VHOST_USER_SEND_RARP] = vhost_user_send_rarp,
1719         [VHOST_USER_NET_SET_MTU] = vhost_user_net_set_mtu,
1720         [VHOST_USER_SET_SLAVE_REQ_FD] = vhost_user_set_req_fd,
1721         [VHOST_USER_IOTLB_MSG] = vhost_user_iotlb_msg,
1722         [VHOST_USER_POSTCOPY_ADVISE] = vhost_user_set_postcopy_advise,
1723         [VHOST_USER_POSTCOPY_LISTEN] = vhost_user_set_postcopy_listen,
1724         [VHOST_USER_POSTCOPY_END] = vhost_user_postcopy_end,
1725 };
1726
1727
1728 /* return bytes# of read on success or negative val on failure. */
1729 static int
1730 read_vhost_message(int sockfd, struct VhostUserMsg *msg)
1731 {
1732         int ret;
1733
1734         ret = read_fd_message(sockfd, (char *)msg, VHOST_USER_HDR_SIZE,
1735                 msg->fds, VHOST_MEMORY_MAX_NREGIONS, &msg->fd_num);
1736         if (ret <= 0)
1737                 return ret;
1738
1739         if (msg->size) {
1740                 if (msg->size > sizeof(msg->payload)) {
1741                         RTE_LOG(ERR, VHOST_CONFIG,
1742                                 "invalid msg size: %d\n", msg->size);
1743                         return -1;
1744                 }
1745                 ret = read(sockfd, &msg->payload, msg->size);
1746                 if (ret <= 0)
1747                         return ret;
1748                 if (ret != (int)msg->size) {
1749                         RTE_LOG(ERR, VHOST_CONFIG,
1750                                 "read control message failed\n");
1751                         return -1;
1752                 }
1753         }
1754
1755         return ret;
1756 }
1757
1758 static int
1759 send_vhost_message(int sockfd, struct VhostUserMsg *msg)
1760 {
1761         if (!msg)
1762                 return 0;
1763
1764         return send_fd_message(sockfd, (char *)msg,
1765                 VHOST_USER_HDR_SIZE + msg->size, msg->fds, msg->fd_num);
1766 }
1767
1768 static int
1769 send_vhost_reply(int sockfd, struct VhostUserMsg *msg)
1770 {
1771         if (!msg)
1772                 return 0;
1773
1774         msg->flags &= ~VHOST_USER_VERSION_MASK;
1775         msg->flags &= ~VHOST_USER_NEED_REPLY;
1776         msg->flags |= VHOST_USER_VERSION;
1777         msg->flags |= VHOST_USER_REPLY_MASK;
1778
1779         return send_vhost_message(sockfd, msg);
1780 }
1781
1782 static int
1783 send_vhost_slave_message(struct virtio_net *dev, struct VhostUserMsg *msg)
1784 {
1785         int ret;
1786
1787         if (msg->flags & VHOST_USER_NEED_REPLY)
1788                 rte_spinlock_lock(&dev->slave_req_lock);
1789
1790         ret = send_vhost_message(dev->slave_req_fd, msg);
1791         if (ret < 0 && (msg->flags & VHOST_USER_NEED_REPLY))
1792                 rte_spinlock_unlock(&dev->slave_req_lock);
1793
1794         return ret;
1795 }
1796
1797 /*
1798  * Allocate a queue pair if it hasn't been allocated yet
1799  */
1800 static int
1801 vhost_user_check_and_alloc_queue_pair(struct virtio_net *dev,
1802                         struct VhostUserMsg *msg)
1803 {
1804         uint16_t vring_idx;
1805
1806         switch (msg->request.master) {
1807         case VHOST_USER_SET_VRING_KICK:
1808         case VHOST_USER_SET_VRING_CALL:
1809         case VHOST_USER_SET_VRING_ERR:
1810                 vring_idx = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
1811                 break;
1812         case VHOST_USER_SET_VRING_NUM:
1813         case VHOST_USER_SET_VRING_BASE:
1814         case VHOST_USER_SET_VRING_ENABLE:
1815                 vring_idx = msg->payload.state.index;
1816                 break;
1817         case VHOST_USER_SET_VRING_ADDR:
1818                 vring_idx = msg->payload.addr.index;
1819                 break;
1820         default:
1821                 return 0;
1822         }
1823
1824         if (vring_idx >= VHOST_MAX_VRING) {
1825                 RTE_LOG(ERR, VHOST_CONFIG,
1826                         "invalid vring index: %u\n", vring_idx);
1827                 return -1;
1828         }
1829
1830         if (dev->virtqueue[vring_idx])
1831                 return 0;
1832
1833         return alloc_vring_queue(dev, vring_idx);
1834 }
1835
1836 static void
1837 vhost_user_lock_all_queue_pairs(struct virtio_net *dev)
1838 {
1839         unsigned int i = 0;
1840         unsigned int vq_num = 0;
1841
1842         while (vq_num < dev->nr_vring) {
1843                 struct vhost_virtqueue *vq = dev->virtqueue[i];
1844
1845                 if (vq) {
1846                         rte_spinlock_lock(&vq->access_lock);
1847                         vq_num++;
1848                 }
1849                 i++;
1850         }
1851 }
1852
1853 static void
1854 vhost_user_unlock_all_queue_pairs(struct virtio_net *dev)
1855 {
1856         unsigned int i = 0;
1857         unsigned int vq_num = 0;
1858
1859         while (vq_num < dev->nr_vring) {
1860                 struct vhost_virtqueue *vq = dev->virtqueue[i];
1861
1862                 if (vq) {
1863                         rte_spinlock_unlock(&vq->access_lock);
1864                         vq_num++;
1865                 }
1866                 i++;
1867         }
1868 }
1869
1870 int
1871 vhost_user_msg_handler(int vid, int fd)
1872 {
1873         struct virtio_net *dev;
1874         struct VhostUserMsg msg;
1875         struct rte_vdpa_device *vdpa_dev;
1876         int did = -1;
1877         int ret;
1878         int unlock_required = 0;
1879         uint32_t skip_master = 0;
1880         int request;
1881
1882         dev = get_device(vid);
1883         if (dev == NULL)
1884                 return -1;
1885
1886         if (!dev->notify_ops) {
1887                 dev->notify_ops = vhost_driver_callback_get(dev->ifname);
1888                 if (!dev->notify_ops) {
1889                         RTE_LOG(ERR, VHOST_CONFIG,
1890                                 "failed to get callback ops for driver %s\n",
1891                                 dev->ifname);
1892                         return -1;
1893                 }
1894         }
1895
1896         ret = read_vhost_message(fd, &msg);
1897         if (ret <= 0 || msg.request.master >= VHOST_USER_MAX) {
1898                 if (ret < 0)
1899                         RTE_LOG(ERR, VHOST_CONFIG,
1900                                 "vhost read message failed\n");
1901                 else if (ret == 0)
1902                         RTE_LOG(INFO, VHOST_CONFIG,
1903                                 "vhost peer closed\n");
1904                 else
1905                         RTE_LOG(ERR, VHOST_CONFIG,
1906                                 "vhost read incorrect message\n");
1907
1908                 return -1;
1909         }
1910
1911         ret = 0;
1912         if (msg.request.master != VHOST_USER_IOTLB_MSG)
1913                 RTE_LOG(INFO, VHOST_CONFIG, "read message %s\n",
1914                         vhost_message_str[msg.request.master]);
1915         else
1916                 RTE_LOG(DEBUG, VHOST_CONFIG, "read message %s\n",
1917                         vhost_message_str[msg.request.master]);
1918
1919         ret = vhost_user_check_and_alloc_queue_pair(dev, &msg);
1920         if (ret < 0) {
1921                 RTE_LOG(ERR, VHOST_CONFIG,
1922                         "failed to alloc queue\n");
1923                 return -1;
1924         }
1925
1926         /*
1927          * Note: we don't lock all queues on VHOST_USER_GET_VRING_BASE
1928          * and VHOST_USER_RESET_OWNER, since it is sent when virtio stops
1929          * and device is destroyed. destroy_device waits for queues to be
1930          * inactive, so it is safe. Otherwise taking the access_lock
1931          * would cause a dead lock.
1932          */
1933         switch (msg.request.master) {
1934         case VHOST_USER_SET_FEATURES:
1935         case VHOST_USER_SET_PROTOCOL_FEATURES:
1936         case VHOST_USER_SET_OWNER:
1937         case VHOST_USER_SET_MEM_TABLE:
1938         case VHOST_USER_SET_LOG_BASE:
1939         case VHOST_USER_SET_LOG_FD:
1940         case VHOST_USER_SET_VRING_NUM:
1941         case VHOST_USER_SET_VRING_ADDR:
1942         case VHOST_USER_SET_VRING_BASE:
1943         case VHOST_USER_SET_VRING_KICK:
1944         case VHOST_USER_SET_VRING_CALL:
1945         case VHOST_USER_SET_VRING_ERR:
1946         case VHOST_USER_SET_VRING_ENABLE:
1947         case VHOST_USER_SEND_RARP:
1948         case VHOST_USER_NET_SET_MTU:
1949         case VHOST_USER_SET_SLAVE_REQ_FD:
1950                 vhost_user_lock_all_queue_pairs(dev);
1951                 unlock_required = 1;
1952                 break;
1953         default:
1954                 break;
1955
1956         }
1957
1958         if (dev->extern_ops.pre_msg_handle) {
1959                 ret = (*dev->extern_ops.pre_msg_handle)(dev->vid,
1960                                 (void *)&msg, &skip_master);
1961                 if (ret == VH_RESULT_ERR)
1962                         goto skip_to_reply;
1963                 else if (ret == VH_RESULT_REPLY)
1964                         send_vhost_reply(fd, &msg);
1965
1966                 if (skip_master)
1967                         goto skip_to_post_handle;
1968         }
1969
1970         request = msg.request.master;
1971         if (request > VHOST_USER_NONE && request < VHOST_USER_MAX) {
1972                 if (!vhost_message_handlers[request])
1973                         goto skip_to_post_handle;
1974                 ret = vhost_message_handlers[request](&dev, &msg, fd);
1975
1976                 switch (ret) {
1977                 case VH_RESULT_ERR:
1978                         RTE_LOG(ERR, VHOST_CONFIG,
1979                                 "Processing %s failed.\n",
1980                                 vhost_message_str[request]);
1981                         break;
1982                 case VH_RESULT_OK:
1983                         RTE_LOG(DEBUG, VHOST_CONFIG,
1984                                 "Processing %s succeeded.\n",
1985                                 vhost_message_str[request]);
1986                         break;
1987                 case VH_RESULT_REPLY:
1988                         RTE_LOG(DEBUG, VHOST_CONFIG,
1989                                 "Processing %s succeeded and needs reply.\n",
1990                                 vhost_message_str[request]);
1991                         send_vhost_reply(fd, &msg);
1992                         break;
1993                 }
1994         } else {
1995                 RTE_LOG(ERR, VHOST_CONFIG,
1996                         "Requested invalid message type %d.\n", request);
1997                 ret = VH_RESULT_ERR;
1998         }
1999
2000 skip_to_post_handle:
2001         if (ret != VH_RESULT_ERR && dev->extern_ops.post_msg_handle) {
2002                 ret = (*dev->extern_ops.post_msg_handle)(
2003                                 dev->vid, (void *)&msg);
2004                 if (ret == VH_RESULT_ERR)
2005                         goto skip_to_reply;
2006                 else if (ret == VH_RESULT_REPLY)
2007                         send_vhost_reply(fd, &msg);
2008         }
2009
2010 skip_to_reply:
2011         if (unlock_required)
2012                 vhost_user_unlock_all_queue_pairs(dev);
2013
2014         /*
2015          * If the request required a reply that was already sent,
2016          * this optional reply-ack won't be sent as the
2017          * VHOST_USER_NEED_REPLY was cleared in send_vhost_reply().
2018          */
2019         if (msg.flags & VHOST_USER_NEED_REPLY) {
2020                 msg.payload.u64 = ret == VH_RESULT_ERR;
2021                 msg.size = sizeof(msg.payload.u64);
2022                 msg.fd_num = 0;
2023                 send_vhost_reply(fd, &msg);
2024         } else if (ret == VH_RESULT_ERR) {
2025                 RTE_LOG(ERR, VHOST_CONFIG,
2026                         "vhost message handling failed.\n");
2027                 return -1;
2028         }
2029
2030         if (!(dev->flags & VIRTIO_DEV_RUNNING) && virtio_is_ready(dev)) {
2031                 dev->flags |= VIRTIO_DEV_READY;
2032
2033                 if (!(dev->flags & VIRTIO_DEV_RUNNING)) {
2034                         if (dev->dequeue_zero_copy) {
2035                                 RTE_LOG(INFO, VHOST_CONFIG,
2036                                                 "dequeue zero copy is enabled\n");
2037                         }
2038
2039                         if (dev->notify_ops->new_device(dev->vid) == 0)
2040                                 dev->flags |= VIRTIO_DEV_RUNNING;
2041                 }
2042         }
2043
2044         did = dev->vdpa_dev_id;
2045         vdpa_dev = rte_vdpa_get_device(did);
2046         if (vdpa_dev && virtio_is_ready(dev) &&
2047                         !(dev->flags & VIRTIO_DEV_VDPA_CONFIGURED) &&
2048                         msg.request.master == VHOST_USER_SET_VRING_ENABLE) {
2049                 if (vdpa_dev->ops->dev_conf)
2050                         vdpa_dev->ops->dev_conf(dev->vid);
2051                 dev->flags |= VIRTIO_DEV_VDPA_CONFIGURED;
2052         }
2053
2054         return 0;
2055 }
2056
2057 static int process_slave_message_reply(struct virtio_net *dev,
2058                                        const struct VhostUserMsg *msg)
2059 {
2060         struct VhostUserMsg msg_reply;
2061         int ret;
2062
2063         if ((msg->flags & VHOST_USER_NEED_REPLY) == 0)
2064                 return 0;
2065
2066         if (read_vhost_message(dev->slave_req_fd, &msg_reply) < 0) {
2067                 ret = -1;
2068                 goto out;
2069         }
2070
2071         if (msg_reply.request.slave != msg->request.slave) {
2072                 RTE_LOG(ERR, VHOST_CONFIG,
2073                         "Received unexpected msg type (%u), expected %u\n",
2074                         msg_reply.request.slave, msg->request.slave);
2075                 ret = -1;
2076                 goto out;
2077         }
2078
2079         ret = msg_reply.payload.u64 ? -1 : 0;
2080
2081 out:
2082         rte_spinlock_unlock(&dev->slave_req_lock);
2083         return ret;
2084 }
2085
2086 int
2087 vhost_user_iotlb_miss(struct virtio_net *dev, uint64_t iova, uint8_t perm)
2088 {
2089         int ret;
2090         struct VhostUserMsg msg = {
2091                 .request.slave = VHOST_USER_SLAVE_IOTLB_MSG,
2092                 .flags = VHOST_USER_VERSION,
2093                 .size = sizeof(msg.payload.iotlb),
2094                 .payload.iotlb = {
2095                         .iova = iova,
2096                         .perm = perm,
2097                         .type = VHOST_IOTLB_MISS,
2098                 },
2099         };
2100
2101         ret = send_vhost_message(dev->slave_req_fd, &msg);
2102         if (ret < 0) {
2103                 RTE_LOG(ERR, VHOST_CONFIG,
2104                                 "Failed to send IOTLB miss message (%d)\n",
2105                                 ret);
2106                 return ret;
2107         }
2108
2109         return 0;
2110 }
2111
2112 static int vhost_user_slave_set_vring_host_notifier(struct virtio_net *dev,
2113                                                     int index, int fd,
2114                                                     uint64_t offset,
2115                                                     uint64_t size)
2116 {
2117         int ret;
2118         struct VhostUserMsg msg = {
2119                 .request.slave = VHOST_USER_SLAVE_VRING_HOST_NOTIFIER_MSG,
2120                 .flags = VHOST_USER_VERSION | VHOST_USER_NEED_REPLY,
2121                 .size = sizeof(msg.payload.area),
2122                 .payload.area = {
2123                         .u64 = index & VHOST_USER_VRING_IDX_MASK,
2124                         .size = size,
2125                         .offset = offset,
2126                 },
2127         };
2128
2129         if (fd < 0)
2130                 msg.payload.area.u64 |= VHOST_USER_VRING_NOFD_MASK;
2131         else {
2132                 msg.fds[0] = fd;
2133                 msg.fd_num = 1;
2134         }
2135
2136         ret = send_vhost_slave_message(dev, &msg);
2137         if (ret < 0) {
2138                 RTE_LOG(ERR, VHOST_CONFIG,
2139                         "Failed to set host notifier (%d)\n", ret);
2140                 return ret;
2141         }
2142
2143         return process_slave_message_reply(dev, &msg);
2144 }
2145
2146 int rte_vhost_host_notifier_ctrl(int vid, bool enable)
2147 {
2148         struct virtio_net *dev;
2149         struct rte_vdpa_device *vdpa_dev;
2150         int vfio_device_fd, did, ret = 0;
2151         uint64_t offset, size;
2152         unsigned int i;
2153
2154         dev = get_device(vid);
2155         if (!dev)
2156                 return -ENODEV;
2157
2158         did = dev->vdpa_dev_id;
2159         if (did < 0)
2160                 return -EINVAL;
2161
2162         if (!(dev->features & (1ULL << VIRTIO_F_VERSION_1)) ||
2163             !(dev->features & (1ULL << VHOST_USER_F_PROTOCOL_FEATURES)) ||
2164             !(dev->protocol_features &
2165                         (1ULL << VHOST_USER_PROTOCOL_F_SLAVE_REQ)) ||
2166             !(dev->protocol_features &
2167                         (1ULL << VHOST_USER_PROTOCOL_F_SLAVE_SEND_FD)) ||
2168             !(dev->protocol_features &
2169                         (1ULL << VHOST_USER_PROTOCOL_F_HOST_NOTIFIER)))
2170                 return -ENOTSUP;
2171
2172         vdpa_dev = rte_vdpa_get_device(did);
2173         if (!vdpa_dev)
2174                 return -ENODEV;
2175
2176         RTE_FUNC_PTR_OR_ERR_RET(vdpa_dev->ops->get_vfio_device_fd, -ENOTSUP);
2177         RTE_FUNC_PTR_OR_ERR_RET(vdpa_dev->ops->get_notify_area, -ENOTSUP);
2178
2179         vfio_device_fd = vdpa_dev->ops->get_vfio_device_fd(vid);
2180         if (vfio_device_fd < 0)
2181                 return -ENOTSUP;
2182
2183         if (enable) {
2184                 for (i = 0; i < dev->nr_vring; i++) {
2185                         if (vdpa_dev->ops->get_notify_area(vid, i, &offset,
2186                                         &size) < 0) {
2187                                 ret = -ENOTSUP;
2188                                 goto disable;
2189                         }
2190
2191                         if (vhost_user_slave_set_vring_host_notifier(dev, i,
2192                                         vfio_device_fd, offset, size) < 0) {
2193                                 ret = -EFAULT;
2194                                 goto disable;
2195                         }
2196                 }
2197         } else {
2198 disable:
2199                 for (i = 0; i < dev->nr_vring; i++) {
2200                         vhost_user_slave_set_vring_host_notifier(dev, i, -1,
2201                                         0, 0);
2202                 }
2203         }
2204
2205         return ret;
2206 }