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