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