xref: /qemu/hw/virtio/vhost-vdpa.c (revision d884e272)
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     struct vhost_vdpa *v = dev->opaque;
974 
975     trace_vhost_vdpa_set_dev_vring_base(dev, ring->index, ring->num,
976                                         v->shadow_vqs_enabled);
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->shared, v->address_space_id, result->iova,
1086                              size);
1087     if (unlikely(r < 0)) {
1088         error_report("Unable to unmap SVQ vring: %s (%d)", g_strerror(-r), -r);
1089         return;
1090     }
1091 
1092     vhost_iova_tree_remove(v->shared->iova_tree, *result);
1093 }
1094 
1095 static void vhost_vdpa_svq_unmap_rings(struct vhost_dev *dev,
1096                                        const VhostShadowVirtqueue *svq)
1097 {
1098     struct vhost_vdpa *v = dev->opaque;
1099     struct vhost_vring_addr svq_addr;
1100 
1101     vhost_svq_get_vring_addr(svq, &svq_addr);
1102 
1103     vhost_vdpa_svq_unmap_ring(v, svq_addr.desc_user_addr);
1104 
1105     vhost_vdpa_svq_unmap_ring(v, svq_addr.used_user_addr);
1106 }
1107 
1108 /**
1109  * Map the SVQ area in the device
1110  *
1111  * @v: Vhost-vdpa device
1112  * @needle: The area to search iova
1113  * @errorp: Error pointer
1114  */
1115 static bool vhost_vdpa_svq_map_ring(struct vhost_vdpa *v, DMAMap *needle,
1116                                     Error **errp)
1117 {
1118     int r;
1119 
1120     r = vhost_iova_tree_map_alloc(v->shared->iova_tree, needle);
1121     if (unlikely(r != IOVA_OK)) {
1122         error_setg(errp, "Cannot allocate iova (%d)", r);
1123         return false;
1124     }
1125 
1126     r = vhost_vdpa_dma_map(v->shared, v->address_space_id, needle->iova,
1127                            needle->size + 1,
1128                            (void *)(uintptr_t)needle->translated_addr,
1129                            needle->perm == IOMMU_RO);
1130     if (unlikely(r != 0)) {
1131         error_setg_errno(errp, -r, "Cannot map region to device");
1132         vhost_iova_tree_remove(v->shared->iova_tree, *needle);
1133     }
1134 
1135     return r == 0;
1136 }
1137 
1138 /**
1139  * Map the shadow virtqueue rings in the device
1140  *
1141  * @dev: The vhost device
1142  * @svq: The shadow virtqueue
1143  * @addr: Assigned IOVA addresses
1144  * @errp: Error pointer
1145  */
1146 static bool vhost_vdpa_svq_map_rings(struct vhost_dev *dev,
1147                                      const VhostShadowVirtqueue *svq,
1148                                      struct vhost_vring_addr *addr,
1149                                      Error **errp)
1150 {
1151     ERRP_GUARD();
1152     DMAMap device_region, driver_region;
1153     struct vhost_vring_addr svq_addr;
1154     struct vhost_vdpa *v = dev->opaque;
1155     size_t device_size = vhost_svq_device_area_size(svq);
1156     size_t driver_size = vhost_svq_driver_area_size(svq);
1157     size_t avail_offset;
1158     bool ok;
1159 
1160     vhost_svq_get_vring_addr(svq, &svq_addr);
1161 
1162     driver_region = (DMAMap) {
1163         .translated_addr = svq_addr.desc_user_addr,
1164         .size = driver_size - 1,
1165         .perm = IOMMU_RO,
1166     };
1167     ok = vhost_vdpa_svq_map_ring(v, &driver_region, errp);
1168     if (unlikely(!ok)) {
1169         error_prepend(errp, "Cannot create vq driver region: ");
1170         return false;
1171     }
1172     addr->desc_user_addr = driver_region.iova;
1173     avail_offset = svq_addr.avail_user_addr - svq_addr.desc_user_addr;
1174     addr->avail_user_addr = driver_region.iova + avail_offset;
1175 
1176     device_region = (DMAMap) {
1177         .translated_addr = svq_addr.used_user_addr,
1178         .size = device_size - 1,
1179         .perm = IOMMU_RW,
1180     };
1181     ok = vhost_vdpa_svq_map_ring(v, &device_region, errp);
1182     if (unlikely(!ok)) {
1183         error_prepend(errp, "Cannot create vq device region: ");
1184         vhost_vdpa_svq_unmap_ring(v, driver_region.translated_addr);
1185     }
1186     addr->used_user_addr = device_region.iova;
1187 
1188     return ok;
1189 }
1190 
1191 static bool vhost_vdpa_svq_setup(struct vhost_dev *dev,
1192                                  VhostShadowVirtqueue *svq, unsigned idx,
1193                                  Error **errp)
1194 {
1195     uint16_t vq_index = dev->vq_index + idx;
1196     struct vhost_vring_state s = {
1197         .index = vq_index,
1198     };
1199     int r;
1200 
1201     r = vhost_vdpa_set_dev_vring_base(dev, &s);
1202     if (unlikely(r)) {
1203         error_setg_errno(errp, -r, "Cannot set vring base");
1204         return false;
1205     }
1206 
1207     r = vhost_vdpa_svq_set_fds(dev, svq, idx, errp);
1208     return r == 0;
1209 }
1210 
1211 static bool vhost_vdpa_svqs_start(struct vhost_dev *dev)
1212 {
1213     struct vhost_vdpa *v = dev->opaque;
1214     Error *err = NULL;
1215     unsigned i;
1216 
1217     if (!v->shadow_vqs_enabled) {
1218         return true;
1219     }
1220 
1221     for (i = 0; i < v->shadow_vqs->len; ++i) {
1222         VirtQueue *vq = virtio_get_queue(dev->vdev, dev->vq_index + i);
1223         VhostShadowVirtqueue *svq = g_ptr_array_index(v->shadow_vqs, i);
1224         struct vhost_vring_addr addr = {
1225             .index = dev->vq_index + i,
1226         };
1227         int r;
1228         bool ok = vhost_vdpa_svq_setup(dev, svq, i, &err);
1229         if (unlikely(!ok)) {
1230             goto err;
1231         }
1232 
1233         vhost_svq_start(svq, dev->vdev, vq, v->shared->iova_tree);
1234         ok = vhost_vdpa_svq_map_rings(dev, svq, &addr, &err);
1235         if (unlikely(!ok)) {
1236             goto err_map;
1237         }
1238 
1239         /* Override vring GPA set by vhost subsystem */
1240         r = vhost_vdpa_set_vring_dev_addr(dev, &addr);
1241         if (unlikely(r != 0)) {
1242             error_setg_errno(&err, -r, "Cannot set device address");
1243             goto err_set_addr;
1244         }
1245     }
1246 
1247     return true;
1248 
1249 err_set_addr:
1250     vhost_vdpa_svq_unmap_rings(dev, g_ptr_array_index(v->shadow_vqs, i));
1251 
1252 err_map:
1253     vhost_svq_stop(g_ptr_array_index(v->shadow_vqs, i));
1254 
1255 err:
1256     error_reportf_err(err, "Cannot setup SVQ %u: ", i);
1257     for (unsigned j = 0; j < i; ++j) {
1258         VhostShadowVirtqueue *svq = g_ptr_array_index(v->shadow_vqs, j);
1259         vhost_vdpa_svq_unmap_rings(dev, svq);
1260         vhost_svq_stop(svq);
1261     }
1262 
1263     return false;
1264 }
1265 
1266 static void vhost_vdpa_svqs_stop(struct vhost_dev *dev)
1267 {
1268     struct vhost_vdpa *v = dev->opaque;
1269 
1270     if (!v->shadow_vqs_enabled) {
1271         return;
1272     }
1273 
1274     for (unsigned i = 0; i < v->shadow_vqs->len; ++i) {
1275         VhostShadowVirtqueue *svq = g_ptr_array_index(v->shadow_vqs, i);
1276 
1277         vhost_svq_stop(svq);
1278         vhost_vdpa_svq_unmap_rings(dev, svq);
1279 
1280         event_notifier_cleanup(&svq->hdev_kick);
1281         event_notifier_cleanup(&svq->hdev_call);
1282     }
1283 }
1284 
1285 static void vhost_vdpa_suspend(struct vhost_dev *dev)
1286 {
1287     struct vhost_vdpa *v = dev->opaque;
1288     int r;
1289 
1290     if (!vhost_vdpa_first_dev(dev)) {
1291         return;
1292     }
1293 
1294     if (dev->backend_cap & BIT_ULL(VHOST_BACKEND_F_SUSPEND)) {
1295         trace_vhost_vdpa_suspend(dev);
1296         r = ioctl(v->shared->device_fd, VHOST_VDPA_SUSPEND);
1297         if (unlikely(r)) {
1298             error_report("Cannot suspend: %s(%d)", g_strerror(errno), errno);
1299         } else {
1300             v->suspended = true;
1301             return;
1302         }
1303     }
1304 
1305     vhost_vdpa_reset_device(dev);
1306 }
1307 
1308 static int vhost_vdpa_dev_start(struct vhost_dev *dev, bool started)
1309 {
1310     struct vhost_vdpa *v = dev->opaque;
1311     bool ok;
1312     trace_vhost_vdpa_dev_start(dev, started);
1313 
1314     if (started) {
1315         vhost_vdpa_host_notifiers_init(dev);
1316         ok = vhost_vdpa_svqs_start(dev);
1317         if (unlikely(!ok)) {
1318             return -1;
1319         }
1320     } else {
1321         vhost_vdpa_suspend(dev);
1322         vhost_vdpa_svqs_stop(dev);
1323         vhost_vdpa_host_notifiers_uninit(dev, dev->nvqs);
1324     }
1325 
1326     if (!vhost_vdpa_last_dev(dev)) {
1327         return 0;
1328     }
1329 
1330     if (started) {
1331         if (vhost_dev_has_iommu(dev) && (v->shadow_vqs_enabled)) {
1332             error_report("SVQ can not work while IOMMU enable, please disable"
1333                          "IOMMU and try again");
1334             return -1;
1335         }
1336         memory_listener_register(&v->shared->listener, dev->vdev->dma_as);
1337 
1338         return vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_DRIVER_OK);
1339     }
1340 
1341     return 0;
1342 }
1343 
1344 static void vhost_vdpa_reset_status(struct vhost_dev *dev)
1345 {
1346     struct vhost_vdpa *v = dev->opaque;
1347 
1348     if (!vhost_vdpa_last_dev(dev)) {
1349         return;
1350     }
1351 
1352     vhost_vdpa_reset_device(dev);
1353     vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_ACKNOWLEDGE |
1354                                VIRTIO_CONFIG_S_DRIVER);
1355     memory_listener_unregister(&v->shared->listener);
1356 }
1357 
1358 static int vhost_vdpa_set_log_base(struct vhost_dev *dev, uint64_t base,
1359                                      struct vhost_log *log)
1360 {
1361     struct vhost_vdpa *v = dev->opaque;
1362     if (v->shadow_vqs_enabled || !vhost_vdpa_first_dev(dev)) {
1363         return 0;
1364     }
1365 
1366     trace_vhost_vdpa_set_log_base(dev, base, log->size, log->refcnt, log->fd,
1367                                   log->log);
1368     return vhost_vdpa_call(dev, VHOST_SET_LOG_BASE, &base);
1369 }
1370 
1371 static int vhost_vdpa_set_vring_addr(struct vhost_dev *dev,
1372                                        struct vhost_vring_addr *addr)
1373 {
1374     struct vhost_vdpa *v = dev->opaque;
1375 
1376     if (v->shadow_vqs_enabled) {
1377         /*
1378          * Device vring addr was set at device start. SVQ base is handled by
1379          * VirtQueue code.
1380          */
1381         return 0;
1382     }
1383 
1384     return vhost_vdpa_set_vring_dev_addr(dev, addr);
1385 }
1386 
1387 static int vhost_vdpa_set_vring_num(struct vhost_dev *dev,
1388                                       struct vhost_vring_state *ring)
1389 {
1390     trace_vhost_vdpa_set_vring_num(dev, ring->index, ring->num);
1391     return vhost_vdpa_call(dev, VHOST_SET_VRING_NUM, ring);
1392 }
1393 
1394 static int vhost_vdpa_set_vring_base(struct vhost_dev *dev,
1395                                        struct vhost_vring_state *ring)
1396 {
1397     struct vhost_vdpa *v = dev->opaque;
1398 
1399     if (v->shadow_vqs_enabled) {
1400         /*
1401          * Device vring base was set at device start. SVQ base is handled by
1402          * VirtQueue code.
1403          */
1404         return 0;
1405     }
1406 
1407     return vhost_vdpa_set_dev_vring_base(dev, ring);
1408 }
1409 
1410 static int vhost_vdpa_get_vring_base(struct vhost_dev *dev,
1411                                        struct vhost_vring_state *ring)
1412 {
1413     struct vhost_vdpa *v = dev->opaque;
1414     int ret;
1415 
1416     if (v->shadow_vqs_enabled) {
1417         ring->num = virtio_queue_get_last_avail_idx(dev->vdev, ring->index);
1418         trace_vhost_vdpa_get_vring_base(dev, ring->index, ring->num, true);
1419         return 0;
1420     }
1421 
1422     if (!v->suspended) {
1423         /*
1424          * Cannot trust in value returned by device, let vhost recover used
1425          * idx from guest.
1426          */
1427         return -1;
1428     }
1429 
1430     ret = vhost_vdpa_call(dev, VHOST_GET_VRING_BASE, ring);
1431     trace_vhost_vdpa_get_vring_base(dev, ring->index, ring->num, false);
1432     return ret;
1433 }
1434 
1435 static int vhost_vdpa_set_vring_kick(struct vhost_dev *dev,
1436                                        struct vhost_vring_file *file)
1437 {
1438     struct vhost_vdpa *v = dev->opaque;
1439     int vdpa_idx = file->index - dev->vq_index;
1440 
1441     if (v->shadow_vqs_enabled) {
1442         VhostShadowVirtqueue *svq = g_ptr_array_index(v->shadow_vqs, vdpa_idx);
1443         vhost_svq_set_svq_kick_fd(svq, file->fd);
1444         return 0;
1445     } else {
1446         return vhost_vdpa_set_vring_dev_kick(dev, file);
1447     }
1448 }
1449 
1450 static int vhost_vdpa_set_vring_call(struct vhost_dev *dev,
1451                                        struct vhost_vring_file *file)
1452 {
1453     struct vhost_vdpa *v = dev->opaque;
1454     int vdpa_idx = file->index - dev->vq_index;
1455     VhostShadowVirtqueue *svq = g_ptr_array_index(v->shadow_vqs, vdpa_idx);
1456 
1457     /* Remember last call fd because we can switch to SVQ anytime. */
1458     vhost_svq_set_svq_call_fd(svq, file->fd);
1459     /*
1460      * When SVQ is transitioning to off, shadow_vqs_enabled has
1461      * not been set back to false yet, but the underlying call fd
1462      * will have to switch back to the guest notifier to signal the
1463      * passthrough virtqueues. In other situations, SVQ's own call
1464      * fd shall be used to signal the device model.
1465      */
1466     if (v->shadow_vqs_enabled &&
1467         v->shared->svq_switching != SVQ_TSTATE_DISABLING) {
1468         return 0;
1469     }
1470 
1471     return vhost_vdpa_set_vring_dev_call(dev, file);
1472 }
1473 
1474 static int vhost_vdpa_get_features(struct vhost_dev *dev,
1475                                      uint64_t *features)
1476 {
1477     int ret = vhost_vdpa_get_dev_features(dev, features);
1478 
1479     if (ret == 0) {
1480         /* Add SVQ logging capabilities */
1481         *features |= BIT_ULL(VHOST_F_LOG_ALL);
1482     }
1483 
1484     return ret;
1485 }
1486 
1487 static int vhost_vdpa_set_owner(struct vhost_dev *dev)
1488 {
1489     if (!vhost_vdpa_first_dev(dev)) {
1490         return 0;
1491     }
1492 
1493     trace_vhost_vdpa_set_owner(dev);
1494     return vhost_vdpa_call(dev, VHOST_SET_OWNER, NULL);
1495 }
1496 
1497 static int vhost_vdpa_vq_get_addr(struct vhost_dev *dev,
1498                     struct vhost_vring_addr *addr, struct vhost_virtqueue *vq)
1499 {
1500     assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA);
1501     addr->desc_user_addr = (uint64_t)(unsigned long)vq->desc_phys;
1502     addr->avail_user_addr = (uint64_t)(unsigned long)vq->avail_phys;
1503     addr->used_user_addr = (uint64_t)(unsigned long)vq->used_phys;
1504     trace_vhost_vdpa_vq_get_addr(dev, vq, addr->desc_user_addr,
1505                                  addr->avail_user_addr, addr->used_user_addr);
1506     return 0;
1507 }
1508 
1509 static bool  vhost_vdpa_force_iommu(struct vhost_dev *dev)
1510 {
1511     return true;
1512 }
1513 
1514 const VhostOps vdpa_ops = {
1515         .backend_type = VHOST_BACKEND_TYPE_VDPA,
1516         .vhost_backend_init = vhost_vdpa_init,
1517         .vhost_backend_cleanup = vhost_vdpa_cleanup,
1518         .vhost_set_log_base = vhost_vdpa_set_log_base,
1519         .vhost_set_vring_addr = vhost_vdpa_set_vring_addr,
1520         .vhost_set_vring_num = vhost_vdpa_set_vring_num,
1521         .vhost_set_vring_base = vhost_vdpa_set_vring_base,
1522         .vhost_get_vring_base = vhost_vdpa_get_vring_base,
1523         .vhost_set_vring_kick = vhost_vdpa_set_vring_kick,
1524         .vhost_set_vring_call = vhost_vdpa_set_vring_call,
1525         .vhost_get_features = vhost_vdpa_get_features,
1526         .vhost_set_backend_cap = vhost_vdpa_set_backend_cap,
1527         .vhost_set_owner = vhost_vdpa_set_owner,
1528         .vhost_set_vring_endian = NULL,
1529         .vhost_backend_memslots_limit = vhost_vdpa_memslots_limit,
1530         .vhost_set_mem_table = vhost_vdpa_set_mem_table,
1531         .vhost_set_features = vhost_vdpa_set_features,
1532         .vhost_reset_device = vhost_vdpa_reset_device,
1533         .vhost_get_vq_index = vhost_vdpa_get_vq_index,
1534         .vhost_get_config  = vhost_vdpa_get_config,
1535         .vhost_set_config = vhost_vdpa_set_config,
1536         .vhost_requires_shm_log = NULL,
1537         .vhost_migration_done = NULL,
1538         .vhost_net_set_mtu = NULL,
1539         .vhost_set_iotlb_callback = NULL,
1540         .vhost_send_device_iotlb_msg = NULL,
1541         .vhost_dev_start = vhost_vdpa_dev_start,
1542         .vhost_get_device_id = vhost_vdpa_get_device_id,
1543         .vhost_vq_get_addr = vhost_vdpa_vq_get_addr,
1544         .vhost_force_iommu = vhost_vdpa_force_iommu,
1545         .vhost_set_config_call = vhost_vdpa_set_config_call,
1546         .vhost_reset_status = vhost_vdpa_reset_status,
1547 };
1548