xref: /qemu/hw/virtio/vhost-vdpa.c (revision 32f0c7ce4c948b2e275dca3cf7fa2a00677b9c1d)
1 /*
2  * vhost-vdpa
3  *
4  *  Copyright(c) 2017-2018 Intel Corporation.
5  *  Copyright(c) 2020 Red Hat, Inc.
6  *
7  * This work is licensed under the terms of the GNU GPL, version 2 or later.
8  * See the COPYING file in the top-level directory.
9  *
10  */
11 
12 #include "qemu/osdep.h"
13 #include <linux/vhost.h>
14 #include <linux/vfio.h>
15 #include <sys/eventfd.h>
16 #include <sys/ioctl.h>
17 #include "exec/target_page.h"
18 #include "hw/virtio/vhost.h"
19 #include "hw/virtio/vhost-backend.h"
20 #include "hw/virtio/virtio-net.h"
21 #include "hw/virtio/vhost-shadow-virtqueue.h"
22 #include "hw/virtio/vhost-vdpa.h"
23 #include "system/address-spaces.h"
24 #include "migration/blocker.h"
25 #include "qemu/cutils.h"
26 #include "qemu/main-loop.h"
27 #include "trace.h"
28 #include "qapi/error.h"
29 
30 /*
31  * Return one past the end of the end of section. Be careful with uint64_t
32  * conversions!
33  */
34 static Int128 vhost_vdpa_section_end(const MemoryRegionSection *section,
35                                      int page_mask)
36 {
37     Int128 llend = int128_make64(section->offset_within_address_space);
38     llend = int128_add(llend, section->size);
39     llend = int128_and(llend, int128_exts64(page_mask));
40 
41     return llend;
42 }
43 
44 static bool vhost_vdpa_listener_skipped_section(MemoryRegionSection *section,
45                                                 uint64_t iova_min,
46                                                 uint64_t iova_max,
47                                                 int page_mask)
48 {
49     Int128 llend;
50     bool is_ram = memory_region_is_ram(section->mr);
51     bool is_iommu = memory_region_is_iommu(section->mr);
52     bool is_protected = memory_region_is_protected(section->mr);
53 
54     /* vhost-vDPA doesn't allow MMIO to be mapped  */
55     bool is_ram_device = memory_region_is_ram_device(section->mr);
56 
57     if ((!is_ram && !is_iommu) || is_protected || is_ram_device) {
58         trace_vhost_vdpa_skipped_memory_section(is_ram, is_iommu, is_protected,
59                                                 is_ram_device, iova_min,
60                                                 iova_max, page_mask);
61         return true;
62     }
63 
64     if (section->offset_within_address_space < iova_min) {
65         error_report("RAM section out of device range (min=0x%" PRIx64
66                      ", addr=0x%" HWADDR_PRIx ")",
67                      iova_min, section->offset_within_address_space);
68         return true;
69     }
70     /*
71      * While using vIOMMU, sometimes the section will be larger than iova_max,
72      * but the memory that actually maps is smaller, so move the check to
73      * function vhost_vdpa_iommu_map_notify(). That function will use the actual
74      * size that maps to the kernel
75      */
76 
77     if (!is_iommu) {
78         llend = vhost_vdpa_section_end(section, page_mask);
79         if (int128_gt(llend, int128_make64(iova_max))) {
80             error_report("RAM section out of device range (max=0x%" PRIx64
81                          ", end addr=0x%" PRIx64 ")",
82                          iova_max, int128_get64(llend));
83             return true;
84         }
85     }
86 
87     return false;
88 }
89 
90 /*
91  * The caller must set asid = 0 if the device does not support asid.
92  * This is not an ABI break since it is set to 0 by the initializer anyway.
93  */
94 int vhost_vdpa_dma_map(VhostVDPAShared *s, uint32_t asid, hwaddr iova,
95                        hwaddr size, void *vaddr, bool readonly)
96 {
97     struct vhost_msg_v2 msg = {};
98     int fd = s->device_fd;
99     int ret = 0;
100 
101     msg.type = VHOST_IOTLB_MSG_V2;
102     msg.asid = asid;
103     msg.iotlb.iova = iova;
104     msg.iotlb.size = size;
105     msg.iotlb.uaddr = (uint64_t)(uintptr_t)vaddr;
106     msg.iotlb.perm = readonly ? VHOST_ACCESS_RO : VHOST_ACCESS_RW;
107     msg.iotlb.type = VHOST_IOTLB_UPDATE;
108 
109     trace_vhost_vdpa_dma_map(s, fd, msg.type, msg.asid, msg.iotlb.iova,
110                              msg.iotlb.size, msg.iotlb.uaddr, msg.iotlb.perm,
111                              msg.iotlb.type);
112 
113     if (write(fd, &msg, sizeof(msg)) != sizeof(msg)) {
114         error_report("failed to write, fd=%d, errno=%d (%s)",
115             fd, errno, strerror(errno));
116         return -EIO ;
117     }
118 
119     return ret;
120 }
121 
122 /*
123  * The caller must set asid = 0 if the device does not support asid.
124  * This is not an ABI break since it is set to 0 by the initializer anyway.
125  */
126 int vhost_vdpa_dma_unmap(VhostVDPAShared *s, uint32_t asid, hwaddr iova,
127                          hwaddr size)
128 {
129     struct vhost_msg_v2 msg = {};
130     int fd = s->device_fd;
131     int ret = 0;
132 
133     msg.type = VHOST_IOTLB_MSG_V2;
134     msg.asid = asid;
135     msg.iotlb.iova = iova;
136     msg.iotlb.size = size;
137     msg.iotlb.type = VHOST_IOTLB_INVALIDATE;
138 
139     trace_vhost_vdpa_dma_unmap(s, fd, msg.type, msg.asid, msg.iotlb.iova,
140                                msg.iotlb.size, msg.iotlb.type);
141 
142     if (write(fd, &msg, sizeof(msg)) != sizeof(msg)) {
143         error_report("failed to write, fd=%d, errno=%d (%s)",
144             fd, errno, strerror(errno));
145         return -EIO ;
146     }
147 
148     return ret;
149 }
150 
151 static void vhost_vdpa_listener_begin_batch(VhostVDPAShared *s)
152 {
153     int fd = s->device_fd;
154     struct vhost_msg_v2 msg = {
155         .type = VHOST_IOTLB_MSG_V2,
156         .iotlb.type = VHOST_IOTLB_BATCH_BEGIN,
157     };
158 
159     trace_vhost_vdpa_listener_begin_batch(s, fd, msg.type, msg.iotlb.type);
160     if (write(fd, &msg, sizeof(msg)) != sizeof(msg)) {
161         error_report("failed to write, fd=%d, errno=%d (%s)",
162                      fd, errno, strerror(errno));
163     }
164 }
165 
166 static void vhost_vdpa_iotlb_batch_begin_once(VhostVDPAShared *s)
167 {
168     if (s->backend_cap & (0x1ULL << VHOST_BACKEND_F_IOTLB_BATCH) &&
169         !s->iotlb_batch_begin_sent) {
170         vhost_vdpa_listener_begin_batch(s);
171     }
172 
173     s->iotlb_batch_begin_sent = true;
174 }
175 
176 static void vhost_vdpa_listener_commit(MemoryListener *listener)
177 {
178     VhostVDPAShared *s = container_of(listener, VhostVDPAShared, listener);
179     struct vhost_msg_v2 msg = {};
180     int fd = s->device_fd;
181 
182     if (!(s->backend_cap & (0x1ULL << VHOST_BACKEND_F_IOTLB_BATCH))) {
183         return;
184     }
185 
186     if (!s->iotlb_batch_begin_sent) {
187         return;
188     }
189 
190     msg.type = VHOST_IOTLB_MSG_V2;
191     msg.iotlb.type = VHOST_IOTLB_BATCH_END;
192 
193     trace_vhost_vdpa_listener_commit(s, fd, msg.type, msg.iotlb.type);
194     if (write(fd, &msg, sizeof(msg)) != sizeof(msg)) {
195         error_report("failed to write, fd=%d, errno=%d (%s)",
196                      fd, errno, strerror(errno));
197     }
198 
199     s->iotlb_batch_begin_sent = false;
200 }
201 
202 static void vhost_vdpa_iommu_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
203 {
204     struct vdpa_iommu *iommu = container_of(n, struct vdpa_iommu, n);
205 
206     hwaddr iova = iotlb->iova + iommu->iommu_offset;
207     VhostVDPAShared *s = iommu->dev_shared;
208     void *vaddr;
209     int ret;
210     Int128 llend;
211     Error *local_err = NULL;
212 
213     if (iotlb->target_as != &address_space_memory) {
214         error_report("Wrong target AS \"%s\", only system memory is allowed",
215                      iotlb->target_as->name ? iotlb->target_as->name : "none");
216         return;
217     }
218     RCU_READ_LOCK_GUARD();
219     /* check if RAM section out of device range */
220     llend = int128_add(int128_makes64(iotlb->addr_mask), int128_makes64(iova));
221     if (int128_gt(llend, int128_make64(s->iova_range.last))) {
222         error_report("RAM section out of device range (max=0x%" PRIx64
223                      ", end addr=0x%" PRIx64 ")",
224                      s->iova_range.last, int128_get64(llend));
225         return;
226     }
227 
228     if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) {
229         bool read_only;
230 
231         if (!memory_get_xlat_addr(iotlb, &vaddr, NULL, &read_only, NULL,
232                                   &local_err)) {
233             error_report_err(local_err);
234             return;
235         }
236         ret = vhost_vdpa_dma_map(s, VHOST_VDPA_GUEST_PA_ASID, iova,
237                                  iotlb->addr_mask + 1, vaddr, read_only);
238         if (ret) {
239             error_report("vhost_vdpa_dma_map(%p, 0x%" HWADDR_PRIx ", "
240                          "0x%" HWADDR_PRIx ", %p) = %d (%m)",
241                          s, iova, iotlb->addr_mask + 1, vaddr, ret);
242         }
243     } else {
244         ret = vhost_vdpa_dma_unmap(s, VHOST_VDPA_GUEST_PA_ASID, iova,
245                                    iotlb->addr_mask + 1);
246         if (ret) {
247             error_report("vhost_vdpa_dma_unmap(%p, 0x%" HWADDR_PRIx ", "
248                          "0x%" HWADDR_PRIx ") = %d (%m)",
249                          s, iova, iotlb->addr_mask + 1, ret);
250         }
251     }
252 }
253 
254 static void vhost_vdpa_iommu_region_add(MemoryListener *listener,
255                                         MemoryRegionSection *section)
256 {
257     VhostVDPAShared *s = container_of(listener, VhostVDPAShared, listener);
258 
259     struct vdpa_iommu *iommu;
260     Int128 end;
261     int iommu_idx;
262     IOMMUMemoryRegion *iommu_mr;
263     int ret;
264 
265     iommu_mr = IOMMU_MEMORY_REGION(section->mr);
266 
267     iommu = g_malloc0(sizeof(*iommu));
268     end = int128_add(int128_make64(section->offset_within_region),
269                      section->size);
270     end = int128_sub(end, int128_one());
271     iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
272                                                    MEMTXATTRS_UNSPECIFIED);
273     iommu->iommu_mr = iommu_mr;
274     iommu_notifier_init(&iommu->n, vhost_vdpa_iommu_map_notify,
275                         IOMMU_NOTIFIER_IOTLB_EVENTS,
276                         section->offset_within_region,
277                         int128_get64(end),
278                         iommu_idx);
279     iommu->iommu_offset = section->offset_within_address_space -
280                           section->offset_within_region;
281     iommu->dev_shared = s;
282 
283     ret = memory_region_register_iommu_notifier(section->mr, &iommu->n, NULL);
284     if (ret) {
285         g_free(iommu);
286         return;
287     }
288 
289     QLIST_INSERT_HEAD(&s->iommu_list, iommu, iommu_next);
290     memory_region_iommu_replay(iommu->iommu_mr, &iommu->n);
291 }
292 
293 static void vhost_vdpa_iommu_region_del(MemoryListener *listener,
294                                         MemoryRegionSection *section)
295 {
296     VhostVDPAShared *s = container_of(listener, VhostVDPAShared, listener);
297 
298     struct vdpa_iommu *iommu;
299 
300     QLIST_FOREACH(iommu, &s->iommu_list, iommu_next)
301     {
302         if (MEMORY_REGION(iommu->iommu_mr) == section->mr &&
303             iommu->n.start == section->offset_within_region) {
304             memory_region_unregister_iommu_notifier(section->mr, &iommu->n);
305             QLIST_REMOVE(iommu, iommu_next);
306             g_free(iommu);
307             break;
308         }
309     }
310 }
311 
312 static void vhost_vdpa_listener_region_add(MemoryListener *listener,
313                                            MemoryRegionSection *section)
314 {
315     DMAMap mem_region = {};
316     VhostVDPAShared *s = container_of(listener, VhostVDPAShared, listener);
317     hwaddr iova;
318     Int128 llend, llsize;
319     void *vaddr;
320     int ret;
321     int page_size = qemu_target_page_size();
322     int page_mask = -page_size;
323 
324     if (vhost_vdpa_listener_skipped_section(section, s->iova_range.first,
325                                             s->iova_range.last, page_mask)) {
326         return;
327     }
328     if (memory_region_is_iommu(section->mr)) {
329         vhost_vdpa_iommu_region_add(listener, section);
330         return;
331     }
332 
333     if (unlikely((section->offset_within_address_space & ~page_mask) !=
334                  (section->offset_within_region & ~page_mask))) {
335         trace_vhost_vdpa_listener_region_add_unaligned(s, section->mr->name,
336                        section->offset_within_address_space & ~page_mask,
337                        section->offset_within_region & ~page_mask);
338         return;
339     }
340 
341     iova = ROUND_UP(section->offset_within_address_space, page_size);
342     llend = vhost_vdpa_section_end(section, page_mask);
343     if (int128_ge(int128_make64(iova), llend)) {
344         return;
345     }
346 
347     memory_region_ref(section->mr);
348 
349     /* Here we assume that memory_region_is_ram(section->mr)==true */
350 
351     vaddr = memory_region_get_ram_ptr(section->mr) +
352             section->offset_within_region +
353             (iova - section->offset_within_address_space);
354 
355     trace_vhost_vdpa_listener_region_add(s, iova, int128_get64(llend),
356                                          vaddr, section->readonly);
357 
358     llsize = int128_sub(llend, int128_make64(iova));
359     if (s->shadow_data) {
360         int r;
361         hwaddr gpa = section->offset_within_address_space;
362 
363         mem_region.size = int128_get64(llsize) - 1,
364         mem_region.perm = IOMMU_ACCESS_FLAG(true, section->readonly),
365 
366         r = vhost_iova_tree_map_alloc_gpa(s->iova_tree, &mem_region, gpa);
367         if (unlikely(r != IOVA_OK)) {
368             error_report("Can't allocate a mapping (%d)", r);
369 
370             if (mem_region.translated_addr == gpa) {
371                 error_report("Insertion to GPA->IOVA tree failed");
372                 /* Remove the mapping from the IOVA-only tree */
373                 goto fail_map;
374             }
375             goto fail;
376         }
377 
378         iova = mem_region.iova;
379     }
380 
381     vhost_vdpa_iotlb_batch_begin_once(s);
382     ret = vhost_vdpa_dma_map(s, VHOST_VDPA_GUEST_PA_ASID, iova,
383                              int128_get64(llsize), vaddr, section->readonly);
384     if (ret) {
385         error_report("vhost vdpa map fail!");
386         goto fail_map;
387     }
388 
389     return;
390 
391 fail_map:
392     if (s->shadow_data) {
393         vhost_iova_tree_remove_gpa(s->iova_tree, mem_region);
394     }
395 
396 fail:
397     /*
398      * On the initfn path, store the first error in the container so we
399      * can gracefully fail.  Runtime, there's not much we can do other
400      * than throw a hardware error.
401      */
402     error_report("vhost-vdpa: DMA mapping failed, unable to continue");
403     return;
404 
405 }
406 
407 static void vhost_vdpa_listener_region_del(MemoryListener *listener,
408                                            MemoryRegionSection *section)
409 {
410     VhostVDPAShared *s = container_of(listener, VhostVDPAShared, listener);
411     hwaddr iova;
412     Int128 llend, llsize;
413     int ret;
414     int page_size = qemu_target_page_size();
415     int page_mask = -page_size;
416 
417     if (vhost_vdpa_listener_skipped_section(section, s->iova_range.first,
418                                             s->iova_range.last, page_mask)) {
419         return;
420     }
421     if (memory_region_is_iommu(section->mr)) {
422         vhost_vdpa_iommu_region_del(listener, section);
423     }
424 
425     if (unlikely((section->offset_within_address_space & ~page_mask) !=
426                  (section->offset_within_region & ~page_mask))) {
427         trace_vhost_vdpa_listener_region_del_unaligned(s, section->mr->name,
428                        section->offset_within_address_space & ~page_mask,
429                        section->offset_within_region & ~page_mask);
430         return;
431     }
432 
433     iova = ROUND_UP(section->offset_within_address_space, page_size);
434     llend = vhost_vdpa_section_end(section, page_mask);
435 
436     trace_vhost_vdpa_listener_region_del(s, iova,
437         int128_get64(int128_sub(llend, int128_one())));
438 
439     if (int128_ge(int128_make64(iova), llend)) {
440         return;
441     }
442 
443     llsize = int128_sub(llend, int128_make64(iova));
444 
445     if (s->shadow_data) {
446         const DMAMap *result;
447         DMAMap mem_region = {
448             .translated_addr = section->offset_within_address_space,
449             .size = int128_get64(llsize) - 1,
450         };
451 
452         result = vhost_iova_tree_find_gpa(s->iova_tree, &mem_region);
453         if (!result) {
454             /* The memory listener map wasn't mapped */
455             return;
456         }
457         iova = result->iova;
458         vhost_iova_tree_remove_gpa(s->iova_tree, *result);
459     }
460     vhost_vdpa_iotlb_batch_begin_once(s);
461     /*
462      * The unmap ioctl doesn't accept a full 64-bit. need to check it
463      */
464     if (int128_eq(llsize, int128_2_64())) {
465         llsize = int128_rshift(llsize, 1);
466         ret = vhost_vdpa_dma_unmap(s, VHOST_VDPA_GUEST_PA_ASID, iova,
467                                    int128_get64(llsize));
468 
469         if (ret) {
470             error_report("vhost_vdpa_dma_unmap(%p, 0x%" HWADDR_PRIx ", "
471                          "0x%" HWADDR_PRIx ") = %d (%m)",
472                          s, iova, int128_get64(llsize), ret);
473         }
474         iova += int128_get64(llsize);
475     }
476     ret = vhost_vdpa_dma_unmap(s, VHOST_VDPA_GUEST_PA_ASID, iova,
477                                int128_get64(llsize));
478 
479     if (ret) {
480         error_report("vhost_vdpa_dma_unmap(%p, 0x%" HWADDR_PRIx ", "
481                      "0x%" HWADDR_PRIx ") = %d (%m)",
482                      s, iova, int128_get64(llsize), ret);
483     }
484 
485     memory_region_unref(section->mr);
486 }
487 /*
488  * IOTLB API is used by vhost-vdpa which requires incremental updating
489  * of the mapping. So we can not use generic vhost memory listener which
490  * depends on the addnop().
491  */
492 static const MemoryListener vhost_vdpa_memory_listener = {
493     .name = "vhost-vdpa",
494     .commit = vhost_vdpa_listener_commit,
495     .region_add = vhost_vdpa_listener_region_add,
496     .region_del = vhost_vdpa_listener_region_del,
497 };
498 
499 static int vhost_vdpa_call(struct vhost_dev *dev, unsigned long int request,
500                              void *arg)
501 {
502     struct vhost_vdpa *v = dev->opaque;
503     int fd = v->shared->device_fd;
504     int ret;
505 
506     assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA);
507 
508     ret = ioctl(fd, request, arg);
509     return ret < 0 ? -errno : ret;
510 }
511 
512 static int vhost_vdpa_add_status(struct vhost_dev *dev, uint8_t status)
513 {
514     uint8_t s;
515     int ret;
516 
517     trace_vhost_vdpa_add_status(dev, status);
518     ret = vhost_vdpa_call(dev, VHOST_VDPA_GET_STATUS, &s);
519     if (ret < 0) {
520         return ret;
521     }
522     if ((s & status) == status) {
523         /* Don't set bits already set */
524         return 0;
525     }
526 
527     s |= status;
528 
529     ret = vhost_vdpa_call(dev, VHOST_VDPA_SET_STATUS, &s);
530     if (ret < 0) {
531         return ret;
532     }
533 
534     ret = vhost_vdpa_call(dev, VHOST_VDPA_GET_STATUS, &s);
535     if (ret < 0) {
536         return ret;
537     }
538 
539     if (!(s & status)) {
540         return -EIO;
541     }
542 
543     return 0;
544 }
545 
546 int vhost_vdpa_get_iova_range(int fd, struct vhost_vdpa_iova_range *iova_range)
547 {
548     int ret = ioctl(fd, VHOST_VDPA_GET_IOVA_RANGE, iova_range);
549 
550     return ret < 0 ? -errno : 0;
551 }
552 
553 /*
554  * The use of this function is for requests that only need to be
555  * applied once. Typically such request occurs at the beginning
556  * of operation, and before setting up queues. It should not be
557  * used for request that performs operation until all queues are
558  * set, which would need to check dev->vq_index_end instead.
559  */
560 static bool vhost_vdpa_first_dev(struct vhost_dev *dev)
561 {
562     struct vhost_vdpa *v = dev->opaque;
563 
564     return v->index == 0;
565 }
566 
567 static bool vhost_vdpa_last_dev(struct vhost_dev *dev)
568 {
569     return dev->vq_index + dev->nvqs == dev->vq_index_end;
570 }
571 
572 static int vhost_vdpa_get_dev_features(struct vhost_dev *dev,
573                                        uint64_t *features)
574 {
575     int ret;
576 
577     ret = vhost_vdpa_call(dev, VHOST_GET_FEATURES, features);
578     trace_vhost_vdpa_get_features(dev, *features);
579     return ret;
580 }
581 
582 static void vhost_vdpa_init_svq(struct vhost_dev *hdev, struct vhost_vdpa *v)
583 {
584     g_autoptr(GPtrArray) shadow_vqs = NULL;
585 
586     shadow_vqs = g_ptr_array_new_full(hdev->nvqs, vhost_svq_free);
587     for (unsigned n = 0; n < hdev->nvqs; ++n) {
588         VhostShadowVirtqueue *svq;
589 
590         svq = vhost_svq_new(v->shadow_vq_ops, v->shadow_vq_ops_opaque);
591         g_ptr_array_add(shadow_vqs, svq);
592     }
593 
594     v->shadow_vqs = g_steal_pointer(&shadow_vqs);
595 }
596 
597 static int vhost_vdpa_set_backend_cap(struct vhost_dev *dev)
598 {
599     struct vhost_vdpa *v = dev->opaque;
600 
601     uint64_t features;
602     uint64_t f = 0x1ULL << VHOST_BACKEND_F_IOTLB_MSG_V2 |
603         0x1ULL << VHOST_BACKEND_F_IOTLB_BATCH |
604         0x1ULL << VHOST_BACKEND_F_IOTLB_ASID |
605         0x1ULL << VHOST_BACKEND_F_SUSPEND;
606     int r;
607 
608     if (vhost_vdpa_call(dev, VHOST_GET_BACKEND_FEATURES, &features)) {
609         return -EFAULT;
610     }
611 
612     features &= f;
613 
614     if (vhost_vdpa_first_dev(dev)) {
615         r = vhost_vdpa_call(dev, VHOST_SET_BACKEND_FEATURES, &features);
616         if (r) {
617             return -EFAULT;
618         }
619     }
620 
621     dev->backend_cap = features;
622     v->shared->backend_cap = features;
623 
624     return 0;
625 }
626 
627 static int vhost_vdpa_init(struct vhost_dev *dev, void *opaque, Error **errp)
628 {
629     struct vhost_vdpa *v = opaque;
630     assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA);
631     trace_vhost_vdpa_init(dev, v->shared, opaque);
632     int ret;
633 
634     v->dev = dev;
635     dev->opaque =  opaque ;
636     v->shared->listener = vhost_vdpa_memory_listener;
637 
638     ret = vhost_vdpa_set_backend_cap(dev);
639     if (unlikely(ret != 0)) {
640         return ret;
641     }
642 
643     vhost_vdpa_init_svq(dev, v);
644 
645     error_propagate(&dev->migration_blocker, v->migration_blocker);
646     if (!vhost_vdpa_first_dev(dev)) {
647         return 0;
648     }
649 
650     /*
651      * If dev->shadow_vqs_enabled at initialization that means the device has
652      * been started with x-svq=on, so don't block migration
653      */
654     if (dev->migration_blocker == NULL && !v->shadow_vqs_enabled) {
655         /* We don't have dev->features yet */
656         uint64_t features;
657         ret = vhost_vdpa_get_dev_features(dev, &features);
658         if (unlikely(ret)) {
659             error_setg_errno(errp, -ret, "Could not get device features");
660             return ret;
661         }
662         vhost_svq_valid_features(features, &dev->migration_blocker);
663     }
664 
665     /*
666      * Similar to VFIO, we end up pinning all guest memory and have to
667      * disable discarding of RAM.
668      */
669     ret = ram_block_discard_disable(true);
670     if (ret) {
671         error_report("Cannot set discarding of RAM broken");
672         return ret;
673     }
674 
675     vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_ACKNOWLEDGE |
676                                VIRTIO_CONFIG_S_DRIVER);
677 
678     return 0;
679 }
680 
681 static void vhost_vdpa_host_notifier_uninit(struct vhost_dev *dev,
682                                             int queue_index)
683 {
684     size_t page_size = qemu_real_host_page_size();
685     struct vhost_vdpa *v = dev->opaque;
686     VirtIODevice *vdev = dev->vdev;
687     VhostVDPAHostNotifier *n;
688 
689     n = &v->notifier[queue_index];
690 
691     if (n->addr) {
692         virtio_queue_set_host_notifier_mr(vdev, queue_index, &n->mr, false);
693         object_unparent(OBJECT(&n->mr));
694         munmap(n->addr, page_size);
695         n->addr = NULL;
696     }
697 }
698 
699 static int vhost_vdpa_host_notifier_init(struct vhost_dev *dev, int queue_index)
700 {
701     size_t page_size = qemu_real_host_page_size();
702     struct vhost_vdpa *v = dev->opaque;
703     VirtIODevice *vdev = dev->vdev;
704     VhostVDPAHostNotifier *n;
705     int fd = v->shared->device_fd;
706     void *addr;
707     char *name;
708 
709     vhost_vdpa_host_notifier_uninit(dev, queue_index);
710 
711     n = &v->notifier[queue_index];
712 
713     addr = mmap(NULL, page_size, PROT_WRITE, MAP_SHARED, fd,
714                 queue_index * page_size);
715     if (addr == MAP_FAILED) {
716         goto err;
717     }
718 
719     name = g_strdup_printf("vhost-vdpa/host-notifier@%p mmaps[%d]",
720                            v, queue_index);
721     memory_region_init_ram_device_ptr(&n->mr, OBJECT(vdev), name,
722                                       page_size, addr);
723     g_free(name);
724 
725     if (virtio_queue_set_host_notifier_mr(vdev, queue_index, &n->mr, true)) {
726         object_unparent(OBJECT(&n->mr));
727         munmap(addr, page_size);
728         goto err;
729     }
730     n->addr = addr;
731 
732     return 0;
733 
734 err:
735     return -1;
736 }
737 
738 static void vhost_vdpa_host_notifiers_uninit(struct vhost_dev *dev, int n)
739 {
740     int i;
741 
742     /*
743      * Pack all the changes to the memory regions in a single
744      * transaction to avoid a few updating of the address space
745      * topology.
746      */
747     memory_region_transaction_begin();
748 
749     for (i = dev->vq_index; i < dev->vq_index + n; i++) {
750         vhost_vdpa_host_notifier_uninit(dev, i);
751     }
752 
753     memory_region_transaction_commit();
754 }
755 
756 static void vhost_vdpa_host_notifiers_init(struct vhost_dev *dev)
757 {
758     struct vhost_vdpa *v = dev->opaque;
759     int i;
760 
761     if (v->shadow_vqs_enabled) {
762         /* FIXME SVQ is not compatible with host notifiers mr */
763         return;
764     }
765 
766     /*
767      * Pack all the changes to the memory regions in a single
768      * transaction to avoid a few updating of the address space
769      * topology.
770      */
771     memory_region_transaction_begin();
772 
773     for (i = dev->vq_index; i < dev->vq_index + dev->nvqs; i++) {
774         if (vhost_vdpa_host_notifier_init(dev, i)) {
775             vhost_vdpa_host_notifiers_uninit(dev, i - dev->vq_index);
776             break;
777         }
778     }
779 
780     memory_region_transaction_commit();
781 }
782 
783 static void vhost_vdpa_svq_cleanup(struct vhost_dev *dev)
784 {
785     struct vhost_vdpa *v = dev->opaque;
786     size_t idx;
787 
788     for (idx = 0; idx < v->shadow_vqs->len; ++idx) {
789         vhost_svq_stop(g_ptr_array_index(v->shadow_vqs, idx));
790     }
791     g_ptr_array_free(v->shadow_vqs, true);
792 }
793 
794 static int vhost_vdpa_cleanup(struct vhost_dev *dev)
795 {
796     struct vhost_vdpa *v;
797     assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA);
798     v = dev->opaque;
799     trace_vhost_vdpa_cleanup(dev, v);
800     if (vhost_vdpa_first_dev(dev)) {
801         ram_block_discard_disable(false);
802         memory_listener_unregister(&v->shared->listener);
803     }
804 
805     vhost_vdpa_host_notifiers_uninit(dev, dev->nvqs);
806     vhost_vdpa_svq_cleanup(dev);
807 
808     dev->opaque = NULL;
809 
810     return 0;
811 }
812 
813 static int vhost_vdpa_memslots_limit(struct vhost_dev *dev)
814 {
815     trace_vhost_vdpa_memslots_limit(dev, INT_MAX);
816     return INT_MAX;
817 }
818 
819 static int vhost_vdpa_set_mem_table(struct vhost_dev *dev,
820                                     struct vhost_memory *mem)
821 {
822     if (!vhost_vdpa_first_dev(dev)) {
823         return 0;
824     }
825 
826     trace_vhost_vdpa_set_mem_table(dev, mem->nregions, mem->padding);
827     if (trace_event_get_state_backends(TRACE_VHOST_VDPA_SET_MEM_TABLE) &&
828         trace_event_get_state_backends(TRACE_VHOST_VDPA_DUMP_REGIONS)) {
829         int i;
830         for (i = 0; i < mem->nregions; i++) {
831             trace_vhost_vdpa_dump_regions(dev, i,
832                                           mem->regions[i].guest_phys_addr,
833                                           mem->regions[i].memory_size,
834                                           mem->regions[i].userspace_addr,
835                                           mem->regions[i].flags_padding);
836         }
837     }
838     if (mem->padding) {
839         return -EINVAL;
840     }
841 
842     return 0;
843 }
844 
845 static int vhost_vdpa_set_features(struct vhost_dev *dev,
846                                    uint64_t features)
847 {
848     struct vhost_vdpa *v = dev->opaque;
849     int ret;
850 
851     if (!vhost_vdpa_first_dev(dev)) {
852         return 0;
853     }
854 
855     if (v->shadow_vqs_enabled) {
856         if ((v->acked_features ^ features) == BIT_ULL(VHOST_F_LOG_ALL)) {
857             /*
858              * QEMU is just trying to enable or disable logging. SVQ handles
859              * this sepparately, so no need to forward this.
860              */
861             v->acked_features = features;
862             return 0;
863         }
864 
865         v->acked_features = features;
866 
867         /* We must not ack _F_LOG if SVQ is enabled */
868         features &= ~BIT_ULL(VHOST_F_LOG_ALL);
869     }
870 
871     trace_vhost_vdpa_set_features(dev, features);
872     ret = vhost_vdpa_call(dev, VHOST_SET_FEATURES, &features);
873     if (ret) {
874         return ret;
875     }
876 
877     return vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_FEATURES_OK);
878 }
879 
880 static int vhost_vdpa_get_device_id(struct vhost_dev *dev,
881                                     uint32_t *device_id)
882 {
883     int ret;
884     ret = vhost_vdpa_call(dev, VHOST_VDPA_GET_DEVICE_ID, device_id);
885     trace_vhost_vdpa_get_device_id(dev, *device_id);
886     return ret;
887 }
888 
889 static int vhost_vdpa_reset_device(struct vhost_dev *dev)
890 {
891     struct vhost_vdpa *v = dev->opaque;
892     int ret;
893     uint8_t status = 0;
894 
895     ret = vhost_vdpa_call(dev, VHOST_VDPA_SET_STATUS, &status);
896     trace_vhost_vdpa_reset_device(dev);
897     v->suspended = false;
898     return ret;
899 }
900 
901 static int vhost_vdpa_get_vq_index(struct vhost_dev *dev, int idx)
902 {
903     assert(idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs);
904 
905     trace_vhost_vdpa_get_vq_index(dev, idx, idx);
906     return idx;
907 }
908 
909 static int vhost_vdpa_set_vring_enable_one(struct vhost_vdpa *v, unsigned idx,
910                                            int enable)
911 {
912     struct vhost_dev *dev = v->dev;
913     struct vhost_vring_state state = {
914         .index = idx,
915         .num = enable,
916     };
917     int r = vhost_vdpa_call(dev, VHOST_VDPA_SET_VRING_ENABLE, &state);
918 
919     trace_vhost_vdpa_set_vring_enable_one(dev, idx, enable, r);
920     return r;
921 }
922 
923 static int vhost_vdpa_set_vring_enable(struct vhost_dev *dev, int enable)
924 {
925     struct vhost_vdpa *v = dev->opaque;
926     unsigned int i;
927     int ret;
928 
929     for (i = 0; i < dev->nvqs; ++i) {
930         ret = vhost_vdpa_set_vring_enable_one(v, i, enable);
931         if (ret < 0) {
932             return ret;
933         }
934     }
935 
936     return 0;
937 }
938 
939 int vhost_vdpa_set_vring_ready(struct vhost_vdpa *v, unsigned idx)
940 {
941     return vhost_vdpa_set_vring_enable_one(v, idx, 1);
942 }
943 
944 static int vhost_vdpa_set_config_call(struct vhost_dev *dev,
945                                        int fd)
946 {
947     trace_vhost_vdpa_set_config_call(dev, fd);
948     return vhost_vdpa_call(dev, VHOST_VDPA_SET_CONFIG_CALL, &fd);
949 }
950 
951 static void vhost_vdpa_dump_config(struct vhost_dev *dev, const uint8_t *config,
952                                    uint32_t config_len)
953 {
954     g_autoptr(GString) str = g_string_sized_new(4 * 16);
955     size_t b, len;
956 
957     for (b = 0; b < config_len; b += len) {
958         len = MIN(config_len - b, 16);
959 
960         g_string_truncate(str, 0);
961         qemu_hexdump_line(str, config + b, len, 1, 4);
962         trace_vhost_vdpa_dump_config(dev, b, str->str);
963     }
964 }
965 
966 static int vhost_vdpa_set_config(struct vhost_dev *dev, const uint8_t *data,
967                                    uint32_t offset, uint32_t size,
968                                    uint32_t flags)
969 {
970     struct vhost_vdpa_config *config;
971     int ret;
972     unsigned long config_size = offsetof(struct vhost_vdpa_config, buf);
973 
974     trace_vhost_vdpa_set_config(dev, offset, size, flags);
975     config = g_malloc(size + config_size);
976     config->off = offset;
977     config->len = size;
978     memcpy(config->buf, data, size);
979     if (trace_event_get_state_backends(TRACE_VHOST_VDPA_SET_CONFIG) &&
980         trace_event_get_state_backends(TRACE_VHOST_VDPA_DUMP_CONFIG)) {
981         vhost_vdpa_dump_config(dev, data, size);
982     }
983     ret = vhost_vdpa_call(dev, VHOST_VDPA_SET_CONFIG, config);
984     g_free(config);
985     return ret;
986 }
987 
988 static int vhost_vdpa_get_config(struct vhost_dev *dev, uint8_t *config,
989                                    uint32_t config_len, Error **errp)
990 {
991     struct vhost_vdpa_config *v_config;
992     unsigned long config_size = offsetof(struct vhost_vdpa_config, buf);
993     int ret;
994 
995     trace_vhost_vdpa_get_config(dev, config, config_len);
996     v_config = g_malloc(config_len + config_size);
997     v_config->len = config_len;
998     v_config->off = 0;
999     ret = vhost_vdpa_call(dev, VHOST_VDPA_GET_CONFIG, v_config);
1000     memcpy(config, v_config->buf, config_len);
1001     g_free(v_config);
1002     if (trace_event_get_state_backends(TRACE_VHOST_VDPA_GET_CONFIG) &&
1003         trace_event_get_state_backends(TRACE_VHOST_VDPA_DUMP_CONFIG)) {
1004         vhost_vdpa_dump_config(dev, config, config_len);
1005     }
1006     return ret;
1007  }
1008 
1009 static int vhost_vdpa_set_dev_vring_base(struct vhost_dev *dev,
1010                                          struct vhost_vring_state *ring)
1011 {
1012     struct vhost_vdpa *v = dev->opaque;
1013 
1014     trace_vhost_vdpa_set_dev_vring_base(dev, ring->index, ring->num,
1015                                         v->shadow_vqs_enabled);
1016     return vhost_vdpa_call(dev, VHOST_SET_VRING_BASE, ring);
1017 }
1018 
1019 static int vhost_vdpa_set_vring_dev_kick(struct vhost_dev *dev,
1020                                          struct vhost_vring_file *file)
1021 {
1022     trace_vhost_vdpa_set_vring_kick(dev, file->index, file->fd);
1023     return vhost_vdpa_call(dev, VHOST_SET_VRING_KICK, file);
1024 }
1025 
1026 static int vhost_vdpa_set_vring_dev_call(struct vhost_dev *dev,
1027                                          struct vhost_vring_file *file)
1028 {
1029     trace_vhost_vdpa_set_vring_call(dev, file->index, file->fd);
1030     return vhost_vdpa_call(dev, VHOST_SET_VRING_CALL, file);
1031 }
1032 
1033 static int vhost_vdpa_set_vring_dev_addr(struct vhost_dev *dev,
1034                                          struct vhost_vring_addr *addr)
1035 {
1036     trace_vhost_vdpa_set_vring_addr(dev, addr->index, addr->flags,
1037                                 addr->desc_user_addr, addr->used_user_addr,
1038                                 addr->avail_user_addr,
1039                                 addr->log_guest_addr);
1040 
1041     return vhost_vdpa_call(dev, VHOST_SET_VRING_ADDR, addr);
1042 
1043 }
1044 
1045 /**
1046  * Set the shadow virtqueue descriptors to the device
1047  *
1048  * @dev: The vhost device model
1049  * @svq: The shadow virtqueue
1050  * @idx: The index of the virtqueue in the vhost device
1051  * @errp: Error
1052  *
1053  * Note that this function does not rewind kick file descriptor if cannot set
1054  * call one.
1055  */
1056 static int vhost_vdpa_svq_set_fds(struct vhost_dev *dev,
1057                                   VhostShadowVirtqueue *svq, unsigned idx,
1058                                   Error **errp)
1059 {
1060     struct vhost_vring_file file = {
1061         .index = dev->vq_index + idx,
1062     };
1063     const EventNotifier *event_notifier = &svq->hdev_kick;
1064     int r;
1065 
1066     r = event_notifier_init(&svq->hdev_kick, 0);
1067     if (r != 0) {
1068         error_setg_errno(errp, -r, "Couldn't create kick event notifier");
1069         goto err_init_hdev_kick;
1070     }
1071 
1072     r = event_notifier_init(&svq->hdev_call, 0);
1073     if (r != 0) {
1074         error_setg_errno(errp, -r, "Couldn't create call event notifier");
1075         goto err_init_hdev_call;
1076     }
1077 
1078     file.fd = event_notifier_get_fd(event_notifier);
1079     r = vhost_vdpa_set_vring_dev_kick(dev, &file);
1080     if (unlikely(r != 0)) {
1081         error_setg_errno(errp, -r, "Can't set device kick fd");
1082         goto err_init_set_dev_fd;
1083     }
1084 
1085     event_notifier = &svq->hdev_call;
1086     file.fd = event_notifier_get_fd(event_notifier);
1087     r = vhost_vdpa_set_vring_dev_call(dev, &file);
1088     if (unlikely(r != 0)) {
1089         error_setg_errno(errp, -r, "Can't set device call fd");
1090         goto err_init_set_dev_fd;
1091     }
1092 
1093     return 0;
1094 
1095 err_init_set_dev_fd:
1096     event_notifier_set_handler(&svq->hdev_call, NULL);
1097 
1098 err_init_hdev_call:
1099     event_notifier_cleanup(&svq->hdev_kick);
1100 
1101 err_init_hdev_kick:
1102     return r;
1103 }
1104 
1105 /**
1106  * Unmap a SVQ area in the device
1107  */
1108 static void vhost_vdpa_svq_unmap_ring(struct vhost_vdpa *v, hwaddr addr)
1109 {
1110     const DMAMap needle = {
1111         .translated_addr = addr,
1112     };
1113     const DMAMap *result = vhost_iova_tree_find_iova(v->shared->iova_tree,
1114                                                      &needle);
1115     hwaddr size;
1116     int r;
1117 
1118     if (unlikely(!result)) {
1119         error_report("Unable to find SVQ address to unmap");
1120         return;
1121     }
1122 
1123     size = ROUND_UP(result->size, qemu_real_host_page_size());
1124     r = vhost_vdpa_dma_unmap(v->shared, v->address_space_id, result->iova,
1125                              size);
1126     if (unlikely(r < 0)) {
1127         error_report("Unable to unmap SVQ vring: %s (%d)", g_strerror(-r), -r);
1128         return;
1129     }
1130 
1131     vhost_iova_tree_remove(v->shared->iova_tree, *result);
1132 }
1133 
1134 static void vhost_vdpa_svq_unmap_rings(struct vhost_dev *dev,
1135                                        const VhostShadowVirtqueue *svq)
1136 {
1137     struct vhost_vdpa *v = dev->opaque;
1138     struct vhost_vring_addr svq_addr;
1139 
1140     vhost_svq_get_vring_addr(svq, &svq_addr);
1141 
1142     vhost_vdpa_svq_unmap_ring(v, svq_addr.desc_user_addr);
1143 
1144     vhost_vdpa_svq_unmap_ring(v, svq_addr.used_user_addr);
1145 }
1146 
1147 /**
1148  * Map the SVQ area in the device
1149  *
1150  * @v: Vhost-vdpa device
1151  * @needle: The area to search iova
1152  * @taddr: The translated address (HVA)
1153  * @errorp: Error pointer
1154  */
1155 static bool vhost_vdpa_svq_map_ring(struct vhost_vdpa *v, DMAMap *needle,
1156                                     hwaddr taddr, Error **errp)
1157 {
1158     int r;
1159 
1160     r = vhost_iova_tree_map_alloc(v->shared->iova_tree, needle, taddr);
1161     if (unlikely(r != IOVA_OK)) {
1162         error_setg(errp, "Cannot allocate iova (%d)", r);
1163 
1164         if (needle->translated_addr == taddr) {
1165             error_append_hint(errp, "Insertion to IOVA->HVA tree failed");
1166             /* Remove the mapping from the IOVA-only tree */
1167             vhost_iova_tree_remove(v->shared->iova_tree, *needle);
1168         }
1169         return false;
1170     }
1171 
1172     r = vhost_vdpa_dma_map(v->shared, v->address_space_id, needle->iova,
1173                            needle->size + 1,
1174                            (void *)(uintptr_t)needle->translated_addr,
1175                            needle->perm == IOMMU_RO);
1176     if (unlikely(r != 0)) {
1177         error_setg_errno(errp, -r, "Cannot map region to device");
1178         vhost_iova_tree_remove(v->shared->iova_tree, *needle);
1179     }
1180 
1181     return r == 0;
1182 }
1183 
1184 /**
1185  * Map the shadow virtqueue rings in the device
1186  *
1187  * @dev: The vhost device
1188  * @svq: The shadow virtqueue
1189  * @addr: Assigned IOVA addresses
1190  * @errp: Error pointer
1191  */
1192 static bool vhost_vdpa_svq_map_rings(struct vhost_dev *dev,
1193                                      const VhostShadowVirtqueue *svq,
1194                                      struct vhost_vring_addr *addr,
1195                                      Error **errp)
1196 {
1197     ERRP_GUARD();
1198     DMAMap device_region, driver_region;
1199     struct vhost_vring_addr svq_addr;
1200     struct vhost_vdpa *v = dev->opaque;
1201     size_t device_size = vhost_svq_device_area_size(svq);
1202     size_t driver_size = vhost_svq_driver_area_size(svq);
1203     size_t avail_offset;
1204     bool ok;
1205 
1206     vhost_svq_get_vring_addr(svq, &svq_addr);
1207 
1208     driver_region = (DMAMap) {
1209         .size = driver_size - 1,
1210         .perm = IOMMU_RO,
1211     };
1212     ok = vhost_vdpa_svq_map_ring(v, &driver_region, svq_addr.desc_user_addr,
1213                                  errp);
1214     if (unlikely(!ok)) {
1215         error_prepend(errp, "Cannot create vq driver region: ");
1216         return false;
1217     }
1218     addr->desc_user_addr = driver_region.iova;
1219     avail_offset = svq_addr.avail_user_addr - svq_addr.desc_user_addr;
1220     addr->avail_user_addr = driver_region.iova + avail_offset;
1221 
1222     device_region = (DMAMap) {
1223         .size = device_size - 1,
1224         .perm = IOMMU_RW,
1225     };
1226     ok = vhost_vdpa_svq_map_ring(v, &device_region, svq_addr.used_user_addr,
1227                                  errp);
1228     if (unlikely(!ok)) {
1229         error_prepend(errp, "Cannot create vq device region: ");
1230         vhost_vdpa_svq_unmap_ring(v, driver_region.translated_addr);
1231     }
1232     addr->used_user_addr = device_region.iova;
1233 
1234     return ok;
1235 }
1236 
1237 static bool vhost_vdpa_svq_setup(struct vhost_dev *dev,
1238                                  VhostShadowVirtqueue *svq, unsigned idx,
1239                                  Error **errp)
1240 {
1241     uint16_t vq_index = dev->vq_index + idx;
1242     struct vhost_vring_state s = {
1243         .index = vq_index,
1244     };
1245     int r;
1246 
1247     r = vhost_vdpa_set_dev_vring_base(dev, &s);
1248     if (unlikely(r)) {
1249         error_setg_errno(errp, -r, "Cannot set vring base");
1250         return false;
1251     }
1252 
1253     r = vhost_vdpa_svq_set_fds(dev, svq, idx, errp);
1254     return r == 0;
1255 }
1256 
1257 static bool vhost_vdpa_svqs_start(struct vhost_dev *dev)
1258 {
1259     struct vhost_vdpa *v = dev->opaque;
1260     Error *err = NULL;
1261     unsigned i;
1262 
1263     if (!v->shadow_vqs_enabled) {
1264         return true;
1265     }
1266 
1267     for (i = 0; i < v->shadow_vqs->len; ++i) {
1268         VirtQueue *vq = virtio_get_queue(dev->vdev, dev->vq_index + i);
1269         VhostShadowVirtqueue *svq = g_ptr_array_index(v->shadow_vqs, i);
1270         struct vhost_vring_addr addr = {
1271             .index = dev->vq_index + i,
1272         };
1273         int r;
1274         bool ok = vhost_vdpa_svq_setup(dev, svq, i, &err);
1275         if (unlikely(!ok)) {
1276             goto err;
1277         }
1278 
1279         vhost_svq_start(svq, dev->vdev, vq, v->shared->iova_tree);
1280         ok = vhost_vdpa_svq_map_rings(dev, svq, &addr, &err);
1281         if (unlikely(!ok)) {
1282             goto err_map;
1283         }
1284 
1285         /* Override vring GPA set by vhost subsystem */
1286         r = vhost_vdpa_set_vring_dev_addr(dev, &addr);
1287         if (unlikely(r != 0)) {
1288             error_setg_errno(&err, -r, "Cannot set device address");
1289             goto err_set_addr;
1290         }
1291     }
1292 
1293     return true;
1294 
1295 err_set_addr:
1296     vhost_vdpa_svq_unmap_rings(dev, g_ptr_array_index(v->shadow_vqs, i));
1297 
1298 err_map:
1299     vhost_svq_stop(g_ptr_array_index(v->shadow_vqs, i));
1300 
1301 err:
1302     error_reportf_err(err, "Cannot setup SVQ %u: ", i);
1303     for (unsigned j = 0; j < i; ++j) {
1304         VhostShadowVirtqueue *svq = g_ptr_array_index(v->shadow_vqs, j);
1305         vhost_vdpa_svq_unmap_rings(dev, svq);
1306         vhost_svq_stop(svq);
1307     }
1308 
1309     return false;
1310 }
1311 
1312 static void vhost_vdpa_svqs_stop(struct vhost_dev *dev)
1313 {
1314     struct vhost_vdpa *v = dev->opaque;
1315 
1316     if (!v->shadow_vqs_enabled) {
1317         return;
1318     }
1319 
1320     for (unsigned i = 0; i < v->shadow_vqs->len; ++i) {
1321         VhostShadowVirtqueue *svq = g_ptr_array_index(v->shadow_vqs, i);
1322 
1323         vhost_svq_stop(svq);
1324         vhost_vdpa_svq_unmap_rings(dev, svq);
1325 
1326         event_notifier_cleanup(&svq->hdev_kick);
1327         event_notifier_cleanup(&svq->hdev_call);
1328     }
1329 }
1330 
1331 static void vhost_vdpa_suspend(struct vhost_dev *dev)
1332 {
1333     struct vhost_vdpa *v = dev->opaque;
1334     int r;
1335 
1336     if (!vhost_vdpa_first_dev(dev)) {
1337         return;
1338     }
1339 
1340     if (dev->backend_cap & BIT_ULL(VHOST_BACKEND_F_SUSPEND)) {
1341         trace_vhost_vdpa_suspend(dev);
1342         r = ioctl(v->shared->device_fd, VHOST_VDPA_SUSPEND);
1343         if (unlikely(r)) {
1344             error_report("Cannot suspend: %s(%d)", g_strerror(errno), errno);
1345         } else {
1346             v->suspended = true;
1347             return;
1348         }
1349     }
1350 
1351     vhost_vdpa_reset_device(dev);
1352 }
1353 
1354 static int vhost_vdpa_dev_start(struct vhost_dev *dev, bool started)
1355 {
1356     struct vhost_vdpa *v = dev->opaque;
1357     bool ok;
1358     trace_vhost_vdpa_dev_start(dev, started);
1359 
1360     if (started) {
1361         vhost_vdpa_host_notifiers_init(dev);
1362         ok = vhost_vdpa_svqs_start(dev);
1363         if (unlikely(!ok)) {
1364             return -1;
1365         }
1366     } else {
1367         vhost_vdpa_suspend(dev);
1368         vhost_vdpa_svqs_stop(dev);
1369         vhost_vdpa_host_notifiers_uninit(dev, dev->nvqs);
1370     }
1371 
1372     if (!vhost_vdpa_last_dev(dev)) {
1373         return 0;
1374     }
1375 
1376     if (started) {
1377         if (vhost_dev_has_iommu(dev) && (v->shadow_vqs_enabled)) {
1378             error_report("SVQ can not work while IOMMU enable, please disable"
1379                          "IOMMU and try again");
1380             return -1;
1381         }
1382         memory_listener_register(&v->shared->listener, dev->vdev->dma_as);
1383 
1384         return vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_DRIVER_OK);
1385     }
1386 
1387     return 0;
1388 }
1389 
1390 static void vhost_vdpa_reset_status(struct vhost_dev *dev)
1391 {
1392     struct vhost_vdpa *v = dev->opaque;
1393 
1394     if (!vhost_vdpa_last_dev(dev)) {
1395         return;
1396     }
1397 
1398     vhost_vdpa_reset_device(dev);
1399     vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_ACKNOWLEDGE |
1400                                VIRTIO_CONFIG_S_DRIVER);
1401     memory_listener_unregister(&v->shared->listener);
1402 }
1403 
1404 static int vhost_vdpa_set_log_base(struct vhost_dev *dev, uint64_t base,
1405                                      struct vhost_log *log)
1406 {
1407     struct vhost_vdpa *v = dev->opaque;
1408     if (v->shadow_vqs_enabled || !vhost_vdpa_first_dev(dev)) {
1409         return 0;
1410     }
1411 
1412     trace_vhost_vdpa_set_log_base(dev, base, log->size, log->refcnt, log->fd,
1413                                   log->log);
1414     return vhost_vdpa_call(dev, VHOST_SET_LOG_BASE, &base);
1415 }
1416 
1417 static int vhost_vdpa_set_vring_addr(struct vhost_dev *dev,
1418                                        struct vhost_vring_addr *addr)
1419 {
1420     struct vhost_vdpa *v = dev->opaque;
1421 
1422     if (v->shadow_vqs_enabled) {
1423         /*
1424          * Device vring addr was set at device start. SVQ base is handled by
1425          * VirtQueue code.
1426          */
1427         return 0;
1428     }
1429 
1430     return vhost_vdpa_set_vring_dev_addr(dev, addr);
1431 }
1432 
1433 static int vhost_vdpa_set_vring_num(struct vhost_dev *dev,
1434                                       struct vhost_vring_state *ring)
1435 {
1436     trace_vhost_vdpa_set_vring_num(dev, ring->index, ring->num);
1437     return vhost_vdpa_call(dev, VHOST_SET_VRING_NUM, ring);
1438 }
1439 
1440 static int vhost_vdpa_set_vring_base(struct vhost_dev *dev,
1441                                        struct vhost_vring_state *ring)
1442 {
1443     struct vhost_vdpa *v = dev->opaque;
1444 
1445     if (v->shadow_vqs_enabled) {
1446         /*
1447          * Device vring base was set at device start. SVQ base is handled by
1448          * VirtQueue code.
1449          */
1450         return 0;
1451     }
1452 
1453     return vhost_vdpa_set_dev_vring_base(dev, ring);
1454 }
1455 
1456 static int vhost_vdpa_get_vring_base(struct vhost_dev *dev,
1457                                        struct vhost_vring_state *ring)
1458 {
1459     struct vhost_vdpa *v = dev->opaque;
1460     int ret;
1461 
1462     if (v->shadow_vqs_enabled) {
1463         ring->num = virtio_queue_get_last_avail_idx(dev->vdev, ring->index);
1464         trace_vhost_vdpa_get_vring_base(dev, ring->index, ring->num, true);
1465         return 0;
1466     }
1467 
1468     if (!v->suspended) {
1469         /*
1470          * Cannot trust in value returned by device, let vhost recover used
1471          * idx from guest.
1472          */
1473         return -1;
1474     }
1475 
1476     ret = vhost_vdpa_call(dev, VHOST_GET_VRING_BASE, ring);
1477     trace_vhost_vdpa_get_vring_base(dev, ring->index, ring->num, false);
1478     return ret;
1479 }
1480 
1481 static int vhost_vdpa_set_vring_kick(struct vhost_dev *dev,
1482                                        struct vhost_vring_file *file)
1483 {
1484     struct vhost_vdpa *v = dev->opaque;
1485     int vdpa_idx = file->index - dev->vq_index;
1486 
1487     if (v->shadow_vqs_enabled) {
1488         VhostShadowVirtqueue *svq = g_ptr_array_index(v->shadow_vqs, vdpa_idx);
1489         vhost_svq_set_svq_kick_fd(svq, file->fd);
1490         return 0;
1491     } else {
1492         return vhost_vdpa_set_vring_dev_kick(dev, file);
1493     }
1494 }
1495 
1496 static int vhost_vdpa_set_vring_call(struct vhost_dev *dev,
1497                                        struct vhost_vring_file *file)
1498 {
1499     struct vhost_vdpa *v = dev->opaque;
1500     int vdpa_idx = file->index - dev->vq_index;
1501     VhostShadowVirtqueue *svq = g_ptr_array_index(v->shadow_vqs, vdpa_idx);
1502 
1503     /* Remember last call fd because we can switch to SVQ anytime. */
1504     vhost_svq_set_svq_call_fd(svq, file->fd);
1505     /*
1506      * When SVQ is transitioning to off, shadow_vqs_enabled has
1507      * not been set back to false yet, but the underlying call fd
1508      * will have to switch back to the guest notifier to signal the
1509      * passthrough virtqueues. In other situations, SVQ's own call
1510      * fd shall be used to signal the device model.
1511      */
1512     if (v->shadow_vqs_enabled &&
1513         v->shared->svq_switching != SVQ_TSTATE_DISABLING) {
1514         return 0;
1515     }
1516 
1517     return vhost_vdpa_set_vring_dev_call(dev, file);
1518 }
1519 
1520 static int vhost_vdpa_get_features(struct vhost_dev *dev,
1521                                      uint64_t *features)
1522 {
1523     int ret = vhost_vdpa_get_dev_features(dev, features);
1524 
1525     if (ret == 0) {
1526         /* Add SVQ logging capabilities */
1527         *features |= BIT_ULL(VHOST_F_LOG_ALL);
1528     }
1529 
1530     return ret;
1531 }
1532 
1533 static int vhost_vdpa_set_owner(struct vhost_dev *dev)
1534 {
1535     if (!vhost_vdpa_first_dev(dev)) {
1536         return 0;
1537     }
1538 
1539     trace_vhost_vdpa_set_owner(dev);
1540     return vhost_vdpa_call(dev, VHOST_SET_OWNER, NULL);
1541 }
1542 
1543 static int vhost_vdpa_vq_get_addr(struct vhost_dev *dev,
1544                     struct vhost_vring_addr *addr, struct vhost_virtqueue *vq)
1545 {
1546     assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA);
1547     addr->desc_user_addr = (uint64_t)(unsigned long)vq->desc_phys;
1548     addr->avail_user_addr = (uint64_t)(unsigned long)vq->avail_phys;
1549     addr->used_user_addr = (uint64_t)(unsigned long)vq->used_phys;
1550     trace_vhost_vdpa_vq_get_addr(dev, vq, addr->desc_user_addr,
1551                                  addr->avail_user_addr, addr->used_user_addr);
1552     return 0;
1553 }
1554 
1555 static bool  vhost_vdpa_force_iommu(struct vhost_dev *dev)
1556 {
1557     return true;
1558 }
1559 
1560 const VhostOps vdpa_ops = {
1561         .backend_type = VHOST_BACKEND_TYPE_VDPA,
1562         .vhost_backend_init = vhost_vdpa_init,
1563         .vhost_backend_cleanup = vhost_vdpa_cleanup,
1564         .vhost_set_log_base = vhost_vdpa_set_log_base,
1565         .vhost_set_vring_addr = vhost_vdpa_set_vring_addr,
1566         .vhost_set_vring_num = vhost_vdpa_set_vring_num,
1567         .vhost_set_vring_base = vhost_vdpa_set_vring_base,
1568         .vhost_get_vring_base = vhost_vdpa_get_vring_base,
1569         .vhost_set_vring_kick = vhost_vdpa_set_vring_kick,
1570         .vhost_set_vring_call = vhost_vdpa_set_vring_call,
1571         .vhost_get_features = vhost_vdpa_get_features,
1572         .vhost_set_owner = vhost_vdpa_set_owner,
1573         .vhost_set_vring_endian = NULL,
1574         .vhost_backend_memslots_limit = vhost_vdpa_memslots_limit,
1575         .vhost_set_mem_table = vhost_vdpa_set_mem_table,
1576         .vhost_set_features = vhost_vdpa_set_features,
1577         .vhost_reset_device = vhost_vdpa_reset_device,
1578         .vhost_get_vq_index = vhost_vdpa_get_vq_index,
1579         .vhost_set_vring_enable = vhost_vdpa_set_vring_enable,
1580         .vhost_get_config  = vhost_vdpa_get_config,
1581         .vhost_set_config = vhost_vdpa_set_config,
1582         .vhost_requires_shm_log = NULL,
1583         .vhost_migration_done = NULL,
1584         .vhost_net_set_mtu = NULL,
1585         .vhost_set_iotlb_callback = NULL,
1586         .vhost_send_device_iotlb_msg = NULL,
1587         .vhost_dev_start = vhost_vdpa_dev_start,
1588         .vhost_get_device_id = vhost_vdpa_get_device_id,
1589         .vhost_vq_get_addr = vhost_vdpa_vq_get_addr,
1590         .vhost_force_iommu = vhost_vdpa_force_iommu,
1591         .vhost_set_config_call = vhost_vdpa_set_config_call,
1592         .vhost_reset_status = vhost_vdpa_reset_status,
1593 };
1594