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