xref: /openbmc/qemu/hw/virtio/virtio-iommu.c (revision 3f5ef05f)
1 /*
2  * virtio-iommu device
3  *
4  * Copyright (c) 2020 Red Hat, Inc.
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms and conditions of the GNU General Public License,
8  * version 2 or later, as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program.  If not, see <http://www.gnu.org/licenses/>.
17  *
18  */
19 
20 #include "qemu/osdep.h"
21 #include "qemu/log.h"
22 #include "qemu/iov.h"
23 #include "qemu/range.h"
24 #include "qemu/reserved-region.h"
25 #include "exec/target_page.h"
26 #include "hw/qdev-properties.h"
27 #include "hw/virtio/virtio.h"
28 #include "sysemu/kvm.h"
29 #include "sysemu/reset.h"
30 #include "sysemu/sysemu.h"
31 #include "qemu/reserved-region.h"
32 #include "qemu/units.h"
33 #include "qapi/error.h"
34 #include "qemu/error-report.h"
35 #include "trace.h"
36 
37 #include "standard-headers/linux/virtio_ids.h"
38 
39 #include "hw/virtio/virtio-bus.h"
40 #include "hw/virtio/virtio-iommu.h"
41 #include "hw/pci/pci_bus.h"
42 #include "hw/pci/pci.h"
43 
44 /* Max size */
45 #define VIOMMU_DEFAULT_QUEUE_SIZE 256
46 #define VIOMMU_PROBE_SIZE 512
47 
48 typedef struct VirtIOIOMMUDomain {
49     uint32_t id;
50     bool bypass;
51     GTree *mappings;
52     QLIST_HEAD(, VirtIOIOMMUEndpoint) endpoint_list;
53 } VirtIOIOMMUDomain;
54 
55 typedef struct VirtIOIOMMUEndpoint {
56     uint32_t id;
57     VirtIOIOMMUDomain *domain;
58     IOMMUMemoryRegion *iommu_mr;
59     QLIST_ENTRY(VirtIOIOMMUEndpoint) next;
60 } VirtIOIOMMUEndpoint;
61 
62 typedef struct VirtIOIOMMUInterval {
63     uint64_t low;
64     uint64_t high;
65 } VirtIOIOMMUInterval;
66 
67 typedef struct VirtIOIOMMUMapping {
68     uint64_t phys_addr;
69     uint32_t flags;
70 } VirtIOIOMMUMapping;
71 
72 struct hiod_key {
73     PCIBus *bus;
74     uint8_t devfn;
75 };
76 
77 static inline uint16_t virtio_iommu_get_bdf(IOMMUDevice *dev)
78 {
79     return PCI_BUILD_BDF(pci_bus_num(dev->bus), dev->devfn);
80 }
81 
82 static bool virtio_iommu_device_bypassed(IOMMUDevice *sdev)
83 {
84     uint32_t sid;
85     bool bypassed;
86     VirtIOIOMMU *s = sdev->viommu;
87     VirtIOIOMMUEndpoint *ep;
88 
89     sid = virtio_iommu_get_bdf(sdev);
90 
91     qemu_rec_mutex_lock(&s->mutex);
92     /* need to check bypass before system reset */
93     if (!s->endpoints) {
94         bypassed = s->config.bypass;
95         goto unlock;
96     }
97 
98     ep = g_tree_lookup(s->endpoints, GUINT_TO_POINTER(sid));
99     if (!ep || !ep->domain) {
100         bypassed = s->config.bypass;
101     } else {
102         bypassed = ep->domain->bypass;
103     }
104 
105 unlock:
106     qemu_rec_mutex_unlock(&s->mutex);
107     return bypassed;
108 }
109 
110 /* Return whether the device is using IOMMU translation. */
111 static bool virtio_iommu_switch_address_space(IOMMUDevice *sdev)
112 {
113     bool use_remapping;
114 
115     assert(sdev);
116 
117     use_remapping = !virtio_iommu_device_bypassed(sdev);
118 
119     trace_virtio_iommu_switch_address_space(pci_bus_num(sdev->bus),
120                                             PCI_SLOT(sdev->devfn),
121                                             PCI_FUNC(sdev->devfn),
122                                             use_remapping);
123 
124     /* Turn off first then on the other */
125     if (use_remapping) {
126         memory_region_set_enabled(&sdev->bypass_mr, false);
127         memory_region_set_enabled(MEMORY_REGION(&sdev->iommu_mr), true);
128     } else {
129         memory_region_set_enabled(MEMORY_REGION(&sdev->iommu_mr), false);
130         memory_region_set_enabled(&sdev->bypass_mr, true);
131     }
132 
133     return use_remapping;
134 }
135 
136 static void virtio_iommu_switch_address_space_all(VirtIOIOMMU *s)
137 {
138     GHashTableIter iter;
139     IOMMUPciBus *iommu_pci_bus;
140     int i;
141 
142     g_hash_table_iter_init(&iter, s->as_by_busptr);
143     while (g_hash_table_iter_next(&iter, NULL, (void **)&iommu_pci_bus)) {
144         for (i = 0; i < PCI_DEVFN_MAX; i++) {
145             if (!iommu_pci_bus->pbdev[i]) {
146                 continue;
147             }
148             virtio_iommu_switch_address_space(iommu_pci_bus->pbdev[i]);
149         }
150     }
151 }
152 
153 /**
154  * The bus number is used for lookup when SID based operations occur.
155  * In that case we lazily populate the IOMMUPciBus array from the bus hash
156  * table. At the time the IOMMUPciBus is created (iommu_find_add_as), the bus
157  * numbers may not be always initialized yet.
158  */
159 static IOMMUPciBus *iommu_find_iommu_pcibus(VirtIOIOMMU *s, uint8_t bus_num)
160 {
161     IOMMUPciBus *iommu_pci_bus = s->iommu_pcibus_by_bus_num[bus_num];
162 
163     if (!iommu_pci_bus) {
164         GHashTableIter iter;
165 
166         g_hash_table_iter_init(&iter, s->as_by_busptr);
167         while (g_hash_table_iter_next(&iter, NULL, (void **)&iommu_pci_bus)) {
168             if (pci_bus_num(iommu_pci_bus->bus) == bus_num) {
169                 s->iommu_pcibus_by_bus_num[bus_num] = iommu_pci_bus;
170                 return iommu_pci_bus;
171             }
172         }
173         return NULL;
174     }
175     return iommu_pci_bus;
176 }
177 
178 static IOMMUMemoryRegion *virtio_iommu_mr(VirtIOIOMMU *s, uint32_t sid)
179 {
180     uint8_t bus_n, devfn;
181     IOMMUPciBus *iommu_pci_bus;
182     IOMMUDevice *dev;
183 
184     bus_n = PCI_BUS_NUM(sid);
185     iommu_pci_bus = iommu_find_iommu_pcibus(s, bus_n);
186     if (iommu_pci_bus) {
187         devfn = sid & (PCI_DEVFN_MAX - 1);
188         dev = iommu_pci_bus->pbdev[devfn];
189         if (dev) {
190             return &dev->iommu_mr;
191         }
192     }
193     return NULL;
194 }
195 
196 static gint interval_cmp(gconstpointer a, gconstpointer b, gpointer user_data)
197 {
198     VirtIOIOMMUInterval *inta = (VirtIOIOMMUInterval *)a;
199     VirtIOIOMMUInterval *intb = (VirtIOIOMMUInterval *)b;
200 
201     if (inta->high < intb->low) {
202         return -1;
203     } else if (intb->high < inta->low) {
204         return 1;
205     } else {
206         return 0;
207     }
208 }
209 
210 static void virtio_iommu_notify_map_unmap(IOMMUMemoryRegion *mr,
211                                           IOMMUTLBEvent *event,
212                                           hwaddr virt_start, hwaddr virt_end)
213 {
214     uint64_t delta = virt_end - virt_start;
215 
216     event->entry.iova = virt_start;
217     event->entry.addr_mask = delta;
218 
219     if (delta == UINT64_MAX) {
220         memory_region_notify_iommu(mr, 0, *event);
221     }
222 
223     while (virt_start != virt_end + 1) {
224         uint64_t mask = dma_aligned_pow2_mask(virt_start, virt_end, 64);
225 
226         event->entry.addr_mask = mask;
227         event->entry.iova = virt_start;
228         memory_region_notify_iommu(mr, 0, *event);
229         virt_start += mask + 1;
230         if (event->entry.perm != IOMMU_NONE) {
231             event->entry.translated_addr += mask + 1;
232         }
233     }
234 }
235 
236 static void virtio_iommu_notify_map(IOMMUMemoryRegion *mr, hwaddr virt_start,
237                                     hwaddr virt_end, hwaddr paddr,
238                                     uint32_t flags)
239 {
240     IOMMUTLBEvent event;
241     IOMMUAccessFlags perm = IOMMU_ACCESS_FLAG(flags & VIRTIO_IOMMU_MAP_F_READ,
242                                               flags & VIRTIO_IOMMU_MAP_F_WRITE);
243 
244     if (!(mr->iommu_notify_flags & IOMMU_NOTIFIER_MAP) ||
245         (flags & VIRTIO_IOMMU_MAP_F_MMIO) || !perm) {
246         return;
247     }
248 
249     trace_virtio_iommu_notify_map(mr->parent_obj.name, virt_start, virt_end,
250                                   paddr, perm);
251 
252     event.type = IOMMU_NOTIFIER_MAP;
253     event.entry.target_as = &address_space_memory;
254     event.entry.perm = perm;
255     event.entry.translated_addr = paddr;
256 
257     virtio_iommu_notify_map_unmap(mr, &event, virt_start, virt_end);
258 }
259 
260 static void virtio_iommu_notify_unmap(IOMMUMemoryRegion *mr, hwaddr virt_start,
261                                       hwaddr virt_end)
262 {
263     IOMMUTLBEvent event;
264 
265     if (!(mr->iommu_notify_flags & IOMMU_NOTIFIER_UNMAP)) {
266         return;
267     }
268 
269     trace_virtio_iommu_notify_unmap(mr->parent_obj.name, virt_start, virt_end);
270 
271     event.type = IOMMU_NOTIFIER_UNMAP;
272     event.entry.target_as = &address_space_memory;
273     event.entry.perm = IOMMU_NONE;
274     event.entry.translated_addr = 0;
275 
276     virtio_iommu_notify_map_unmap(mr, &event, virt_start, virt_end);
277 }
278 
279 static gboolean virtio_iommu_notify_unmap_cb(gpointer key, gpointer value,
280                                              gpointer data)
281 {
282     VirtIOIOMMUInterval *interval = (VirtIOIOMMUInterval *) key;
283     IOMMUMemoryRegion *mr = (IOMMUMemoryRegion *) data;
284 
285     virtio_iommu_notify_unmap(mr, interval->low, interval->high);
286 
287     return false;
288 }
289 
290 static gboolean virtio_iommu_notify_map_cb(gpointer key, gpointer value,
291                                            gpointer data)
292 {
293     VirtIOIOMMUMapping *mapping = (VirtIOIOMMUMapping *) value;
294     VirtIOIOMMUInterval *interval = (VirtIOIOMMUInterval *) key;
295     IOMMUMemoryRegion *mr = (IOMMUMemoryRegion *) data;
296 
297     virtio_iommu_notify_map(mr, interval->low, interval->high,
298                             mapping->phys_addr, mapping->flags);
299 
300     return false;
301 }
302 
303 static void virtio_iommu_detach_endpoint_from_domain(VirtIOIOMMUEndpoint *ep)
304 {
305     VirtIOIOMMUDomain *domain = ep->domain;
306     IOMMUDevice *sdev = container_of(ep->iommu_mr, IOMMUDevice, iommu_mr);
307 
308     if (!ep->domain) {
309         return;
310     }
311     g_tree_foreach(domain->mappings, virtio_iommu_notify_unmap_cb,
312                    ep->iommu_mr);
313     QLIST_REMOVE(ep, next);
314     ep->domain = NULL;
315     virtio_iommu_switch_address_space(sdev);
316 }
317 
318 static VirtIOIOMMUEndpoint *virtio_iommu_get_endpoint(VirtIOIOMMU *s,
319                                                       uint32_t ep_id)
320 {
321     VirtIOIOMMUEndpoint *ep;
322     IOMMUMemoryRegion *mr;
323 
324     ep = g_tree_lookup(s->endpoints, GUINT_TO_POINTER(ep_id));
325     if (ep) {
326         return ep;
327     }
328     mr = virtio_iommu_mr(s, ep_id);
329     if (!mr) {
330         return NULL;
331     }
332     ep = g_malloc0(sizeof(*ep));
333     ep->id = ep_id;
334     ep->iommu_mr = mr;
335     trace_virtio_iommu_get_endpoint(ep_id);
336     g_tree_insert(s->endpoints, GUINT_TO_POINTER(ep_id), ep);
337     return ep;
338 }
339 
340 static void virtio_iommu_put_endpoint(gpointer data)
341 {
342     VirtIOIOMMUEndpoint *ep = (VirtIOIOMMUEndpoint *)data;
343 
344     if (ep->domain) {
345         virtio_iommu_detach_endpoint_from_domain(ep);
346     }
347 
348     trace_virtio_iommu_put_endpoint(ep->id);
349     g_free(ep);
350 }
351 
352 static VirtIOIOMMUDomain *virtio_iommu_get_domain(VirtIOIOMMU *s,
353                                                   uint32_t domain_id,
354                                                   bool bypass)
355 {
356     VirtIOIOMMUDomain *domain;
357 
358     domain = g_tree_lookup(s->domains, GUINT_TO_POINTER(domain_id));
359     if (domain) {
360         if (domain->bypass != bypass) {
361             return NULL;
362         }
363         return domain;
364     }
365     domain = g_malloc0(sizeof(*domain));
366     domain->id = domain_id;
367     domain->mappings = g_tree_new_full((GCompareDataFunc)interval_cmp,
368                                    NULL, (GDestroyNotify)g_free,
369                                    (GDestroyNotify)g_free);
370     domain->bypass = bypass;
371     g_tree_insert(s->domains, GUINT_TO_POINTER(domain_id), domain);
372     QLIST_INIT(&domain->endpoint_list);
373     trace_virtio_iommu_get_domain(domain_id);
374     return domain;
375 }
376 
377 static void virtio_iommu_put_domain(gpointer data)
378 {
379     VirtIOIOMMUDomain *domain = (VirtIOIOMMUDomain *)data;
380     VirtIOIOMMUEndpoint *iter, *tmp;
381 
382     QLIST_FOREACH_SAFE(iter, &domain->endpoint_list, next, tmp) {
383         virtio_iommu_detach_endpoint_from_domain(iter);
384     }
385     g_tree_destroy(domain->mappings);
386     trace_virtio_iommu_put_domain(domain->id);
387     g_free(domain);
388 }
389 
390 static void add_prop_resv_regions(IOMMUDevice *sdev)
391 {
392     VirtIOIOMMU *s = sdev->viommu;
393     int i;
394 
395     for (i = 0; i < s->nr_prop_resv_regions; i++) {
396         ReservedRegion *reg = g_new0(ReservedRegion, 1);
397 
398         *reg = s->prop_resv_regions[i];
399         sdev->resv_regions = resv_region_list_insert(sdev->resv_regions, reg);
400     }
401 }
402 
403 static AddressSpace *virtio_iommu_find_add_as(PCIBus *bus, void *opaque,
404                                               int devfn)
405 {
406     VirtIOIOMMU *s = opaque;
407     IOMMUPciBus *sbus = g_hash_table_lookup(s->as_by_busptr, bus);
408     static uint32_t mr_index;
409     IOMMUDevice *sdev;
410 
411     if (!sbus) {
412         sbus = g_malloc0(sizeof(IOMMUPciBus) +
413                          sizeof(IOMMUDevice *) * PCI_DEVFN_MAX);
414         sbus->bus = bus;
415         g_hash_table_insert(s->as_by_busptr, bus, sbus);
416     }
417 
418     sdev = sbus->pbdev[devfn];
419     if (!sdev) {
420         char *name = g_strdup_printf("%s-%d-%d",
421                                      TYPE_VIRTIO_IOMMU_MEMORY_REGION,
422                                      mr_index++, devfn);
423         sdev = sbus->pbdev[devfn] = g_new0(IOMMUDevice, 1);
424 
425         sdev->viommu = s;
426         sdev->bus = bus;
427         sdev->devfn = devfn;
428 
429         trace_virtio_iommu_init_iommu_mr(name);
430 
431         memory_region_init(&sdev->root, OBJECT(s), name, UINT64_MAX);
432         address_space_init(&sdev->as, &sdev->root, TYPE_VIRTIO_IOMMU);
433         add_prop_resv_regions(sdev);
434 
435         /*
436          * Build the IOMMU disabled container with aliases to the
437          * shared MRs.  Note that aliasing to a shared memory region
438          * could help the memory API to detect same FlatViews so we
439          * can have devices to share the same FlatView when in bypass
440          * mode. (either by not configuring virtio-iommu driver or with
441          * "iommu=pt").  It will greatly reduce the total number of
442          * FlatViews of the system hence VM runs faster.
443          */
444         memory_region_init_alias(&sdev->bypass_mr, OBJECT(s),
445                                  "system", get_system_memory(), 0,
446                                  memory_region_size(get_system_memory()));
447 
448         memory_region_init_iommu(&sdev->iommu_mr, sizeof(sdev->iommu_mr),
449                                  TYPE_VIRTIO_IOMMU_MEMORY_REGION,
450                                  OBJECT(s), name,
451                                  UINT64_MAX);
452 
453         /*
454          * Hook both the containers under the root container, we
455          * switch between iommu & bypass MRs by enable/disable
456          * corresponding sub-containers
457          */
458         memory_region_add_subregion_overlap(&sdev->root, 0,
459                                             MEMORY_REGION(&sdev->iommu_mr),
460                                             0);
461         memory_region_add_subregion_overlap(&sdev->root, 0,
462                                             &sdev->bypass_mr, 0);
463 
464         virtio_iommu_switch_address_space(sdev);
465         g_free(name);
466     }
467     return &sdev->as;
468 }
469 
470 static void virtio_iommu_device_clear(VirtIOIOMMU *s, PCIBus *bus, int devfn)
471 {
472     IOMMUPciBus *sbus = g_hash_table_lookup(s->as_by_busptr, bus);
473     IOMMUDevice *sdev;
474 
475     if (!sbus) {
476         return;
477     }
478 
479     sdev = sbus->pbdev[devfn];
480     if (!sdev) {
481         return;
482     }
483 
484     g_list_free_full(sdev->resv_regions, g_free);
485     sdev->resv_regions = NULL;
486     g_free(sdev);
487     sbus->pbdev[devfn] = NULL;
488 }
489 
490 static gboolean hiod_equal(gconstpointer v1, gconstpointer v2)
491 {
492     const struct hiod_key *key1 = v1;
493     const struct hiod_key *key2 = v2;
494 
495     return (key1->bus == key2->bus) && (key1->devfn == key2->devfn);
496 }
497 
498 static guint hiod_hash(gconstpointer v)
499 {
500     const struct hiod_key *key = v;
501     guint value = (guint)(uintptr_t)key->bus;
502 
503     return (guint)(value << 8 | key->devfn);
504 }
505 
506 static void hiod_destroy(gpointer v)
507 {
508     object_unref(v);
509 }
510 
511 static HostIOMMUDevice *
512 get_host_iommu_device(VirtIOIOMMU *viommu, PCIBus *bus, int devfn) {
513     struct hiod_key key = {
514         .bus = bus,
515         .devfn = devfn,
516     };
517 
518     return g_hash_table_lookup(viommu->host_iommu_devices, &key);
519 }
520 
521 /**
522  * rebuild_resv_regions: rebuild resv regions with both the
523  * info of host resv ranges and property set resv ranges
524  */
525 static int rebuild_resv_regions(IOMMUDevice *sdev)
526 {
527     GList *l;
528     int i = 0;
529 
530     /* free the existing list and rebuild it from scratch */
531     g_list_free_full(sdev->resv_regions, g_free);
532     sdev->resv_regions = NULL;
533 
534     /* First add host reserved regions if any, all tagged as RESERVED */
535     for (l = sdev->host_resv_ranges; l; l = l->next) {
536         ReservedRegion *reg = g_new0(ReservedRegion, 1);
537         Range *r = (Range *)l->data;
538 
539         reg->type = VIRTIO_IOMMU_RESV_MEM_T_RESERVED;
540         range_set_bounds(&reg->range, range_lob(r), range_upb(r));
541         sdev->resv_regions = resv_region_list_insert(sdev->resv_regions, reg);
542         trace_virtio_iommu_host_resv_regions(sdev->iommu_mr.parent_obj.name, i,
543                                              range_lob(&reg->range),
544                                              range_upb(&reg->range));
545         i++;
546     }
547     /*
548      * then add higher priority reserved regions set by the machine
549      * through properties
550      */
551     add_prop_resv_regions(sdev);
552     return 0;
553 }
554 
555 static int virtio_iommu_set_host_iova_ranges(VirtIOIOMMU *s, PCIBus *bus,
556                                              int devfn, GList *iova_ranges,
557                                              Error **errp)
558 {
559     IOMMUPciBus *sbus = g_hash_table_lookup(s->as_by_busptr, bus);
560     IOMMUDevice *sdev;
561     GList *current_ranges;
562     GList *l, *tmp, *new_ranges = NULL;
563     int ret = -EINVAL;
564 
565     if (!sbus) {
566         error_setg(errp, "%s: no IOMMUPciBus found!", __func__);
567         return ret;
568     }
569 
570     sdev = sbus->pbdev[devfn];
571     if (!sdev) {
572         error_setg(errp, "%s: no IOMMUDevice found!", __func__);
573         return ret;
574     }
575 
576     current_ranges = sdev->host_resv_ranges;
577 
578     g_assert(!sdev->probe_done);
579 
580     /* check that each new resv region is included in an existing one */
581     if (sdev->host_resv_ranges) {
582         range_inverse_array(iova_ranges,
583                             &new_ranges,
584                             0, UINT64_MAX);
585 
586         for (tmp = new_ranges; tmp; tmp = tmp->next) {
587             Range *newr = (Range *)tmp->data;
588             bool included = false;
589 
590             for (l = current_ranges; l; l = l->next) {
591                 Range * r = (Range *)l->data;
592 
593                 if (range_contains_range(r, newr)) {
594                     included = true;
595                     break;
596                 }
597             }
598             if (!included) {
599                 goto error;
600             }
601         }
602         /* all new reserved ranges are included in existing ones */
603         ret = 0;
604         goto out;
605     }
606 
607     range_inverse_array(iova_ranges,
608                         &sdev->host_resv_ranges,
609                         0, UINT64_MAX);
610     rebuild_resv_regions(sdev);
611 
612     return 0;
613 error:
614     error_setg(errp, "%s Conflicting host reserved ranges set!",
615                __func__);
616 out:
617     g_list_free_full(new_ranges, g_free);
618     return ret;
619 }
620 
621 static bool check_page_size_mask(VirtIOIOMMU *viommu, uint64_t new_mask,
622                                  Error **errp)
623 {
624     uint64_t cur_mask = viommu->config.page_size_mask;
625 
626     if ((cur_mask & new_mask) == 0) {
627         error_setg(errp, "virtio-iommu reports a page size mask 0x%"PRIx64
628                    " incompatible with currently supported mask 0x%"PRIx64,
629                    new_mask, cur_mask);
630         return false;
631     }
632     /*
633      * Once the granule is frozen we can't change the mask anymore. If by
634      * chance the hotplugged device supports the same granule, we can still
635      * accept it.
636      */
637     if (viommu->granule_frozen) {
638         int cur_granule = ctz64(cur_mask);
639 
640         if (!(BIT_ULL(cur_granule) & new_mask)) {
641             error_setg(errp,
642                        "virtio-iommu does not support frozen granule 0x%llx",
643                        BIT_ULL(cur_granule));
644             return false;
645         }
646     }
647     return true;
648 }
649 
650 static bool virtio_iommu_set_iommu_device(PCIBus *bus, void *opaque, int devfn,
651                                           HostIOMMUDevice *hiod, Error **errp)
652 {
653     ERRP_GUARD();
654     VirtIOIOMMU *viommu = opaque;
655     HostIOMMUDeviceClass *hiodc = HOST_IOMMU_DEVICE_GET_CLASS(hiod);
656     struct hiod_key *new_key;
657     GList *host_iova_ranges = NULL;
658 
659     assert(hiod);
660 
661     if (get_host_iommu_device(viommu, bus, devfn)) {
662         error_setg(errp, "Host IOMMU device already exists");
663         return false;
664     }
665 
666     if (hiodc->get_iova_ranges) {
667         int ret;
668         host_iova_ranges = hiodc->get_iova_ranges(hiod);
669         if (!host_iova_ranges) {
670             return true; /* some old kernels may not support that capability */
671         }
672         ret = virtio_iommu_set_host_iova_ranges(viommu, hiod->aliased_bus,
673                                                 hiod->aliased_devfn,
674                                                 host_iova_ranges, errp);
675         if (ret) {
676             goto error;
677         }
678     }
679     if (hiodc->get_page_size_mask) {
680         uint64_t new_mask = hiodc->get_page_size_mask(hiod);
681 
682         if (check_page_size_mask(viommu, new_mask, errp)) {
683             /*
684              * The default mask depends on the "granule" property. For example,
685              * with 4k granule, it is -(4 * KiB). When an assigned device has
686              * page size restrictions due to the hardware IOMMU configuration,
687              * apply this restriction to the mask.
688              */
689             trace_virtio_iommu_update_page_size_mask(hiod->name,
690                                                      viommu->config.page_size_mask,
691                                                      new_mask);
692             if (!viommu->granule_frozen) {
693                 viommu->config.page_size_mask &= new_mask;
694             }
695         } else {
696             error_prepend(errp, "%s: ", hiod->name);
697             goto error;
698         }
699     }
700 
701     new_key = g_malloc(sizeof(*new_key));
702     new_key->bus = bus;
703     new_key->devfn = devfn;
704 
705     object_ref(hiod);
706     g_hash_table_insert(viommu->host_iommu_devices, new_key, hiod);
707     g_list_free_full(host_iova_ranges, g_free);
708 
709     return true;
710 error:
711     g_list_free_full(host_iova_ranges, g_free);
712     return false;
713 }
714 
715 static void
716 virtio_iommu_unset_iommu_device(PCIBus *bus, void *opaque, int devfn)
717 {
718     VirtIOIOMMU *viommu = opaque;
719     HostIOMMUDevice *hiod;
720     struct hiod_key key = {
721         .bus = bus,
722         .devfn = devfn,
723     };
724 
725     hiod = g_hash_table_lookup(viommu->host_iommu_devices, &key);
726     if (!hiod) {
727         return;
728     }
729 
730     g_hash_table_remove(viommu->host_iommu_devices, &key);
731     virtio_iommu_device_clear(viommu, bus, devfn);
732 }
733 
734 static const PCIIOMMUOps virtio_iommu_ops = {
735     .get_address_space = virtio_iommu_find_add_as,
736     .set_iommu_device = virtio_iommu_set_iommu_device,
737     .unset_iommu_device = virtio_iommu_unset_iommu_device,
738 };
739 
740 static int virtio_iommu_attach(VirtIOIOMMU *s,
741                                struct virtio_iommu_req_attach *req)
742 {
743     uint32_t domain_id = le32_to_cpu(req->domain);
744     uint32_t ep_id = le32_to_cpu(req->endpoint);
745     uint32_t flags = le32_to_cpu(req->flags);
746     VirtIOIOMMUDomain *domain;
747     VirtIOIOMMUEndpoint *ep;
748     IOMMUDevice *sdev;
749 
750     trace_virtio_iommu_attach(domain_id, ep_id);
751 
752     if (flags & ~VIRTIO_IOMMU_ATTACH_F_BYPASS) {
753         return VIRTIO_IOMMU_S_INVAL;
754     }
755 
756     ep = virtio_iommu_get_endpoint(s, ep_id);
757     if (!ep) {
758         return VIRTIO_IOMMU_S_NOENT;
759     }
760 
761     if (ep->domain) {
762         VirtIOIOMMUDomain *previous_domain = ep->domain;
763         /*
764          * the device is already attached to a domain,
765          * detach it first
766          */
767         virtio_iommu_detach_endpoint_from_domain(ep);
768         if (QLIST_EMPTY(&previous_domain->endpoint_list)) {
769             g_tree_remove(s->domains, GUINT_TO_POINTER(previous_domain->id));
770         }
771     }
772 
773     domain = virtio_iommu_get_domain(s, domain_id,
774                                      flags & VIRTIO_IOMMU_ATTACH_F_BYPASS);
775     if (!domain) {
776         /* Incompatible bypass flag */
777         return VIRTIO_IOMMU_S_INVAL;
778     }
779     QLIST_INSERT_HEAD(&domain->endpoint_list, ep, next);
780 
781     ep->domain = domain;
782     sdev = container_of(ep->iommu_mr, IOMMUDevice, iommu_mr);
783     virtio_iommu_switch_address_space(sdev);
784 
785     /* Replay domain mappings on the associated memory region */
786     g_tree_foreach(domain->mappings, virtio_iommu_notify_map_cb,
787                    ep->iommu_mr);
788 
789     return VIRTIO_IOMMU_S_OK;
790 }
791 
792 static int virtio_iommu_detach(VirtIOIOMMU *s,
793                                struct virtio_iommu_req_detach *req)
794 {
795     uint32_t domain_id = le32_to_cpu(req->domain);
796     uint32_t ep_id = le32_to_cpu(req->endpoint);
797     VirtIOIOMMUDomain *domain;
798     VirtIOIOMMUEndpoint *ep;
799 
800     trace_virtio_iommu_detach(domain_id, ep_id);
801 
802     ep = g_tree_lookup(s->endpoints, GUINT_TO_POINTER(ep_id));
803     if (!ep) {
804         return VIRTIO_IOMMU_S_NOENT;
805     }
806 
807     domain = ep->domain;
808 
809     if (!domain || domain->id != domain_id) {
810         return VIRTIO_IOMMU_S_INVAL;
811     }
812 
813     virtio_iommu_detach_endpoint_from_domain(ep);
814 
815     if (QLIST_EMPTY(&domain->endpoint_list)) {
816         g_tree_remove(s->domains, GUINT_TO_POINTER(domain->id));
817     }
818     return VIRTIO_IOMMU_S_OK;
819 }
820 
821 static int virtio_iommu_map(VirtIOIOMMU *s,
822                             struct virtio_iommu_req_map *req)
823 {
824     uint32_t domain_id = le32_to_cpu(req->domain);
825     uint64_t phys_start = le64_to_cpu(req->phys_start);
826     uint64_t virt_start = le64_to_cpu(req->virt_start);
827     uint64_t virt_end = le64_to_cpu(req->virt_end);
828     uint32_t flags = le32_to_cpu(req->flags);
829     VirtIOIOMMUDomain *domain;
830     VirtIOIOMMUInterval *interval;
831     VirtIOIOMMUMapping *mapping;
832     VirtIOIOMMUEndpoint *ep;
833 
834     if (flags & ~VIRTIO_IOMMU_MAP_F_MASK) {
835         return VIRTIO_IOMMU_S_INVAL;
836     }
837 
838     domain = g_tree_lookup(s->domains, GUINT_TO_POINTER(domain_id));
839     if (!domain) {
840         return VIRTIO_IOMMU_S_NOENT;
841     }
842 
843     if (domain->bypass) {
844         return VIRTIO_IOMMU_S_INVAL;
845     }
846 
847     interval = g_malloc0(sizeof(*interval));
848 
849     interval->low = virt_start;
850     interval->high = virt_end;
851 
852     mapping = g_tree_lookup(domain->mappings, (gpointer)interval);
853     if (mapping) {
854         g_free(interval);
855         return VIRTIO_IOMMU_S_INVAL;
856     }
857 
858     trace_virtio_iommu_map(domain_id, virt_start, virt_end, phys_start, flags);
859 
860     mapping = g_malloc0(sizeof(*mapping));
861     mapping->phys_addr = phys_start;
862     mapping->flags = flags;
863 
864     g_tree_insert(domain->mappings, interval, mapping);
865 
866     QLIST_FOREACH(ep, &domain->endpoint_list, next) {
867         virtio_iommu_notify_map(ep->iommu_mr, virt_start, virt_end, phys_start,
868                                 flags);
869     }
870 
871     return VIRTIO_IOMMU_S_OK;
872 }
873 
874 static int virtio_iommu_unmap(VirtIOIOMMU *s,
875                               struct virtio_iommu_req_unmap *req)
876 {
877     uint32_t domain_id = le32_to_cpu(req->domain);
878     uint64_t virt_start = le64_to_cpu(req->virt_start);
879     uint64_t virt_end = le64_to_cpu(req->virt_end);
880     VirtIOIOMMUMapping *iter_val;
881     VirtIOIOMMUInterval interval, *iter_key;
882     VirtIOIOMMUDomain *domain;
883     VirtIOIOMMUEndpoint *ep;
884     int ret = VIRTIO_IOMMU_S_OK;
885 
886     trace_virtio_iommu_unmap(domain_id, virt_start, virt_end);
887 
888     domain = g_tree_lookup(s->domains, GUINT_TO_POINTER(domain_id));
889     if (!domain) {
890         return VIRTIO_IOMMU_S_NOENT;
891     }
892 
893     if (domain->bypass) {
894         return VIRTIO_IOMMU_S_INVAL;
895     }
896 
897     interval.low = virt_start;
898     interval.high = virt_end;
899 
900     while (g_tree_lookup_extended(domain->mappings, &interval,
901                                   (void **)&iter_key, (void**)&iter_val)) {
902         uint64_t current_low = iter_key->low;
903         uint64_t current_high = iter_key->high;
904 
905         if (interval.low <= current_low && interval.high >= current_high) {
906             QLIST_FOREACH(ep, &domain->endpoint_list, next) {
907                 virtio_iommu_notify_unmap(ep->iommu_mr, current_low,
908                                           current_high);
909             }
910             g_tree_remove(domain->mappings, iter_key);
911             trace_virtio_iommu_unmap_done(domain_id, current_low, current_high);
912         } else {
913             ret = VIRTIO_IOMMU_S_RANGE;
914             break;
915         }
916     }
917     return ret;
918 }
919 
920 static ssize_t virtio_iommu_fill_resv_mem_prop(IOMMUDevice *sdev, uint32_t ep,
921                                                uint8_t *buf, size_t free)
922 {
923     struct virtio_iommu_probe_resv_mem prop = {};
924     size_t size = sizeof(prop), length = size - sizeof(prop.head), total;
925     GList *l;
926 
927     total = size * g_list_length(sdev->resv_regions);
928     if (total > free) {
929         return -ENOSPC;
930     }
931 
932     for (l = sdev->resv_regions; l; l = l->next) {
933         ReservedRegion *reg = l->data;
934         unsigned subtype = reg->type;
935         Range *range = &reg->range;
936 
937         assert(subtype == VIRTIO_IOMMU_RESV_MEM_T_RESERVED ||
938                subtype == VIRTIO_IOMMU_RESV_MEM_T_MSI);
939         prop.head.type = cpu_to_le16(VIRTIO_IOMMU_PROBE_T_RESV_MEM);
940         prop.head.length = cpu_to_le16(length);
941         prop.subtype = subtype;
942         prop.start = cpu_to_le64(range_lob(range));
943         prop.end = cpu_to_le64(range_upb(range));
944 
945         memcpy(buf, &prop, size);
946 
947         trace_virtio_iommu_fill_resv_property(ep, prop.subtype,
948                                               prop.start, prop.end);
949         buf += size;
950     }
951     return total;
952 }
953 
954 /**
955  * virtio_iommu_probe - Fill the probe request buffer with
956  * the properties the device is able to return
957  */
958 static int virtio_iommu_probe(VirtIOIOMMU *s,
959                               struct virtio_iommu_req_probe *req,
960                               uint8_t *buf)
961 {
962     uint32_t ep_id = le32_to_cpu(req->endpoint);
963     IOMMUMemoryRegion *iommu_mr = virtio_iommu_mr(s, ep_id);
964     size_t free = VIOMMU_PROBE_SIZE;
965     IOMMUDevice *sdev;
966     ssize_t count;
967 
968     if (!iommu_mr) {
969         return VIRTIO_IOMMU_S_NOENT;
970     }
971 
972     sdev = container_of(iommu_mr, IOMMUDevice, iommu_mr);
973 
974     count = virtio_iommu_fill_resv_mem_prop(sdev, ep_id, buf, free);
975     if (count < 0) {
976         return VIRTIO_IOMMU_S_INVAL;
977     }
978     buf += count;
979     free -= count;
980     sdev->probe_done = true;
981 
982     return VIRTIO_IOMMU_S_OK;
983 }
984 
985 static int virtio_iommu_iov_to_req(struct iovec *iov,
986                                    unsigned int iov_cnt,
987                                    void *req, size_t payload_sz)
988 {
989     size_t sz = iov_to_buf(iov, iov_cnt, 0, req, payload_sz);
990 
991     if (unlikely(sz != payload_sz)) {
992         return VIRTIO_IOMMU_S_INVAL;
993     }
994     return 0;
995 }
996 
997 #define virtio_iommu_handle_req(__req)                                  \
998 static int virtio_iommu_handle_ ## __req(VirtIOIOMMU *s,                \
999                                          struct iovec *iov,             \
1000                                          unsigned int iov_cnt)          \
1001 {                                                                       \
1002     struct virtio_iommu_req_ ## __req req;                              \
1003     int ret = virtio_iommu_iov_to_req(iov, iov_cnt, &req,               \
1004                     sizeof(req) - sizeof(struct virtio_iommu_req_tail));\
1005                                                                         \
1006     return ret ? ret : virtio_iommu_ ## __req(s, &req);                 \
1007 }
1008 
1009 virtio_iommu_handle_req(attach)
1010 virtio_iommu_handle_req(detach)
1011 virtio_iommu_handle_req(map)
1012 virtio_iommu_handle_req(unmap)
1013 
1014 static int virtio_iommu_handle_probe(VirtIOIOMMU *s,
1015                                      struct iovec *iov,
1016                                      unsigned int iov_cnt,
1017                                      uint8_t *buf)
1018 {
1019     struct virtio_iommu_req_probe req;
1020     int ret = virtio_iommu_iov_to_req(iov, iov_cnt, &req, sizeof(req));
1021 
1022     return ret ? ret : virtio_iommu_probe(s, &req, buf);
1023 }
1024 
1025 static void virtio_iommu_handle_command(VirtIODevice *vdev, VirtQueue *vq)
1026 {
1027     VirtIOIOMMU *s = VIRTIO_IOMMU(vdev);
1028     struct virtio_iommu_req_head head;
1029     struct virtio_iommu_req_tail tail = {};
1030     VirtQueueElement *elem;
1031     unsigned int iov_cnt;
1032     struct iovec *iov;
1033     void *buf = NULL;
1034     size_t sz;
1035 
1036     for (;;) {
1037         size_t output_size = sizeof(tail);
1038 
1039         elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
1040         if (!elem) {
1041             return;
1042         }
1043 
1044         if (iov_size(elem->in_sg, elem->in_num) < sizeof(tail) ||
1045             iov_size(elem->out_sg, elem->out_num) < sizeof(head)) {
1046             virtio_error(vdev, "virtio-iommu bad head/tail size");
1047             virtqueue_detach_element(vq, elem, 0);
1048             g_free(elem);
1049             break;
1050         }
1051 
1052         iov_cnt = elem->out_num;
1053         iov = elem->out_sg;
1054         sz = iov_to_buf(iov, iov_cnt, 0, &head, sizeof(head));
1055         if (unlikely(sz != sizeof(head))) {
1056             qemu_log_mask(LOG_GUEST_ERROR,
1057                           "%s: read %zu bytes from command head"
1058                           "but expected %zu\n", __func__, sz, sizeof(head));
1059             tail.status = VIRTIO_IOMMU_S_DEVERR;
1060             goto out;
1061         }
1062         qemu_rec_mutex_lock(&s->mutex);
1063         switch (head.type) {
1064         case VIRTIO_IOMMU_T_ATTACH:
1065             tail.status = virtio_iommu_handle_attach(s, iov, iov_cnt);
1066             break;
1067         case VIRTIO_IOMMU_T_DETACH:
1068             tail.status = virtio_iommu_handle_detach(s, iov, iov_cnt);
1069             break;
1070         case VIRTIO_IOMMU_T_MAP:
1071             tail.status = virtio_iommu_handle_map(s, iov, iov_cnt);
1072             break;
1073         case VIRTIO_IOMMU_T_UNMAP:
1074             tail.status = virtio_iommu_handle_unmap(s, iov, iov_cnt);
1075             break;
1076         case VIRTIO_IOMMU_T_PROBE:
1077         {
1078             struct virtio_iommu_req_tail *ptail;
1079 
1080             output_size = s->config.probe_size + sizeof(tail);
1081             buf = g_malloc0(output_size);
1082 
1083             ptail = buf + s->config.probe_size;
1084             ptail->status = virtio_iommu_handle_probe(s, iov, iov_cnt, buf);
1085             break;
1086         }
1087         default:
1088             tail.status = VIRTIO_IOMMU_S_UNSUPP;
1089         }
1090         qemu_rec_mutex_unlock(&s->mutex);
1091 
1092 out:
1093         sz = iov_from_buf(elem->in_sg, elem->in_num, 0,
1094                           buf ? buf : &tail, output_size);
1095         if (unlikely(sz != output_size)) {
1096             qemu_log_mask(LOG_GUEST_ERROR,
1097                           "%s: wrote %zu bytes to command response"
1098                           "but response size is %zu\n",
1099                           __func__, sz, output_size);
1100             tail.status = VIRTIO_IOMMU_S_DEVERR;
1101             /*
1102              * We checked that sizeof(tail) can fit to elem->in_sg at the
1103              * beginning of the loop
1104              */
1105             output_size = sizeof(tail);
1106             g_free(buf);
1107             buf = NULL;
1108             sz = iov_from_buf(elem->in_sg,
1109                               elem->in_num,
1110                               0,
1111                               &tail,
1112                               output_size);
1113         }
1114         assert(sz == output_size);
1115 
1116         virtqueue_push(vq, elem, sz);
1117         virtio_notify(vdev, vq);
1118         g_free(elem);
1119         g_free(buf);
1120         buf = NULL;
1121     }
1122 }
1123 
1124 static void virtio_iommu_report_fault(VirtIOIOMMU *viommu, uint8_t reason,
1125                                       int flags, uint32_t endpoint,
1126                                       uint64_t address)
1127 {
1128     VirtIODevice *vdev = &viommu->parent_obj;
1129     VirtQueue *vq = viommu->event_vq;
1130     struct virtio_iommu_fault fault;
1131     VirtQueueElement *elem;
1132     size_t sz;
1133 
1134     memset(&fault, 0, sizeof(fault));
1135     fault.reason = reason;
1136     fault.flags = cpu_to_le32(flags);
1137     fault.endpoint = cpu_to_le32(endpoint);
1138     fault.address = cpu_to_le64(address);
1139 
1140     elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
1141 
1142     if (!elem) {
1143         error_report_once(
1144             "no buffer available in event queue to report event");
1145         return;
1146     }
1147 
1148     if (iov_size(elem->in_sg, elem->in_num) < sizeof(fault)) {
1149         virtio_error(vdev, "error buffer of wrong size");
1150         virtqueue_detach_element(vq, elem, 0);
1151         g_free(elem);
1152         return;
1153     }
1154 
1155     sz = iov_from_buf(elem->in_sg, elem->in_num, 0,
1156                       &fault, sizeof(fault));
1157     assert(sz == sizeof(fault));
1158 
1159     trace_virtio_iommu_report_fault(reason, flags, endpoint, address);
1160     virtqueue_push(vq, elem, sz);
1161     virtio_notify(vdev, vq);
1162     g_free(elem);
1163 
1164 }
1165 
1166 static IOMMUTLBEntry virtio_iommu_translate(IOMMUMemoryRegion *mr, hwaddr addr,
1167                                             IOMMUAccessFlags flag,
1168                                             int iommu_idx)
1169 {
1170     IOMMUDevice *sdev = container_of(mr, IOMMUDevice, iommu_mr);
1171     VirtIOIOMMUInterval interval, *mapping_key;
1172     VirtIOIOMMUMapping *mapping_value;
1173     VirtIOIOMMU *s = sdev->viommu;
1174     bool read_fault, write_fault;
1175     VirtIOIOMMUEndpoint *ep;
1176     uint32_t sid, flags;
1177     bool bypass_allowed;
1178     int granule;
1179     bool found;
1180     GList *l;
1181 
1182     interval.low = addr;
1183     interval.high = addr + 1;
1184     granule = ctz64(s->config.page_size_mask);
1185 
1186     IOMMUTLBEntry entry = {
1187         .target_as = &address_space_memory,
1188         .iova = addr,
1189         .translated_addr = addr,
1190         .addr_mask = BIT_ULL(granule) - 1,
1191         .perm = IOMMU_NONE,
1192     };
1193 
1194     bypass_allowed = s->config.bypass;
1195 
1196     sid = virtio_iommu_get_bdf(sdev);
1197 
1198     trace_virtio_iommu_translate(mr->parent_obj.name, sid, addr, flag);
1199     qemu_rec_mutex_lock(&s->mutex);
1200 
1201     ep = g_tree_lookup(s->endpoints, GUINT_TO_POINTER(sid));
1202 
1203     if (bypass_allowed)
1204         assert(ep && ep->domain && !ep->domain->bypass);
1205 
1206     if (!ep) {
1207         if (!bypass_allowed) {
1208             error_report_once("%s sid=%d is not known!!", __func__, sid);
1209             virtio_iommu_report_fault(s, VIRTIO_IOMMU_FAULT_R_UNKNOWN,
1210                                       VIRTIO_IOMMU_FAULT_F_ADDRESS,
1211                                       sid, addr);
1212         } else {
1213             entry.perm = flag;
1214         }
1215         goto unlock;
1216     }
1217 
1218     for (l = sdev->resv_regions; l; l = l->next) {
1219         ReservedRegion *reg = l->data;
1220 
1221         if (range_contains(&reg->range, addr)) {
1222             switch (reg->type) {
1223             case VIRTIO_IOMMU_RESV_MEM_T_MSI:
1224                 entry.perm = flag;
1225                 break;
1226             case VIRTIO_IOMMU_RESV_MEM_T_RESERVED:
1227             default:
1228                 virtio_iommu_report_fault(s, VIRTIO_IOMMU_FAULT_R_MAPPING,
1229                                           VIRTIO_IOMMU_FAULT_F_ADDRESS,
1230                                           sid, addr);
1231                 break;
1232             }
1233             goto unlock;
1234         }
1235     }
1236 
1237     if (!ep->domain) {
1238         if (!bypass_allowed) {
1239             error_report_once("%s %02x:%02x.%01x not attached to any domain",
1240                               __func__, PCI_BUS_NUM(sid),
1241                               PCI_SLOT(sid), PCI_FUNC(sid));
1242             virtio_iommu_report_fault(s, VIRTIO_IOMMU_FAULT_R_DOMAIN,
1243                                       VIRTIO_IOMMU_FAULT_F_ADDRESS,
1244                                       sid, addr);
1245         } else {
1246             entry.perm = flag;
1247         }
1248         goto unlock;
1249     } else if (ep->domain->bypass) {
1250         entry.perm = flag;
1251         goto unlock;
1252     }
1253 
1254     found = g_tree_lookup_extended(ep->domain->mappings, (gpointer)(&interval),
1255                                    (void **)&mapping_key,
1256                                    (void **)&mapping_value);
1257     if (!found) {
1258         error_report_once("%s no mapping for 0x%"PRIx64" for sid=%d",
1259                           __func__, addr, sid);
1260         virtio_iommu_report_fault(s, VIRTIO_IOMMU_FAULT_R_MAPPING,
1261                                   VIRTIO_IOMMU_FAULT_F_ADDRESS,
1262                                   sid, addr);
1263         goto unlock;
1264     }
1265 
1266     read_fault = (flag & IOMMU_RO) &&
1267                     !(mapping_value->flags & VIRTIO_IOMMU_MAP_F_READ);
1268     write_fault = (flag & IOMMU_WO) &&
1269                     !(mapping_value->flags & VIRTIO_IOMMU_MAP_F_WRITE);
1270 
1271     flags = read_fault ? VIRTIO_IOMMU_FAULT_F_READ : 0;
1272     flags |= write_fault ? VIRTIO_IOMMU_FAULT_F_WRITE : 0;
1273     if (flags) {
1274         error_report_once("%s permission error on 0x%"PRIx64"(%d): allowed=%d",
1275                           __func__, addr, flag, mapping_value->flags);
1276         flags |= VIRTIO_IOMMU_FAULT_F_ADDRESS;
1277         virtio_iommu_report_fault(s, VIRTIO_IOMMU_FAULT_R_MAPPING,
1278                                   flags | VIRTIO_IOMMU_FAULT_F_ADDRESS,
1279                                   sid, addr);
1280         goto unlock;
1281     }
1282     entry.translated_addr = addr - mapping_key->low + mapping_value->phys_addr;
1283     entry.perm = flag;
1284     trace_virtio_iommu_translate_out(addr, entry.translated_addr, sid);
1285 
1286 unlock:
1287     qemu_rec_mutex_unlock(&s->mutex);
1288     return entry;
1289 }
1290 
1291 static void virtio_iommu_get_config(VirtIODevice *vdev, uint8_t *config_data)
1292 {
1293     VirtIOIOMMU *dev = VIRTIO_IOMMU(vdev);
1294     struct virtio_iommu_config *dev_config = &dev->config;
1295     struct virtio_iommu_config *out_config = (void *)config_data;
1296 
1297     out_config->page_size_mask = cpu_to_le64(dev_config->page_size_mask);
1298     out_config->input_range.start = cpu_to_le64(dev_config->input_range.start);
1299     out_config->input_range.end = cpu_to_le64(dev_config->input_range.end);
1300     out_config->domain_range.start = cpu_to_le32(dev_config->domain_range.start);
1301     out_config->domain_range.end = cpu_to_le32(dev_config->domain_range.end);
1302     out_config->probe_size = cpu_to_le32(dev_config->probe_size);
1303     out_config->bypass = dev_config->bypass;
1304 
1305     trace_virtio_iommu_get_config(dev_config->page_size_mask,
1306                                   dev_config->input_range.start,
1307                                   dev_config->input_range.end,
1308                                   dev_config->domain_range.start,
1309                                   dev_config->domain_range.end,
1310                                   dev_config->probe_size,
1311                                   dev_config->bypass);
1312 }
1313 
1314 static void virtio_iommu_set_config(VirtIODevice *vdev,
1315                                     const uint8_t *config_data)
1316 {
1317     VirtIOIOMMU *dev = VIRTIO_IOMMU(vdev);
1318     struct virtio_iommu_config *dev_config = &dev->config;
1319     const struct virtio_iommu_config *in_config = (void *)config_data;
1320 
1321     if (in_config->bypass != dev_config->bypass) {
1322         if (!virtio_vdev_has_feature(vdev, VIRTIO_IOMMU_F_BYPASS_CONFIG)) {
1323             virtio_error(vdev, "cannot set config.bypass");
1324             return;
1325         } else if (in_config->bypass != 0 && in_config->bypass != 1) {
1326             virtio_error(vdev, "invalid config.bypass value '%u'",
1327                          in_config->bypass);
1328             return;
1329         }
1330         dev_config->bypass = in_config->bypass;
1331         virtio_iommu_switch_address_space_all(dev);
1332     }
1333 
1334     trace_virtio_iommu_set_config(in_config->bypass);
1335 }
1336 
1337 static uint64_t virtio_iommu_get_features(VirtIODevice *vdev, uint64_t f,
1338                                           Error **errp)
1339 {
1340     VirtIOIOMMU *dev = VIRTIO_IOMMU(vdev);
1341 
1342     f |= dev->features;
1343     trace_virtio_iommu_get_features(f);
1344     return f;
1345 }
1346 
1347 static gint int_cmp(gconstpointer a, gconstpointer b, gpointer user_data)
1348 {
1349     guint ua = GPOINTER_TO_UINT(a);
1350     guint ub = GPOINTER_TO_UINT(b);
1351     return (ua > ub) - (ua < ub);
1352 }
1353 
1354 static gboolean virtio_iommu_remap(gpointer key, gpointer value, gpointer data)
1355 {
1356     VirtIOIOMMUMapping *mapping = (VirtIOIOMMUMapping *) value;
1357     VirtIOIOMMUInterval *interval = (VirtIOIOMMUInterval *) key;
1358     IOMMUMemoryRegion *mr = (IOMMUMemoryRegion *) data;
1359 
1360     trace_virtio_iommu_remap(mr->parent_obj.name, interval->low, interval->high,
1361                              mapping->phys_addr);
1362     virtio_iommu_notify_map(mr, interval->low, interval->high,
1363                             mapping->phys_addr, mapping->flags);
1364     return false;
1365 }
1366 
1367 static void virtio_iommu_replay(IOMMUMemoryRegion *mr, IOMMUNotifier *n)
1368 {
1369     IOMMUDevice *sdev = container_of(mr, IOMMUDevice, iommu_mr);
1370     VirtIOIOMMU *s = sdev->viommu;
1371     uint32_t sid;
1372     VirtIOIOMMUEndpoint *ep;
1373 
1374     sid = virtio_iommu_get_bdf(sdev);
1375 
1376     qemu_rec_mutex_lock(&s->mutex);
1377 
1378     if (!s->endpoints) {
1379         goto unlock;
1380     }
1381 
1382     ep = g_tree_lookup(s->endpoints, GUINT_TO_POINTER(sid));
1383     if (!ep || !ep->domain) {
1384         goto unlock;
1385     }
1386 
1387     g_tree_foreach(ep->domain->mappings, virtio_iommu_remap, mr);
1388 
1389 unlock:
1390     qemu_rec_mutex_unlock(&s->mutex);
1391 }
1392 
1393 static int virtio_iommu_notify_flag_changed(IOMMUMemoryRegion *iommu_mr,
1394                                             IOMMUNotifierFlag old,
1395                                             IOMMUNotifierFlag new,
1396                                             Error **errp)
1397 {
1398     if (new & IOMMU_NOTIFIER_DEVIOTLB_UNMAP) {
1399         error_setg(errp, "Virtio-iommu does not support dev-iotlb yet");
1400         return -EINVAL;
1401     }
1402 
1403     if (old == IOMMU_NOTIFIER_NONE) {
1404         trace_virtio_iommu_notify_flag_add(iommu_mr->parent_obj.name);
1405     } else if (new == IOMMU_NOTIFIER_NONE) {
1406         trace_virtio_iommu_notify_flag_del(iommu_mr->parent_obj.name);
1407     }
1408     return 0;
1409 }
1410 
1411 static void virtio_iommu_system_reset(void *opaque)
1412 {
1413     VirtIOIOMMU *s = opaque;
1414 
1415     trace_virtio_iommu_system_reset();
1416 
1417     memset(s->iommu_pcibus_by_bus_num, 0, sizeof(s->iommu_pcibus_by_bus_num));
1418 
1419     /*
1420      * config.bypass is sticky across device reset, but should be restored on
1421      * system reset
1422      */
1423     s->config.bypass = s->boot_bypass;
1424     virtio_iommu_switch_address_space_all(s);
1425 
1426 }
1427 
1428 static void virtio_iommu_freeze_granule(Notifier *notifier, void *data)
1429 {
1430     VirtIOIOMMU *s = container_of(notifier, VirtIOIOMMU, machine_done);
1431     int granule;
1432 
1433     s->granule_frozen = true;
1434     granule = ctz64(s->config.page_size_mask);
1435     trace_virtio_iommu_freeze_granule(BIT_ULL(granule));
1436 }
1437 
1438 static void virtio_iommu_device_realize(DeviceState *dev, Error **errp)
1439 {
1440     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1441     VirtIOIOMMU *s = VIRTIO_IOMMU(dev);
1442 
1443     virtio_init(vdev, VIRTIO_ID_IOMMU, sizeof(struct virtio_iommu_config));
1444 
1445     s->req_vq = virtio_add_queue(vdev, VIOMMU_DEFAULT_QUEUE_SIZE,
1446                              virtio_iommu_handle_command);
1447     s->event_vq = virtio_add_queue(vdev, VIOMMU_DEFAULT_QUEUE_SIZE, NULL);
1448 
1449     /*
1450      * config.bypass is needed to get initial address space early, such as
1451      * in vfio realize
1452      */
1453     s->config.bypass = s->boot_bypass;
1454     if (s->aw_bits < 32 || s->aw_bits > 64) {
1455         error_setg(errp, "aw-bits must be within [32,64]");
1456         return;
1457     }
1458     s->config.input_range.end =
1459         s->aw_bits == 64 ? UINT64_MAX : BIT_ULL(s->aw_bits) - 1;
1460 
1461     switch (s->granule_mode) {
1462     case GRANULE_MODE_4K:
1463         s->config.page_size_mask = -(4 * KiB);
1464         break;
1465     case GRANULE_MODE_8K:
1466         s->config.page_size_mask = -(8 * KiB);
1467         break;
1468     case GRANULE_MODE_16K:
1469         s->config.page_size_mask = -(16 * KiB);
1470         break;
1471     case GRANULE_MODE_64K:
1472         s->config.page_size_mask = -(64 * KiB);
1473         break;
1474     case GRANULE_MODE_HOST:
1475         s->config.page_size_mask = qemu_real_host_page_mask();
1476         break;
1477     default:
1478         error_setg(errp, "Unsupported granule mode");
1479     }
1480     s->config.domain_range.end = UINT32_MAX;
1481     s->config.probe_size = VIOMMU_PROBE_SIZE;
1482 
1483     virtio_add_feature(&s->features, VIRTIO_RING_F_EVENT_IDX);
1484     virtio_add_feature(&s->features, VIRTIO_RING_F_INDIRECT_DESC);
1485     virtio_add_feature(&s->features, VIRTIO_F_VERSION_1);
1486     virtio_add_feature(&s->features, VIRTIO_IOMMU_F_INPUT_RANGE);
1487     virtio_add_feature(&s->features, VIRTIO_IOMMU_F_DOMAIN_RANGE);
1488     virtio_add_feature(&s->features, VIRTIO_IOMMU_F_MAP_UNMAP);
1489     virtio_add_feature(&s->features, VIRTIO_IOMMU_F_MMIO);
1490     virtio_add_feature(&s->features, VIRTIO_IOMMU_F_PROBE);
1491     virtio_add_feature(&s->features, VIRTIO_IOMMU_F_BYPASS_CONFIG);
1492 
1493     qemu_rec_mutex_init(&s->mutex);
1494 
1495     s->as_by_busptr = g_hash_table_new_full(NULL, NULL, NULL, g_free);
1496 
1497     s->host_iommu_devices = g_hash_table_new_full(hiod_hash, hiod_equal,
1498                                                   g_free, hiod_destroy);
1499 
1500     if (s->primary_bus) {
1501         pci_setup_iommu(s->primary_bus, &virtio_iommu_ops, s);
1502     } else {
1503         error_setg(errp, "VIRTIO-IOMMU is not attached to any PCI bus!");
1504     }
1505 
1506     s->machine_done.notify = virtio_iommu_freeze_granule;
1507     qemu_add_machine_init_done_notifier(&s->machine_done);
1508 
1509     qemu_register_reset(virtio_iommu_system_reset, s);
1510 }
1511 
1512 static void virtio_iommu_device_unrealize(DeviceState *dev)
1513 {
1514     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1515     VirtIOIOMMU *s = VIRTIO_IOMMU(dev);
1516 
1517     qemu_unregister_reset(virtio_iommu_system_reset, s);
1518     qemu_remove_machine_init_done_notifier(&s->machine_done);
1519 
1520     g_hash_table_destroy(s->as_by_busptr);
1521     if (s->domains) {
1522         g_tree_destroy(s->domains);
1523     }
1524     if (s->endpoints) {
1525         g_tree_destroy(s->endpoints);
1526     }
1527 
1528     qemu_rec_mutex_destroy(&s->mutex);
1529 
1530     virtio_delete_queue(s->req_vq);
1531     virtio_delete_queue(s->event_vq);
1532     virtio_cleanup(vdev);
1533 }
1534 
1535 static void virtio_iommu_device_reset(VirtIODevice *vdev)
1536 {
1537     VirtIOIOMMU *s = VIRTIO_IOMMU(vdev);
1538 
1539     trace_virtio_iommu_device_reset();
1540 
1541     if (s->domains) {
1542         g_tree_destroy(s->domains);
1543     }
1544     if (s->endpoints) {
1545         g_tree_destroy(s->endpoints);
1546     }
1547     s->domains = g_tree_new_full((GCompareDataFunc)int_cmp,
1548                                  NULL, NULL, virtio_iommu_put_domain);
1549     s->endpoints = g_tree_new_full((GCompareDataFunc)int_cmp,
1550                                    NULL, NULL, virtio_iommu_put_endpoint);
1551 }
1552 
1553 static void virtio_iommu_set_status(VirtIODevice *vdev, uint8_t status)
1554 {
1555     trace_virtio_iommu_device_status(status);
1556 }
1557 
1558 static void virtio_iommu_instance_init(Object *obj)
1559 {
1560 }
1561 
1562 #define VMSTATE_INTERVAL                               \
1563 {                                                      \
1564     .name = "interval",                                \
1565     .version_id = 1,                                   \
1566     .minimum_version_id = 1,                           \
1567     .fields = (const VMStateField[]) {                 \
1568         VMSTATE_UINT64(low, VirtIOIOMMUInterval),      \
1569         VMSTATE_UINT64(high, VirtIOIOMMUInterval),     \
1570         VMSTATE_END_OF_LIST()                          \
1571     }                                                  \
1572 }
1573 
1574 #define VMSTATE_MAPPING                               \
1575 {                                                     \
1576     .name = "mapping",                                \
1577     .version_id = 1,                                  \
1578     .minimum_version_id = 1,                          \
1579     .fields = (const VMStateField[]) {                \
1580         VMSTATE_UINT64(phys_addr, VirtIOIOMMUMapping),\
1581         VMSTATE_UINT32(flags, VirtIOIOMMUMapping),    \
1582         VMSTATE_END_OF_LIST()                         \
1583     },                                                \
1584 }
1585 
1586 static const VMStateDescription vmstate_interval_mapping[2] = {
1587     VMSTATE_MAPPING,   /* value */
1588     VMSTATE_INTERVAL   /* key   */
1589 };
1590 
1591 static int domain_preload(void *opaque)
1592 {
1593     VirtIOIOMMUDomain *domain = opaque;
1594 
1595     domain->mappings = g_tree_new_full((GCompareDataFunc)interval_cmp,
1596                                        NULL, g_free, g_free);
1597     return 0;
1598 }
1599 
1600 static const VMStateDescription vmstate_endpoint = {
1601     .name = "endpoint",
1602     .version_id = 1,
1603     .minimum_version_id = 1,
1604     .fields = (const VMStateField[]) {
1605         VMSTATE_UINT32(id, VirtIOIOMMUEndpoint),
1606         VMSTATE_END_OF_LIST()
1607     }
1608 };
1609 
1610 static const VMStateDescription vmstate_domain = {
1611     .name = "domain",
1612     .version_id = 2,
1613     .minimum_version_id = 2,
1614     .pre_load = domain_preload,
1615     .fields = (const VMStateField[]) {
1616         VMSTATE_UINT32(id, VirtIOIOMMUDomain),
1617         VMSTATE_GTREE_V(mappings, VirtIOIOMMUDomain, 1,
1618                         vmstate_interval_mapping,
1619                         VirtIOIOMMUInterval, VirtIOIOMMUMapping),
1620         VMSTATE_QLIST_V(endpoint_list, VirtIOIOMMUDomain, 1,
1621                         vmstate_endpoint, VirtIOIOMMUEndpoint, next),
1622         VMSTATE_BOOL_V(bypass, VirtIOIOMMUDomain, 2),
1623         VMSTATE_END_OF_LIST()
1624     }
1625 };
1626 
1627 static gboolean reconstruct_endpoints(gpointer key, gpointer value,
1628                                       gpointer data)
1629 {
1630     VirtIOIOMMU *s = (VirtIOIOMMU *)data;
1631     VirtIOIOMMUDomain *d = (VirtIOIOMMUDomain *)value;
1632     VirtIOIOMMUEndpoint *iter;
1633     IOMMUMemoryRegion *mr;
1634 
1635     QLIST_FOREACH(iter, &d->endpoint_list, next) {
1636         mr = virtio_iommu_mr(s, iter->id);
1637         assert(mr);
1638 
1639         iter->domain = d;
1640         iter->iommu_mr = mr;
1641         g_tree_insert(s->endpoints, GUINT_TO_POINTER(iter->id), iter);
1642     }
1643     return false; /* continue the domain traversal */
1644 }
1645 
1646 static int iommu_post_load(void *opaque, int version_id)
1647 {
1648     VirtIOIOMMU *s = opaque;
1649 
1650     g_tree_foreach(s->domains, reconstruct_endpoints, s);
1651 
1652     /*
1653      * Memory regions are dynamically turned on/off depending on
1654      * 'config.bypass' and attached domain type if there is. After
1655      * migration, we need to make sure the memory regions are
1656      * still correct.
1657      */
1658     virtio_iommu_switch_address_space_all(s);
1659     return 0;
1660 }
1661 
1662 static const VMStateDescription vmstate_virtio_iommu_device = {
1663     .name = "virtio-iommu-device",
1664     .minimum_version_id = 2,
1665     .version_id = 2,
1666     .post_load = iommu_post_load,
1667     .fields = (const VMStateField[]) {
1668         VMSTATE_GTREE_DIRECT_KEY_V(domains, VirtIOIOMMU, 2,
1669                                    &vmstate_domain, VirtIOIOMMUDomain),
1670         VMSTATE_UINT8_V(config.bypass, VirtIOIOMMU, 2),
1671         VMSTATE_END_OF_LIST()
1672     },
1673 };
1674 
1675 static const VMStateDescription vmstate_virtio_iommu = {
1676     .name = "virtio-iommu",
1677     .minimum_version_id = 2,
1678     .priority = MIG_PRI_IOMMU,
1679     .version_id = 2,
1680     .fields = (const VMStateField[]) {
1681         VMSTATE_VIRTIO_DEVICE,
1682         VMSTATE_END_OF_LIST()
1683     },
1684 };
1685 
1686 static Property virtio_iommu_properties[] = {
1687     DEFINE_PROP_LINK("primary-bus", VirtIOIOMMU, primary_bus,
1688                      TYPE_PCI_BUS, PCIBus *),
1689     DEFINE_PROP_BOOL("boot-bypass", VirtIOIOMMU, boot_bypass, true),
1690     DEFINE_PROP_GRANULE_MODE("granule", VirtIOIOMMU, granule_mode,
1691                              GRANULE_MODE_HOST),
1692     DEFINE_PROP_UINT8("aw-bits", VirtIOIOMMU, aw_bits, 64),
1693     DEFINE_PROP_END_OF_LIST(),
1694 };
1695 
1696 static void virtio_iommu_class_init(ObjectClass *klass, void *data)
1697 {
1698     DeviceClass *dc = DEVICE_CLASS(klass);
1699     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1700 
1701     device_class_set_props(dc, virtio_iommu_properties);
1702     dc->vmsd = &vmstate_virtio_iommu;
1703 
1704     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
1705     vdc->realize = virtio_iommu_device_realize;
1706     vdc->unrealize = virtio_iommu_device_unrealize;
1707     vdc->reset = virtio_iommu_device_reset;
1708     vdc->get_config = virtio_iommu_get_config;
1709     vdc->set_config = virtio_iommu_set_config;
1710     vdc->get_features = virtio_iommu_get_features;
1711     vdc->set_status = virtio_iommu_set_status;
1712     vdc->vmsd = &vmstate_virtio_iommu_device;
1713 }
1714 
1715 static void virtio_iommu_memory_region_class_init(ObjectClass *klass,
1716                                                   void *data)
1717 {
1718     IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_CLASS(klass);
1719 
1720     imrc->translate = virtio_iommu_translate;
1721     imrc->replay = virtio_iommu_replay;
1722     imrc->notify_flag_changed = virtio_iommu_notify_flag_changed;
1723 }
1724 
1725 static const TypeInfo virtio_iommu_info = {
1726     .name = TYPE_VIRTIO_IOMMU,
1727     .parent = TYPE_VIRTIO_DEVICE,
1728     .instance_size = sizeof(VirtIOIOMMU),
1729     .instance_init = virtio_iommu_instance_init,
1730     .class_init = virtio_iommu_class_init,
1731 };
1732 
1733 static const TypeInfo virtio_iommu_memory_region_info = {
1734     .parent = TYPE_IOMMU_MEMORY_REGION,
1735     .name = TYPE_VIRTIO_IOMMU_MEMORY_REGION,
1736     .class_init = virtio_iommu_memory_region_class_init,
1737 };
1738 
1739 static void virtio_register_types(void)
1740 {
1741     type_register_static(&virtio_iommu_info);
1742     type_register_static(&virtio_iommu_memory_region_info);
1743 }
1744 
1745 type_init(virtio_register_types)
1746