xref: /openbmc/qemu/hw/i386/intel_iommu.c (revision 0d70c5aa1bbfb0f5099d53d6e084337a8246cc0c)
1 /*
2  * QEMU emulation of an Intel IOMMU (VT-d)
3  *   (DMA Remapping device)
4  *
5  * Copyright (C) 2013 Knut Omang, Oracle <knut.omang@oracle.com>
6  * Copyright (C) 2014 Le Tan, <tamlokveer@gmail.com>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12 
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17 
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, see <http://www.gnu.org/licenses/>.
20  */
21 
22 #include "qemu/osdep.h"
23 #include "qemu/error-report.h"
24 #include "qemu/main-loop.h"
25 #include "qapi/error.h"
26 #include "hw/sysbus.h"
27 #include "intel_iommu_internal.h"
28 #include "hw/pci/pci.h"
29 #include "hw/pci/pci_bus.h"
30 #include "hw/qdev-properties.h"
31 #include "hw/i386/pc.h"
32 #include "hw/i386/apic-msidef.h"
33 #include "hw/i386/x86-iommu.h"
34 #include "hw/pci-host/q35.h"
35 #include "system/kvm.h"
36 #include "system/dma.h"
37 #include "system/system.h"
38 #include "hw/i386/apic_internal.h"
39 #include "kvm/kvm_i386.h"
40 #include "migration/vmstate.h"
41 #include "trace.h"
42 
43 /* context entry operations */
44 #define VTD_CE_GET_RID2PASID(ce) \
45     ((ce)->val[1] & VTD_SM_CONTEXT_ENTRY_RID2PASID_MASK)
46 #define VTD_CE_GET_PASID_DIR_TABLE(ce) \
47     ((ce)->val[0] & VTD_PASID_DIR_BASE_ADDR_MASK)
48 
49 /* pe operations */
50 #define VTD_PE_GET_TYPE(pe) ((pe)->val[0] & VTD_SM_PASID_ENTRY_PGTT)
51 #define VTD_PE_GET_FL_LEVEL(pe) \
52     (4 + (((pe)->val[2] >> 2) & VTD_SM_PASID_ENTRY_FLPM))
53 #define VTD_PE_GET_SL_LEVEL(pe) \
54     (2 + (((pe)->val[0] >> 2) & VTD_SM_PASID_ENTRY_AW))
55 
56 /*
57  * PCI bus number (or SID) is not reliable since the device is usaully
58  * initialized before guest can configure the PCI bridge
59  * (SECONDARY_BUS_NUMBER).
60  */
61 struct vtd_as_key {
62     PCIBus *bus;
63     uint8_t devfn;
64     uint32_t pasid;
65 };
66 
67 /* bus/devfn is PCI device's real BDF not the aliased one */
68 struct vtd_hiod_key {
69     PCIBus *bus;
70     uint8_t devfn;
71 };
72 
73 struct vtd_as_raw_key {
74     uint16_t sid;
75     uint32_t pasid;
76 };
77 
78 struct vtd_iotlb_key {
79     uint64_t gfn;
80     uint32_t pasid;
81     uint16_t sid;
82     uint8_t level;
83 };
84 
85 static void vtd_address_space_refresh_all(IntelIOMMUState *s);
86 static void vtd_address_space_unmap(VTDAddressSpace *as, IOMMUNotifier *n);
87 
88 static void vtd_panic_require_caching_mode(void)
89 {
90     error_report("We need to set caching-mode=on for intel-iommu to enable "
91                  "device assignment with IOMMU protection.");
92     exit(1);
93 }
94 
95 static void vtd_define_quad(IntelIOMMUState *s, hwaddr addr, uint64_t val,
96                             uint64_t wmask, uint64_t w1cmask)
97 {
98     stq_le_p(&s->csr[addr], val);
99     stq_le_p(&s->wmask[addr], wmask);
100     stq_le_p(&s->w1cmask[addr], w1cmask);
101 }
102 
103 static void vtd_define_quad_wo(IntelIOMMUState *s, hwaddr addr, uint64_t mask)
104 {
105     stq_le_p(&s->womask[addr], mask);
106 }
107 
108 static void vtd_define_long(IntelIOMMUState *s, hwaddr addr, uint32_t val,
109                             uint32_t wmask, uint32_t w1cmask)
110 {
111     stl_le_p(&s->csr[addr], val);
112     stl_le_p(&s->wmask[addr], wmask);
113     stl_le_p(&s->w1cmask[addr], w1cmask);
114 }
115 
116 static void vtd_define_long_wo(IntelIOMMUState *s, hwaddr addr, uint32_t mask)
117 {
118     stl_le_p(&s->womask[addr], mask);
119 }
120 
121 /* "External" get/set operations */
122 static void vtd_set_quad(IntelIOMMUState *s, hwaddr addr, uint64_t val)
123 {
124     uint64_t oldval = ldq_le_p(&s->csr[addr]);
125     uint64_t wmask = ldq_le_p(&s->wmask[addr]);
126     uint64_t w1cmask = ldq_le_p(&s->w1cmask[addr]);
127     stq_le_p(&s->csr[addr],
128              ((oldval & ~wmask) | (val & wmask)) & ~(w1cmask & val));
129 }
130 
131 static void vtd_set_long(IntelIOMMUState *s, hwaddr addr, uint32_t val)
132 {
133     uint32_t oldval = ldl_le_p(&s->csr[addr]);
134     uint32_t wmask = ldl_le_p(&s->wmask[addr]);
135     uint32_t w1cmask = ldl_le_p(&s->w1cmask[addr]);
136     stl_le_p(&s->csr[addr],
137              ((oldval & ~wmask) | (val & wmask)) & ~(w1cmask & val));
138 }
139 
140 static uint64_t vtd_get_quad(IntelIOMMUState *s, hwaddr addr)
141 {
142     uint64_t val = ldq_le_p(&s->csr[addr]);
143     uint64_t womask = ldq_le_p(&s->womask[addr]);
144     return val & ~womask;
145 }
146 
147 static uint32_t vtd_get_long(IntelIOMMUState *s, hwaddr addr)
148 {
149     uint32_t val = ldl_le_p(&s->csr[addr]);
150     uint32_t womask = ldl_le_p(&s->womask[addr]);
151     return val & ~womask;
152 }
153 
154 /* "Internal" get/set operations */
155 static uint64_t vtd_get_quad_raw(IntelIOMMUState *s, hwaddr addr)
156 {
157     return ldq_le_p(&s->csr[addr]);
158 }
159 
160 static uint32_t vtd_get_long_raw(IntelIOMMUState *s, hwaddr addr)
161 {
162     return ldl_le_p(&s->csr[addr]);
163 }
164 
165 static void vtd_set_quad_raw(IntelIOMMUState *s, hwaddr addr, uint64_t val)
166 {
167     stq_le_p(&s->csr[addr], val);
168 }
169 
170 static uint32_t vtd_set_clear_mask_long(IntelIOMMUState *s, hwaddr addr,
171                                         uint32_t clear, uint32_t mask)
172 {
173     uint32_t new_val = (ldl_le_p(&s->csr[addr]) & ~clear) | mask;
174     stl_le_p(&s->csr[addr], new_val);
175     return new_val;
176 }
177 
178 static uint64_t vtd_set_clear_mask_quad(IntelIOMMUState *s, hwaddr addr,
179                                         uint64_t clear, uint64_t mask)
180 {
181     uint64_t new_val = (ldq_le_p(&s->csr[addr]) & ~clear) | mask;
182     stq_le_p(&s->csr[addr], new_val);
183     return new_val;
184 }
185 
186 static inline void vtd_iommu_lock(IntelIOMMUState *s)
187 {
188     qemu_mutex_lock(&s->iommu_lock);
189 }
190 
191 static inline void vtd_iommu_unlock(IntelIOMMUState *s)
192 {
193     qemu_mutex_unlock(&s->iommu_lock);
194 }
195 
196 static void vtd_update_scalable_state(IntelIOMMUState *s)
197 {
198     uint64_t val = vtd_get_quad_raw(s, DMAR_RTADDR_REG);
199 
200     if (s->scalable_mode) {
201         s->root_scalable = val & VTD_RTADDR_SMT;
202     }
203 }
204 
205 static void vtd_update_iq_dw(IntelIOMMUState *s)
206 {
207     uint64_t val = vtd_get_quad_raw(s, DMAR_IQA_REG);
208 
209     if (s->ecap & VTD_ECAP_SMTS &&
210         val & VTD_IQA_DW_MASK) {
211         s->iq_dw = true;
212     } else {
213         s->iq_dw = false;
214     }
215 }
216 
217 /* Whether the address space needs to notify new mappings */
218 static inline gboolean vtd_as_has_map_notifier(VTDAddressSpace *as)
219 {
220     return as->notifier_flags & IOMMU_NOTIFIER_MAP;
221 }
222 
223 /* GHashTable functions */
224 static gboolean vtd_iotlb_equal(gconstpointer v1, gconstpointer v2)
225 {
226     const struct vtd_iotlb_key *key1 = v1;
227     const struct vtd_iotlb_key *key2 = v2;
228 
229     return key1->sid == key2->sid &&
230            key1->pasid == key2->pasid &&
231            key1->level == key2->level &&
232            key1->gfn == key2->gfn;
233 }
234 
235 static guint vtd_iotlb_hash(gconstpointer v)
236 {
237     const struct vtd_iotlb_key *key = v;
238     uint64_t hash64 = key->gfn | ((uint64_t)(key->sid) << VTD_IOTLB_SID_SHIFT) |
239         (uint64_t)(key->level - 1) << VTD_IOTLB_LVL_SHIFT |
240         (uint64_t)(key->pasid) << VTD_IOTLB_PASID_SHIFT;
241 
242     return (guint)((hash64 >> 32) ^ (hash64 & 0xffffffffU));
243 }
244 
245 static gboolean vtd_as_equal(gconstpointer v1, gconstpointer v2)
246 {
247     const struct vtd_as_key *key1 = v1;
248     const struct vtd_as_key *key2 = v2;
249 
250     return (key1->bus == key2->bus) && (key1->devfn == key2->devfn) &&
251            (key1->pasid == key2->pasid);
252 }
253 
254 /*
255  * Note that we use pointer to PCIBus as the key, so hashing/shifting
256  * based on the pointer value is intended. Note that we deal with
257  * collisions through vtd_as_equal().
258  */
259 static guint vtd_as_hash(gconstpointer v)
260 {
261     const struct vtd_as_key *key = v;
262     guint value = (guint)(uintptr_t)key->bus;
263 
264     return (guint)(value << 8 | key->devfn);
265 }
266 
267 /* Same implementation as vtd_as_hash() */
268 static guint vtd_hiod_hash(gconstpointer v)
269 {
270     return vtd_as_hash(v);
271 }
272 
273 static gboolean vtd_hiod_equal(gconstpointer v1, gconstpointer v2)
274 {
275     const struct vtd_hiod_key *key1 = v1;
276     const struct vtd_hiod_key *key2 = v2;
277 
278     return (key1->bus == key2->bus) && (key1->devfn == key2->devfn);
279 }
280 
281 static void vtd_hiod_destroy(gpointer v)
282 {
283     object_unref(v);
284 }
285 
286 static gboolean vtd_hash_remove_by_domain(gpointer key, gpointer value,
287                                           gpointer user_data)
288 {
289     VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value;
290     uint16_t domain_id = *(uint16_t *)user_data;
291     return entry->domain_id == domain_id;
292 }
293 
294 /* The shift of an addr for a certain level of paging structure */
295 static inline uint32_t vtd_pt_level_shift(uint32_t level)
296 {
297     assert(level != 0);
298     return VTD_PAGE_SHIFT_4K + (level - 1) * VTD_LEVEL_BITS;
299 }
300 
301 static inline uint64_t vtd_pt_level_page_mask(uint32_t level)
302 {
303     return ~((1ULL << vtd_pt_level_shift(level)) - 1);
304 }
305 
306 static gboolean vtd_hash_remove_by_page(gpointer key, gpointer value,
307                                         gpointer user_data)
308 {
309     VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value;
310     VTDIOTLBPageInvInfo *info = (VTDIOTLBPageInvInfo *)user_data;
311     uint64_t gfn = (info->addr >> VTD_PAGE_SHIFT_4K) & info->mask;
312     uint64_t gfn_tlb = (info->addr & entry->mask) >> VTD_PAGE_SHIFT_4K;
313 
314     if (entry->domain_id != info->domain_id) {
315         return false;
316     }
317 
318     /*
319      * According to spec, IOTLB entries caching first-stage (PGTT=001b) or
320      * nested (PGTT=011b) mapping associated with specified domain-id are
321      * invalidated. Nested isn't supported yet, so only need to check 001b.
322      */
323     if (entry->pgtt == VTD_SM_PASID_ENTRY_FLT) {
324         return true;
325     }
326 
327     return (entry->gfn & info->mask) == gfn || entry->gfn == gfn_tlb;
328 }
329 
330 static gboolean vtd_hash_remove_by_page_piotlb(gpointer key, gpointer value,
331                                                gpointer user_data)
332 {
333     VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value;
334     VTDIOTLBPageInvInfo *info = (VTDIOTLBPageInvInfo *)user_data;
335     uint64_t gfn = (info->addr >> VTD_PAGE_SHIFT_4K) & info->mask;
336     uint64_t gfn_tlb = (info->addr & entry->mask) >> VTD_PAGE_SHIFT_4K;
337 
338     /*
339      * According to spec, PASID-based-IOTLB Invalidation in page granularity
340      * doesn't invalidate IOTLB entries caching second-stage (PGTT=010b)
341      * or pass-through (PGTT=100b) mappings. Nested isn't supported yet,
342      * so only need to check first-stage (PGTT=001b) mappings.
343      */
344     if (entry->pgtt != VTD_SM_PASID_ENTRY_FLT) {
345         return false;
346     }
347 
348     return entry->domain_id == info->domain_id && entry->pasid == info->pasid &&
349            ((entry->gfn & info->mask) == gfn || entry->gfn == gfn_tlb);
350 }
351 
352 /* Reset all the gen of VTDAddressSpace to zero and set the gen of
353  * IntelIOMMUState to 1.  Must be called with IOMMU lock held.
354  */
355 static void vtd_reset_context_cache_locked(IntelIOMMUState *s)
356 {
357     VTDAddressSpace *vtd_as;
358     GHashTableIter as_it;
359 
360     trace_vtd_context_cache_reset();
361 
362     g_hash_table_iter_init(&as_it, s->vtd_address_spaces);
363 
364     while (g_hash_table_iter_next(&as_it, NULL, (void **)&vtd_as)) {
365         vtd_as->context_cache_entry.context_cache_gen = 0;
366     }
367     s->context_cache_gen = 1;
368 }
369 
370 /* Must be called with IOMMU lock held. */
371 static void vtd_reset_iotlb_locked(IntelIOMMUState *s)
372 {
373     assert(s->iotlb);
374     g_hash_table_remove_all(s->iotlb);
375 }
376 
377 static void vtd_reset_iotlb(IntelIOMMUState *s)
378 {
379     vtd_iommu_lock(s);
380     vtd_reset_iotlb_locked(s);
381     vtd_iommu_unlock(s);
382 }
383 
384 static void vtd_reset_caches(IntelIOMMUState *s)
385 {
386     vtd_iommu_lock(s);
387     vtd_reset_iotlb_locked(s);
388     vtd_reset_context_cache_locked(s);
389     vtd_iommu_unlock(s);
390 }
391 
392 static uint64_t vtd_get_iotlb_gfn(hwaddr addr, uint32_t level)
393 {
394     return (addr & vtd_pt_level_page_mask(level)) >> VTD_PAGE_SHIFT_4K;
395 }
396 
397 /* Must be called with IOMMU lock held */
398 static VTDIOTLBEntry *vtd_lookup_iotlb(IntelIOMMUState *s, uint16_t source_id,
399                                        uint32_t pasid, hwaddr addr)
400 {
401     struct vtd_iotlb_key key;
402     VTDIOTLBEntry *entry;
403     unsigned level;
404 
405     for (level = VTD_PT_LEVEL; level < VTD_PML4_LEVEL; level++) {
406         key.gfn = vtd_get_iotlb_gfn(addr, level);
407         key.level = level;
408         key.sid = source_id;
409         key.pasid = pasid;
410         entry = g_hash_table_lookup(s->iotlb, &key);
411         if (entry) {
412             goto out;
413         }
414     }
415 
416 out:
417     return entry;
418 }
419 
420 /* Must be with IOMMU lock held */
421 static void vtd_update_iotlb(IntelIOMMUState *s, uint16_t source_id,
422                              uint16_t domain_id, hwaddr addr, uint64_t pte,
423                              uint8_t access_flags, uint32_t level,
424                              uint32_t pasid, uint8_t pgtt)
425 {
426     VTDIOTLBEntry *entry = g_malloc(sizeof(*entry));
427     struct vtd_iotlb_key *key = g_malloc(sizeof(*key));
428     uint64_t gfn = vtd_get_iotlb_gfn(addr, level);
429 
430     trace_vtd_iotlb_page_update(source_id, addr, pte, domain_id);
431     if (g_hash_table_size(s->iotlb) >= VTD_IOTLB_MAX_SIZE) {
432         trace_vtd_iotlb_reset("iotlb exceeds size limit");
433         vtd_reset_iotlb_locked(s);
434     }
435 
436     entry->gfn = gfn;
437     entry->domain_id = domain_id;
438     entry->pte = pte;
439     entry->access_flags = access_flags;
440     entry->mask = vtd_pt_level_page_mask(level);
441     entry->pasid = pasid;
442     entry->pgtt = pgtt;
443 
444     key->gfn = gfn;
445     key->sid = source_id;
446     key->level = level;
447     key->pasid = pasid;
448 
449     g_hash_table_replace(s->iotlb, key, entry);
450 }
451 
452 /* Given the reg addr of both the message data and address, generate an
453  * interrupt via MSI.
454  */
455 static void vtd_generate_interrupt(IntelIOMMUState *s, hwaddr mesg_addr_reg,
456                                    hwaddr mesg_data_reg)
457 {
458     MSIMessage msi;
459 
460     assert(mesg_data_reg < DMAR_REG_SIZE);
461     assert(mesg_addr_reg < DMAR_REG_SIZE);
462 
463     msi.address = vtd_get_long_raw(s, mesg_addr_reg);
464     msi.data = vtd_get_long_raw(s, mesg_data_reg);
465 
466     trace_vtd_irq_generate(msi.address, msi.data);
467 
468     apic_get_class(NULL)->send_msi(&msi);
469 }
470 
471 /* Generate a fault event to software via MSI if conditions are met.
472  * Notice that the value of FSTS_REG being passed to it should be the one
473  * before any update.
474  */
475 static void vtd_generate_fault_event(IntelIOMMUState *s, uint32_t pre_fsts)
476 {
477     if (pre_fsts & VTD_FSTS_PPF || pre_fsts & VTD_FSTS_PFO ||
478         pre_fsts & VTD_FSTS_IQE) {
479         error_report_once("There are previous interrupt conditions "
480                           "to be serviced by software, fault event "
481                           "is not generated");
482         return;
483     }
484     vtd_set_clear_mask_long(s, DMAR_FECTL_REG, 0, VTD_FECTL_IP);
485     if (vtd_get_long_raw(s, DMAR_FECTL_REG) & VTD_FECTL_IM) {
486         error_report_once("Interrupt Mask set, irq is not generated");
487     } else {
488         vtd_generate_interrupt(s, DMAR_FEADDR_REG, DMAR_FEDATA_REG);
489         vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
490     }
491 }
492 
493 /* Check if the Fault (F) field of the Fault Recording Register referenced by
494  * @index is Set.
495  */
496 static bool vtd_is_frcd_set(IntelIOMMUState *s, uint16_t index)
497 {
498     /* Each reg is 128-bit */
499     hwaddr addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
500     addr += 8; /* Access the high 64-bit half */
501 
502     assert(index < DMAR_FRCD_REG_NR);
503 
504     return vtd_get_quad_raw(s, addr) & VTD_FRCD_F;
505 }
506 
507 /* Update the PPF field of Fault Status Register.
508  * Should be called whenever change the F field of any fault recording
509  * registers.
510  */
511 static void vtd_update_fsts_ppf(IntelIOMMUState *s)
512 {
513     uint32_t i;
514     uint32_t ppf_mask = 0;
515 
516     for (i = 0; i < DMAR_FRCD_REG_NR; i++) {
517         if (vtd_is_frcd_set(s, i)) {
518             ppf_mask = VTD_FSTS_PPF;
519             break;
520         }
521     }
522     vtd_set_clear_mask_long(s, DMAR_FSTS_REG, VTD_FSTS_PPF, ppf_mask);
523     trace_vtd_fsts_ppf(!!ppf_mask);
524 }
525 
526 static void vtd_set_frcd_and_update_ppf(IntelIOMMUState *s, uint16_t index)
527 {
528     /* Each reg is 128-bit */
529     hwaddr addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
530     addr += 8; /* Access the high 64-bit half */
531 
532     assert(index < DMAR_FRCD_REG_NR);
533 
534     vtd_set_clear_mask_quad(s, addr, 0, VTD_FRCD_F);
535     vtd_update_fsts_ppf(s);
536 }
537 
538 /* Must not update F field now, should be done later */
539 static void vtd_record_frcd(IntelIOMMUState *s, uint16_t index,
540                             uint64_t hi, uint64_t lo)
541 {
542     hwaddr frcd_reg_addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
543 
544     assert(index < DMAR_FRCD_REG_NR);
545 
546     vtd_set_quad_raw(s, frcd_reg_addr, lo);
547     vtd_set_quad_raw(s, frcd_reg_addr + 8, hi);
548 
549     trace_vtd_frr_new(index, hi, lo);
550 }
551 
552 /* Try to collapse multiple pending faults from the same requester */
553 static bool vtd_try_collapse_fault(IntelIOMMUState *s, uint16_t source_id)
554 {
555     uint32_t i;
556     uint64_t frcd_reg;
557     hwaddr addr = DMAR_FRCD_REG_OFFSET + 8; /* The high 64-bit half */
558 
559     for (i = 0; i < DMAR_FRCD_REG_NR; i++) {
560         frcd_reg = vtd_get_quad_raw(s, addr);
561         if ((frcd_reg & VTD_FRCD_F) &&
562             ((frcd_reg & VTD_FRCD_SID_MASK) == source_id)) {
563             return true;
564         }
565         addr += 16; /* 128-bit for each */
566     }
567     return false;
568 }
569 
570 /* Log and report an DMAR (address translation) fault to software */
571 static void vtd_report_frcd_fault(IntelIOMMUState *s, uint64_t source_id,
572                                   uint64_t hi, uint64_t lo)
573 {
574     uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
575 
576     if (fsts_reg & VTD_FSTS_PFO) {
577         error_report_once("New fault is not recorded due to "
578                           "Primary Fault Overflow");
579         return;
580     }
581 
582     if (vtd_try_collapse_fault(s, source_id)) {
583         error_report_once("New fault is not recorded due to "
584                           "compression of faults");
585         return;
586     }
587 
588     if (vtd_is_frcd_set(s, s->next_frcd_reg)) {
589         error_report_once("Next Fault Recording Reg is used, "
590                           "new fault is not recorded, set PFO field");
591         vtd_set_clear_mask_long(s, DMAR_FSTS_REG, 0, VTD_FSTS_PFO);
592         return;
593     }
594 
595     vtd_record_frcd(s, s->next_frcd_reg, hi, lo);
596 
597     if (fsts_reg & VTD_FSTS_PPF) {
598         error_report_once("There are pending faults already, "
599                           "fault event is not generated");
600         vtd_set_frcd_and_update_ppf(s, s->next_frcd_reg);
601         s->next_frcd_reg++;
602         if (s->next_frcd_reg == DMAR_FRCD_REG_NR) {
603             s->next_frcd_reg = 0;
604         }
605     } else {
606         vtd_set_clear_mask_long(s, DMAR_FSTS_REG, VTD_FSTS_FRI_MASK,
607                                 VTD_FSTS_FRI(s->next_frcd_reg));
608         vtd_set_frcd_and_update_ppf(s, s->next_frcd_reg); /* Will set PPF */
609         s->next_frcd_reg++;
610         if (s->next_frcd_reg == DMAR_FRCD_REG_NR) {
611             s->next_frcd_reg = 0;
612         }
613         /* This case actually cause the PPF to be Set.
614          * So generate fault event (interrupt).
615          */
616          vtd_generate_fault_event(s, fsts_reg);
617     }
618 }
619 
620 /* Log and report an DMAR (address translation) fault to software */
621 static void vtd_report_dmar_fault(IntelIOMMUState *s, uint16_t source_id,
622                                   hwaddr addr, VTDFaultReason fault,
623                                   bool is_write, bool is_pasid,
624                                   uint32_t pasid)
625 {
626     uint64_t hi, lo;
627 
628     assert(fault < VTD_FR_MAX);
629 
630     trace_vtd_dmar_fault(source_id, fault, addr, is_write);
631 
632     lo = VTD_FRCD_FI(addr);
633     hi = VTD_FRCD_SID(source_id) | VTD_FRCD_FR(fault) |
634          VTD_FRCD_PV(pasid) | VTD_FRCD_PP(is_pasid);
635     if (!is_write) {
636         hi |= VTD_FRCD_T;
637     }
638 
639     vtd_report_frcd_fault(s, source_id, hi, lo);
640 }
641 
642 
643 static void vtd_report_ir_fault(IntelIOMMUState *s, uint64_t source_id,
644                                 VTDFaultReason fault, uint16_t index)
645 {
646     uint64_t hi, lo;
647 
648     lo = VTD_FRCD_IR_IDX(index);
649     hi = VTD_FRCD_SID(source_id) | VTD_FRCD_FR(fault);
650 
651     vtd_report_frcd_fault(s, source_id, hi, lo);
652 }
653 
654 /* Handle Invalidation Queue Errors of queued invalidation interface error
655  * conditions.
656  */
657 static void vtd_handle_inv_queue_error(IntelIOMMUState *s)
658 {
659     uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
660 
661     vtd_set_clear_mask_long(s, DMAR_FSTS_REG, 0, VTD_FSTS_IQE);
662     vtd_generate_fault_event(s, fsts_reg);
663 }
664 
665 /* Set the IWC field and try to generate an invalidation completion interrupt */
666 static void vtd_generate_completion_event(IntelIOMMUState *s)
667 {
668     if (vtd_get_long_raw(s, DMAR_ICS_REG) & VTD_ICS_IWC) {
669         trace_vtd_inv_desc_wait_irq("One pending, skip current");
670         return;
671     }
672     vtd_set_clear_mask_long(s, DMAR_ICS_REG, 0, VTD_ICS_IWC);
673     vtd_set_clear_mask_long(s, DMAR_IECTL_REG, 0, VTD_IECTL_IP);
674     if (vtd_get_long_raw(s, DMAR_IECTL_REG) & VTD_IECTL_IM) {
675         trace_vtd_inv_desc_wait_irq("IM in IECTL_REG is set, "
676                                     "new event not generated");
677         return;
678     } else {
679         /* Generate the interrupt event */
680         trace_vtd_inv_desc_wait_irq("Generating complete event");
681         vtd_generate_interrupt(s, DMAR_IEADDR_REG, DMAR_IEDATA_REG);
682         vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
683     }
684 }
685 
686 static inline bool vtd_root_entry_present(IntelIOMMUState *s,
687                                           VTDRootEntry *re,
688                                           uint8_t devfn)
689 {
690     if (s->root_scalable && devfn > UINT8_MAX / 2) {
691         return re->hi & VTD_ROOT_ENTRY_P;
692     }
693 
694     return re->lo & VTD_ROOT_ENTRY_P;
695 }
696 
697 static int vtd_get_root_entry(IntelIOMMUState *s, uint8_t index,
698                               VTDRootEntry *re)
699 {
700     dma_addr_t addr;
701 
702     addr = s->root + index * sizeof(*re);
703     if (dma_memory_read(&address_space_memory, addr,
704                         re, sizeof(*re), MEMTXATTRS_UNSPECIFIED)) {
705         re->lo = 0;
706         return -VTD_FR_ROOT_TABLE_INV;
707     }
708     re->lo = le64_to_cpu(re->lo);
709     re->hi = le64_to_cpu(re->hi);
710     return 0;
711 }
712 
713 static inline bool vtd_ce_present(VTDContextEntry *context)
714 {
715     return context->lo & VTD_CONTEXT_ENTRY_P;
716 }
717 
718 static int vtd_get_context_entry_from_root(IntelIOMMUState *s,
719                                            VTDRootEntry *re,
720                                            uint8_t index,
721                                            VTDContextEntry *ce)
722 {
723     dma_addr_t addr, ce_size;
724 
725     /* we have checked that root entry is present */
726     ce_size = s->root_scalable ? VTD_CTX_ENTRY_SCALABLE_SIZE :
727               VTD_CTX_ENTRY_LEGACY_SIZE;
728 
729     if (s->root_scalable && index > UINT8_MAX / 2) {
730         index = index & (~VTD_DEVFN_CHECK_MASK);
731         addr = re->hi & VTD_ROOT_ENTRY_CTP;
732     } else {
733         addr = re->lo & VTD_ROOT_ENTRY_CTP;
734     }
735 
736     addr = addr + index * ce_size;
737     if (dma_memory_read(&address_space_memory, addr,
738                         ce, ce_size, MEMTXATTRS_UNSPECIFIED)) {
739         return -VTD_FR_CONTEXT_TABLE_INV;
740     }
741 
742     ce->lo = le64_to_cpu(ce->lo);
743     ce->hi = le64_to_cpu(ce->hi);
744     if (ce_size == VTD_CTX_ENTRY_SCALABLE_SIZE) {
745         ce->val[2] = le64_to_cpu(ce->val[2]);
746         ce->val[3] = le64_to_cpu(ce->val[3]);
747     }
748     return 0;
749 }
750 
751 static inline dma_addr_t vtd_ce_get_slpt_base(VTDContextEntry *ce)
752 {
753     return ce->lo & VTD_CONTEXT_ENTRY_SLPTPTR;
754 }
755 
756 static inline uint64_t vtd_get_pte_addr(uint64_t pte, uint8_t aw)
757 {
758     return pte & VTD_PT_BASE_ADDR_MASK(aw);
759 }
760 
761 /* Whether the pte indicates the address of the page frame */
762 static inline bool vtd_is_last_pte(uint64_t pte, uint32_t level)
763 {
764     return level == VTD_PT_LEVEL || (pte & VTD_PT_PAGE_SIZE_MASK);
765 }
766 
767 /* Get the content of a pte located in @base_addr[@index] */
768 static uint64_t vtd_get_pte(dma_addr_t base_addr, uint32_t index)
769 {
770     uint64_t pte;
771 
772     assert(index < VTD_PT_ENTRY_NR);
773 
774     if (dma_memory_read(&address_space_memory,
775                         base_addr + index * sizeof(pte),
776                         &pte, sizeof(pte), MEMTXATTRS_UNSPECIFIED)) {
777         pte = (uint64_t)-1;
778         return pte;
779     }
780     pte = le64_to_cpu(pte);
781     return pte;
782 }
783 
784 /* Given an iova and the level of paging structure, return the offset
785  * of current level.
786  */
787 static inline uint32_t vtd_iova_level_offset(uint64_t iova, uint32_t level)
788 {
789     return (iova >> vtd_pt_level_shift(level)) &
790             ((1ULL << VTD_LEVEL_BITS) - 1);
791 }
792 
793 /* Check Capability Register to see if the @level of page-table is supported */
794 static inline bool vtd_is_sl_level_supported(IntelIOMMUState *s, uint32_t level)
795 {
796     return VTD_CAP_SAGAW_MASK & s->cap &
797            (1ULL << (level - 2 + VTD_CAP_SAGAW_SHIFT));
798 }
799 
800 static inline bool vtd_is_fl_level_supported(IntelIOMMUState *s, uint32_t level)
801 {
802     return level == VTD_PML4_LEVEL;
803 }
804 
805 /* Return true if check passed, otherwise false */
806 static inline bool vtd_pe_type_check(IntelIOMMUState *s, VTDPASIDEntry *pe)
807 {
808     switch (VTD_PE_GET_TYPE(pe)) {
809     case VTD_SM_PASID_ENTRY_FLT:
810         return !!(s->ecap & VTD_ECAP_FLTS);
811     case VTD_SM_PASID_ENTRY_SLT:
812         return !!(s->ecap & VTD_ECAP_SLTS);
813     case VTD_SM_PASID_ENTRY_NESTED:
814         /* Not support NESTED page table type yet */
815         return false;
816     case VTD_SM_PASID_ENTRY_PT:
817         return !!(s->ecap & VTD_ECAP_PT);
818     default:
819         /* Unknown type */
820         return false;
821     }
822 }
823 
824 static inline bool vtd_pdire_present(VTDPASIDDirEntry *pdire)
825 {
826     return pdire->val & 1;
827 }
828 
829 /**
830  * Caller of this function should check present bit if wants
831  * to use pdir entry for further usage except for fpd bit check.
832  */
833 static int vtd_get_pdire_from_pdir_table(dma_addr_t pasid_dir_base,
834                                          uint32_t pasid,
835                                          VTDPASIDDirEntry *pdire)
836 {
837     uint32_t index;
838     dma_addr_t addr, entry_size;
839 
840     index = VTD_PASID_DIR_INDEX(pasid);
841     entry_size = VTD_PASID_DIR_ENTRY_SIZE;
842     addr = pasid_dir_base + index * entry_size;
843     if (dma_memory_read(&address_space_memory, addr,
844                         pdire, entry_size, MEMTXATTRS_UNSPECIFIED)) {
845         return -VTD_FR_PASID_DIR_ACCESS_ERR;
846     }
847 
848     pdire->val = le64_to_cpu(pdire->val);
849 
850     return 0;
851 }
852 
853 static inline bool vtd_pe_present(VTDPASIDEntry *pe)
854 {
855     return pe->val[0] & VTD_PASID_ENTRY_P;
856 }
857 
858 static int vtd_get_pe_in_pasid_leaf_table(IntelIOMMUState *s,
859                                           uint32_t pasid,
860                                           dma_addr_t addr,
861                                           VTDPASIDEntry *pe)
862 {
863     uint8_t pgtt;
864     uint32_t index;
865     dma_addr_t entry_size;
866 
867     index = VTD_PASID_TABLE_INDEX(pasid);
868     entry_size = VTD_PASID_ENTRY_SIZE;
869     addr = addr + index * entry_size;
870     if (dma_memory_read(&address_space_memory, addr,
871                         pe, entry_size, MEMTXATTRS_UNSPECIFIED)) {
872         return -VTD_FR_PASID_TABLE_ACCESS_ERR;
873     }
874     for (size_t i = 0; i < ARRAY_SIZE(pe->val); i++) {
875         pe->val[i] = le64_to_cpu(pe->val[i]);
876     }
877 
878     /* Do translation type check */
879     if (!vtd_pe_type_check(s, pe)) {
880         return -VTD_FR_PASID_TABLE_ENTRY_INV;
881     }
882 
883     pgtt = VTD_PE_GET_TYPE(pe);
884     if (pgtt == VTD_SM_PASID_ENTRY_SLT &&
885         !vtd_is_sl_level_supported(s, VTD_PE_GET_SL_LEVEL(pe))) {
886             return -VTD_FR_PASID_TABLE_ENTRY_INV;
887     }
888 
889     if (pgtt == VTD_SM_PASID_ENTRY_FLT &&
890         !vtd_is_fl_level_supported(s, VTD_PE_GET_FL_LEVEL(pe))) {
891             return -VTD_FR_PASID_TABLE_ENTRY_INV;
892     }
893 
894     return 0;
895 }
896 
897 /**
898  * Caller of this function should check present bit if wants
899  * to use pasid entry for further usage except for fpd bit check.
900  */
901 static int vtd_get_pe_from_pdire(IntelIOMMUState *s,
902                                  uint32_t pasid,
903                                  VTDPASIDDirEntry *pdire,
904                                  VTDPASIDEntry *pe)
905 {
906     dma_addr_t addr = pdire->val & VTD_PASID_TABLE_BASE_ADDR_MASK;
907 
908     return vtd_get_pe_in_pasid_leaf_table(s, pasid, addr, pe);
909 }
910 
911 /**
912  * This function gets a pasid entry from a specified pasid
913  * table (includes dir and leaf table) with a specified pasid.
914  * Sanity check should be done to ensure return a present
915  * pasid entry to caller.
916  */
917 static int vtd_get_pe_from_pasid_table(IntelIOMMUState *s,
918                                        dma_addr_t pasid_dir_base,
919                                        uint32_t pasid,
920                                        VTDPASIDEntry *pe)
921 {
922     int ret;
923     VTDPASIDDirEntry pdire;
924 
925     ret = vtd_get_pdire_from_pdir_table(pasid_dir_base,
926                                         pasid, &pdire);
927     if (ret) {
928         return ret;
929     }
930 
931     if (!vtd_pdire_present(&pdire)) {
932         return -VTD_FR_PASID_DIR_ENTRY_P;
933     }
934 
935     ret = vtd_get_pe_from_pdire(s, pasid, &pdire, pe);
936     if (ret) {
937         return ret;
938     }
939 
940     if (!vtd_pe_present(pe)) {
941         return -VTD_FR_PASID_ENTRY_P;
942     }
943 
944     return 0;
945 }
946 
947 static int vtd_ce_get_rid2pasid_entry(IntelIOMMUState *s,
948                                       VTDContextEntry *ce,
949                                       VTDPASIDEntry *pe,
950                                       uint32_t pasid)
951 {
952     dma_addr_t pasid_dir_base;
953     int ret = 0;
954 
955     if (pasid == PCI_NO_PASID) {
956         pasid = VTD_CE_GET_RID2PASID(ce);
957     }
958     pasid_dir_base = VTD_CE_GET_PASID_DIR_TABLE(ce);
959     ret = vtd_get_pe_from_pasid_table(s, pasid_dir_base, pasid, pe);
960 
961     return ret;
962 }
963 
964 static int vtd_ce_get_pasid_fpd(IntelIOMMUState *s,
965                                 VTDContextEntry *ce,
966                                 bool *pe_fpd_set,
967                                 uint32_t pasid)
968 {
969     int ret;
970     dma_addr_t pasid_dir_base;
971     VTDPASIDDirEntry pdire;
972     VTDPASIDEntry pe;
973 
974     if (pasid == PCI_NO_PASID) {
975         pasid = VTD_CE_GET_RID2PASID(ce);
976     }
977     pasid_dir_base = VTD_CE_GET_PASID_DIR_TABLE(ce);
978 
979     /*
980      * No present bit check since fpd is meaningful even
981      * if the present bit is clear.
982      */
983     ret = vtd_get_pdire_from_pdir_table(pasid_dir_base, pasid, &pdire);
984     if (ret) {
985         return ret;
986     }
987 
988     if (pdire.val & VTD_PASID_DIR_FPD) {
989         *pe_fpd_set = true;
990         return 0;
991     }
992 
993     if (!vtd_pdire_present(&pdire)) {
994         return -VTD_FR_PASID_DIR_ENTRY_P;
995     }
996 
997     /*
998      * No present bit check since fpd is meaningful even
999      * if the present bit is clear.
1000      */
1001     ret = vtd_get_pe_from_pdire(s, pasid, &pdire, &pe);
1002     if (ret) {
1003         return ret;
1004     }
1005 
1006     if (pe.val[0] & VTD_PASID_ENTRY_FPD) {
1007         *pe_fpd_set = true;
1008     }
1009 
1010     return 0;
1011 }
1012 
1013 /* Get the page-table level that hardware should use for the second-level
1014  * page-table walk from the Address Width field of context-entry.
1015  */
1016 static inline uint32_t vtd_ce_get_level(VTDContextEntry *ce)
1017 {
1018     return 2 + (ce->hi & VTD_CONTEXT_ENTRY_AW);
1019 }
1020 
1021 static uint32_t vtd_get_iova_level(IntelIOMMUState *s,
1022                                    VTDContextEntry *ce,
1023                                    uint32_t pasid)
1024 {
1025     VTDPASIDEntry pe;
1026 
1027     if (s->root_scalable) {
1028         vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
1029         if (s->flts) {
1030             return VTD_PE_GET_FL_LEVEL(&pe);
1031         } else {
1032             return VTD_PE_GET_SL_LEVEL(&pe);
1033         }
1034     }
1035 
1036     return vtd_ce_get_level(ce);
1037 }
1038 
1039 static inline uint32_t vtd_ce_get_agaw(VTDContextEntry *ce)
1040 {
1041     return 30 + (ce->hi & VTD_CONTEXT_ENTRY_AW) * 9;
1042 }
1043 
1044 static uint32_t vtd_get_iova_agaw(IntelIOMMUState *s,
1045                                   VTDContextEntry *ce,
1046                                   uint32_t pasid)
1047 {
1048     VTDPASIDEntry pe;
1049 
1050     if (s->root_scalable) {
1051         vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
1052         return 30 + ((pe.val[0] >> 2) & VTD_SM_PASID_ENTRY_AW) * 9;
1053     }
1054 
1055     return vtd_ce_get_agaw(ce);
1056 }
1057 
1058 static inline uint32_t vtd_ce_get_type(VTDContextEntry *ce)
1059 {
1060     return ce->lo & VTD_CONTEXT_ENTRY_TT;
1061 }
1062 
1063 /* Only for Legacy Mode. Return true if check passed, otherwise false */
1064 static inline bool vtd_ce_type_check(X86IOMMUState *x86_iommu,
1065                                      VTDContextEntry *ce)
1066 {
1067     switch (vtd_ce_get_type(ce)) {
1068     case VTD_CONTEXT_TT_MULTI_LEVEL:
1069         /* Always supported */
1070         break;
1071     case VTD_CONTEXT_TT_DEV_IOTLB:
1072         if (!x86_iommu->dt_supported) {
1073             error_report_once("%s: DT specified but not supported", __func__);
1074             return false;
1075         }
1076         break;
1077     case VTD_CONTEXT_TT_PASS_THROUGH:
1078         if (!x86_iommu->pt_supported) {
1079             error_report_once("%s: PT specified but not supported", __func__);
1080             return false;
1081         }
1082         break;
1083     default:
1084         /* Unknown type */
1085         error_report_once("%s: unknown ce type: %"PRIu32, __func__,
1086                           vtd_ce_get_type(ce));
1087         return false;
1088     }
1089     return true;
1090 }
1091 
1092 static inline uint64_t vtd_iova_limit(IntelIOMMUState *s,
1093                                       VTDContextEntry *ce, uint8_t aw,
1094                                       uint32_t pasid)
1095 {
1096     uint32_t ce_agaw = vtd_get_iova_agaw(s, ce, pasid);
1097     return 1ULL << MIN(ce_agaw, aw);
1098 }
1099 
1100 /* Return true if IOVA passes range check, otherwise false. */
1101 static inline bool vtd_iova_sl_range_check(IntelIOMMUState *s,
1102                                            uint64_t iova, VTDContextEntry *ce,
1103                                            uint8_t aw, uint32_t pasid)
1104 {
1105     /*
1106      * Check if @iova is above 2^X-1, where X is the minimum of MGAW
1107      * in CAP_REG and AW in context-entry.
1108      */
1109     return !(iova & ~(vtd_iova_limit(s, ce, aw, pasid) - 1));
1110 }
1111 
1112 static dma_addr_t vtd_get_iova_pgtbl_base(IntelIOMMUState *s,
1113                                           VTDContextEntry *ce,
1114                                           uint32_t pasid)
1115 {
1116     VTDPASIDEntry pe;
1117 
1118     if (s->root_scalable) {
1119         vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
1120         if (s->flts) {
1121             return pe.val[2] & VTD_SM_PASID_ENTRY_FLPTPTR;
1122         } else {
1123             return pe.val[0] & VTD_SM_PASID_ENTRY_SLPTPTR;
1124         }
1125     }
1126 
1127     return vtd_ce_get_slpt_base(ce);
1128 }
1129 
1130 /*
1131  * Rsvd field masks for spte:
1132  *     vtd_spte_rsvd 4k pages
1133  *     vtd_spte_rsvd_large large pages
1134  *
1135  * We support only 3-level and 4-level page tables (see vtd_init() which
1136  * sets only VTD_CAP_SAGAW_39bit and maybe VTD_CAP_SAGAW_48bit bits in s->cap).
1137  */
1138 #define VTD_SPTE_RSVD_LEN 5
1139 static uint64_t vtd_spte_rsvd[VTD_SPTE_RSVD_LEN];
1140 static uint64_t vtd_spte_rsvd_large[VTD_SPTE_RSVD_LEN];
1141 
1142 static bool vtd_slpte_nonzero_rsvd(uint64_t slpte, uint32_t level)
1143 {
1144     uint64_t rsvd_mask;
1145 
1146     /*
1147      * We should have caught a guest-mis-programmed level earlier,
1148      * via vtd_is_sl_level_supported.
1149      */
1150     assert(level < VTD_SPTE_RSVD_LEN);
1151     /*
1152      * Zero level doesn't exist. The smallest level is VTD_PT_LEVEL=1 and
1153      * checked by vtd_is_last_pte().
1154      */
1155     assert(level);
1156 
1157     if ((level == VTD_PD_LEVEL || level == VTD_PDP_LEVEL) &&
1158         (slpte & VTD_PT_PAGE_SIZE_MASK)) {
1159         /* large page */
1160         rsvd_mask = vtd_spte_rsvd_large[level];
1161     } else {
1162         rsvd_mask = vtd_spte_rsvd[level];
1163     }
1164 
1165     return slpte & rsvd_mask;
1166 }
1167 
1168 /* Given the @iova, get relevant @slptep. @slpte_level will be the last level
1169  * of the translation, can be used for deciding the size of large page.
1170  */
1171 static int vtd_iova_to_slpte(IntelIOMMUState *s, VTDContextEntry *ce,
1172                              uint64_t iova, bool is_write,
1173                              uint64_t *slptep, uint32_t *slpte_level,
1174                              bool *reads, bool *writes, uint8_t aw_bits,
1175                              uint32_t pasid)
1176 {
1177     dma_addr_t addr = vtd_get_iova_pgtbl_base(s, ce, pasid);
1178     uint32_t level = vtd_get_iova_level(s, ce, pasid);
1179     uint32_t offset;
1180     uint64_t slpte;
1181     uint64_t access_right_check;
1182 
1183     if (!vtd_iova_sl_range_check(s, iova, ce, aw_bits, pasid)) {
1184         error_report_once("%s: detected IOVA overflow (iova=0x%" PRIx64 ","
1185                           "pasid=0x%" PRIx32 ")", __func__, iova, pasid);
1186         return -VTD_FR_ADDR_BEYOND_MGAW;
1187     }
1188 
1189     /* FIXME: what is the Atomics request here? */
1190     access_right_check = is_write ? VTD_SL_W : VTD_SL_R;
1191 
1192     while (true) {
1193         offset = vtd_iova_level_offset(iova, level);
1194         slpte = vtd_get_pte(addr, offset);
1195 
1196         if (slpte == (uint64_t)-1) {
1197             error_report_once("%s: detected read error on DMAR slpte "
1198                               "(iova=0x%" PRIx64 ", pasid=0x%" PRIx32 ")",
1199                               __func__, iova, pasid);
1200             if (level == vtd_get_iova_level(s, ce, pasid)) {
1201                 /* Invalid programming of context-entry */
1202                 return -VTD_FR_CONTEXT_ENTRY_INV;
1203             } else {
1204                 return -VTD_FR_PAGING_ENTRY_INV;
1205             }
1206         }
1207         *reads = (*reads) && (slpte & VTD_SL_R);
1208         *writes = (*writes) && (slpte & VTD_SL_W);
1209         if (!(slpte & access_right_check)) {
1210             error_report_once("%s: detected slpte permission error "
1211                               "(iova=0x%" PRIx64 ", level=0x%" PRIx32 ", "
1212                               "slpte=0x%" PRIx64 ", write=%d, pasid=0x%"
1213                               PRIx32 ")", __func__, iova, level,
1214                               slpte, is_write, pasid);
1215             return is_write ? -VTD_FR_WRITE : -VTD_FR_READ;
1216         }
1217         if (vtd_slpte_nonzero_rsvd(slpte, level)) {
1218             error_report_once("%s: detected splte reserve non-zero "
1219                               "iova=0x%" PRIx64 ", level=0x%" PRIx32
1220                               "slpte=0x%" PRIx64 ", pasid=0x%" PRIX32 ")",
1221                               __func__, iova, level, slpte, pasid);
1222             return -VTD_FR_PAGING_ENTRY_RSVD;
1223         }
1224 
1225         if (vtd_is_last_pte(slpte, level)) {
1226             *slptep = slpte;
1227             *slpte_level = level;
1228             break;
1229         }
1230         addr = vtd_get_pte_addr(slpte, aw_bits);
1231         level--;
1232     }
1233 
1234     return 0;
1235 }
1236 
1237 typedef int (*vtd_page_walk_hook)(const IOMMUTLBEvent *event, void *private);
1238 
1239 /**
1240  * Constant information used during page walking
1241  *
1242  * @hook_fn: hook func to be called when detected page
1243  * @private: private data to be passed into hook func
1244  * @notify_unmap: whether we should notify invalid entries
1245  * @as: VT-d address space of the device
1246  * @aw: maximum address width
1247  * @domain: domain ID of the page walk
1248  */
1249 typedef struct {
1250     VTDAddressSpace *as;
1251     vtd_page_walk_hook hook_fn;
1252     void *private;
1253     bool notify_unmap;
1254     uint8_t aw;
1255     uint16_t domain_id;
1256 } vtd_page_walk_info;
1257 
1258 static int vtd_page_walk_one(IOMMUTLBEvent *event, vtd_page_walk_info *info)
1259 {
1260     VTDAddressSpace *as = info->as;
1261     vtd_page_walk_hook hook_fn = info->hook_fn;
1262     void *private = info->private;
1263     IOMMUTLBEntry *entry = &event->entry;
1264     DMAMap target = {
1265         .iova = entry->iova,
1266         .size = entry->addr_mask,
1267         .translated_addr = entry->translated_addr,
1268         .perm = entry->perm,
1269     };
1270     const DMAMap *mapped = iova_tree_find(as->iova_tree, &target);
1271 
1272     if (event->type == IOMMU_NOTIFIER_UNMAP && !info->notify_unmap) {
1273         trace_vtd_page_walk_one_skip_unmap(entry->iova, entry->addr_mask);
1274         return 0;
1275     }
1276 
1277     assert(hook_fn);
1278 
1279     /* Update local IOVA mapped ranges */
1280     if (event->type == IOMMU_NOTIFIER_MAP) {
1281         if (mapped) {
1282             /* If it's exactly the same translation, skip */
1283             if (!memcmp(mapped, &target, sizeof(target))) {
1284                 trace_vtd_page_walk_one_skip_map(entry->iova, entry->addr_mask,
1285                                                  entry->translated_addr);
1286                 return 0;
1287             } else {
1288                 /*
1289                  * Translation changed.  Normally this should not
1290                  * happen, but it can happen when with buggy guest
1291                  * OSes.  Note that there will be a small window that
1292                  * we don't have map at all.  But that's the best
1293                  * effort we can do.  The ideal way to emulate this is
1294                  * atomically modify the PTE to follow what has
1295                  * changed, but we can't.  One example is that vfio
1296                  * driver only has VFIO_IOMMU_[UN]MAP_DMA but no
1297                  * interface to modify a mapping (meanwhile it seems
1298                  * meaningless to even provide one).  Anyway, let's
1299                  * mark this as a TODO in case one day we'll have
1300                  * a better solution.
1301                  */
1302                 IOMMUAccessFlags cache_perm = entry->perm;
1303                 int ret;
1304 
1305                 /* Emulate an UNMAP */
1306                 event->type = IOMMU_NOTIFIER_UNMAP;
1307                 entry->perm = IOMMU_NONE;
1308                 trace_vtd_page_walk_one(info->domain_id,
1309                                         entry->iova,
1310                                         entry->translated_addr,
1311                                         entry->addr_mask,
1312                                         entry->perm);
1313                 ret = hook_fn(event, private);
1314                 if (ret) {
1315                     return ret;
1316                 }
1317                 /* Drop any existing mapping */
1318                 iova_tree_remove(as->iova_tree, target);
1319                 /* Recover the correct type */
1320                 event->type = IOMMU_NOTIFIER_MAP;
1321                 entry->perm = cache_perm;
1322             }
1323         }
1324         iova_tree_insert(as->iova_tree, &target);
1325     } else {
1326         if (!mapped) {
1327             /* Skip since we didn't map this range at all */
1328             trace_vtd_page_walk_one_skip_unmap(entry->iova, entry->addr_mask);
1329             return 0;
1330         }
1331         iova_tree_remove(as->iova_tree, target);
1332     }
1333 
1334     trace_vtd_page_walk_one(info->domain_id, entry->iova,
1335                             entry->translated_addr, entry->addr_mask,
1336                             entry->perm);
1337     return hook_fn(event, private);
1338 }
1339 
1340 /**
1341  * vtd_page_walk_level - walk over specific level for IOVA range
1342  *
1343  * @addr: base GPA addr to start the walk
1344  * @start: IOVA range start address
1345  * @end: IOVA range end address (start <= addr < end)
1346  * @read: whether parent level has read permission
1347  * @write: whether parent level has write permission
1348  * @info: constant information for the page walk
1349  */
1350 static int vtd_page_walk_level(dma_addr_t addr, uint64_t start,
1351                                uint64_t end, uint32_t level, bool read,
1352                                bool write, vtd_page_walk_info *info)
1353 {
1354     bool read_cur, write_cur, entry_valid;
1355     uint32_t offset;
1356     uint64_t slpte;
1357     uint64_t subpage_size, subpage_mask;
1358     IOMMUTLBEvent event;
1359     uint64_t iova = start;
1360     uint64_t iova_next;
1361     int ret = 0;
1362 
1363     trace_vtd_page_walk_level(addr, level, start, end);
1364 
1365     subpage_size = 1ULL << vtd_pt_level_shift(level);
1366     subpage_mask = vtd_pt_level_page_mask(level);
1367 
1368     while (iova < end) {
1369         iova_next = (iova & subpage_mask) + subpage_size;
1370 
1371         offset = vtd_iova_level_offset(iova, level);
1372         slpte = vtd_get_pte(addr, offset);
1373 
1374         if (slpte == (uint64_t)-1) {
1375             trace_vtd_page_walk_skip_read(iova, iova_next);
1376             goto next;
1377         }
1378 
1379         if (vtd_slpte_nonzero_rsvd(slpte, level)) {
1380             trace_vtd_page_walk_skip_reserve(iova, iova_next);
1381             goto next;
1382         }
1383 
1384         /* Permissions are stacked with parents' */
1385         read_cur = read && (slpte & VTD_SL_R);
1386         write_cur = write && (slpte & VTD_SL_W);
1387 
1388         /*
1389          * As long as we have either read/write permission, this is a
1390          * valid entry. The rule works for both page entries and page
1391          * table entries.
1392          */
1393         entry_valid = read_cur | write_cur;
1394 
1395         if (!vtd_is_last_pte(slpte, level) && entry_valid) {
1396             /*
1397              * This is a valid PDE (or even bigger than PDE).  We need
1398              * to walk one further level.
1399              */
1400             ret = vtd_page_walk_level(vtd_get_pte_addr(slpte, info->aw),
1401                                       iova, MIN(iova_next, end), level - 1,
1402                                       read_cur, write_cur, info);
1403         } else {
1404             /*
1405              * This means we are either:
1406              *
1407              * (1) the real page entry (either 4K page, or huge page)
1408              * (2) the whole range is invalid
1409              *
1410              * In either case, we send an IOTLB notification down.
1411              */
1412             event.entry.target_as = &address_space_memory;
1413             event.entry.iova = iova & subpage_mask;
1414             event.entry.perm = IOMMU_ACCESS_FLAG(read_cur, write_cur);
1415             event.entry.addr_mask = ~subpage_mask;
1416             /* NOTE: this is only meaningful if entry_valid == true */
1417             event.entry.translated_addr = vtd_get_pte_addr(slpte, info->aw);
1418             event.type = event.entry.perm ? IOMMU_NOTIFIER_MAP :
1419                                             IOMMU_NOTIFIER_UNMAP;
1420             ret = vtd_page_walk_one(&event, info);
1421         }
1422 
1423         if (ret < 0) {
1424             return ret;
1425         }
1426 
1427 next:
1428         iova = iova_next;
1429     }
1430 
1431     return 0;
1432 }
1433 
1434 /**
1435  * vtd_page_walk - walk specific IOVA range, and call the hook
1436  *
1437  * @s: intel iommu state
1438  * @ce: context entry to walk upon
1439  * @start: IOVA address to start the walk
1440  * @end: IOVA range end address (start <= addr < end)
1441  * @info: page walking information struct
1442  */
1443 static int vtd_page_walk(IntelIOMMUState *s, VTDContextEntry *ce,
1444                          uint64_t start, uint64_t end,
1445                          vtd_page_walk_info *info,
1446                          uint32_t pasid)
1447 {
1448     dma_addr_t addr = vtd_get_iova_pgtbl_base(s, ce, pasid);
1449     uint32_t level = vtd_get_iova_level(s, ce, pasid);
1450 
1451     if (!vtd_iova_sl_range_check(s, start, ce, info->aw, pasid)) {
1452         return -VTD_FR_ADDR_BEYOND_MGAW;
1453     }
1454 
1455     if (!vtd_iova_sl_range_check(s, end, ce, info->aw, pasid)) {
1456         /* Fix end so that it reaches the maximum */
1457         end = vtd_iova_limit(s, ce, info->aw, pasid);
1458     }
1459 
1460     return vtd_page_walk_level(addr, start, end, level, true, true, info);
1461 }
1462 
1463 static int vtd_root_entry_rsvd_bits_check(IntelIOMMUState *s,
1464                                           VTDRootEntry *re)
1465 {
1466     /* Legacy Mode reserved bits check */
1467     if (!s->root_scalable &&
1468         (re->hi || (re->lo & VTD_ROOT_ENTRY_RSVD(s->aw_bits))))
1469         goto rsvd_err;
1470 
1471     /* Scalable Mode reserved bits check */
1472     if (s->root_scalable &&
1473         ((re->lo & VTD_ROOT_ENTRY_RSVD(s->aw_bits)) ||
1474          (re->hi & VTD_ROOT_ENTRY_RSVD(s->aw_bits))))
1475         goto rsvd_err;
1476 
1477     return 0;
1478 
1479 rsvd_err:
1480     error_report_once("%s: invalid root entry: hi=0x%"PRIx64
1481                       ", lo=0x%"PRIx64,
1482                       __func__, re->hi, re->lo);
1483     return -VTD_FR_ROOT_ENTRY_RSVD;
1484 }
1485 
1486 static inline int vtd_context_entry_rsvd_bits_check(IntelIOMMUState *s,
1487                                                     VTDContextEntry *ce)
1488 {
1489     if (!s->root_scalable &&
1490         (ce->hi & VTD_CONTEXT_ENTRY_RSVD_HI ||
1491          ce->lo & VTD_CONTEXT_ENTRY_RSVD_LO(s->aw_bits))) {
1492         error_report_once("%s: invalid context entry: hi=%"PRIx64
1493                           ", lo=%"PRIx64" (reserved nonzero)",
1494                           __func__, ce->hi, ce->lo);
1495         return -VTD_FR_CONTEXT_ENTRY_RSVD;
1496     }
1497 
1498     if (s->root_scalable &&
1499         (ce->val[0] & VTD_SM_CONTEXT_ENTRY_RSVD_VAL0(s->aw_bits) ||
1500          ce->val[1] & VTD_SM_CONTEXT_ENTRY_RSVD_VAL1 ||
1501          ce->val[2] ||
1502          ce->val[3])) {
1503         error_report_once("%s: invalid context entry: val[3]=%"PRIx64
1504                           ", val[2]=%"PRIx64
1505                           ", val[1]=%"PRIx64
1506                           ", val[0]=%"PRIx64" (reserved nonzero)",
1507                           __func__, ce->val[3], ce->val[2],
1508                           ce->val[1], ce->val[0]);
1509         return -VTD_FR_CONTEXT_ENTRY_RSVD;
1510     }
1511 
1512     return 0;
1513 }
1514 
1515 static int vtd_ce_rid2pasid_check(IntelIOMMUState *s,
1516                                   VTDContextEntry *ce)
1517 {
1518     VTDPASIDEntry pe;
1519 
1520     /*
1521      * Make sure in Scalable Mode, a present context entry
1522      * has valid rid2pasid setting, which includes valid
1523      * rid2pasid field and corresponding pasid entry setting
1524      */
1525     return vtd_ce_get_rid2pasid_entry(s, ce, &pe, PCI_NO_PASID);
1526 }
1527 
1528 /* Map a device to its corresponding domain (context-entry) */
1529 static int vtd_dev_to_context_entry(IntelIOMMUState *s, uint8_t bus_num,
1530                                     uint8_t devfn, VTDContextEntry *ce)
1531 {
1532     VTDRootEntry re;
1533     int ret_fr;
1534     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
1535 
1536     ret_fr = vtd_get_root_entry(s, bus_num, &re);
1537     if (ret_fr) {
1538         return ret_fr;
1539     }
1540 
1541     if (!vtd_root_entry_present(s, &re, devfn)) {
1542         /* Not error - it's okay we don't have root entry. */
1543         trace_vtd_re_not_present(bus_num);
1544         return -VTD_FR_ROOT_ENTRY_P;
1545     }
1546 
1547     ret_fr = vtd_root_entry_rsvd_bits_check(s, &re);
1548     if (ret_fr) {
1549         return ret_fr;
1550     }
1551 
1552     ret_fr = vtd_get_context_entry_from_root(s, &re, devfn, ce);
1553     if (ret_fr) {
1554         return ret_fr;
1555     }
1556 
1557     if (!vtd_ce_present(ce)) {
1558         /* Not error - it's okay we don't have context entry. */
1559         trace_vtd_ce_not_present(bus_num, devfn);
1560         return -VTD_FR_CONTEXT_ENTRY_P;
1561     }
1562 
1563     ret_fr = vtd_context_entry_rsvd_bits_check(s, ce);
1564     if (ret_fr) {
1565         return ret_fr;
1566     }
1567 
1568     /* Check if the programming of context-entry is valid */
1569     if (!s->root_scalable &&
1570         !vtd_is_sl_level_supported(s, vtd_ce_get_level(ce))) {
1571         error_report_once("%s: invalid context entry: hi=%"PRIx64
1572                           ", lo=%"PRIx64" (level %d not supported)",
1573                           __func__, ce->hi, ce->lo,
1574                           vtd_ce_get_level(ce));
1575         return -VTD_FR_CONTEXT_ENTRY_INV;
1576     }
1577 
1578     if (!s->root_scalable) {
1579         /* Do translation type check */
1580         if (!vtd_ce_type_check(x86_iommu, ce)) {
1581             /* Errors dumped in vtd_ce_type_check() */
1582             return -VTD_FR_CONTEXT_ENTRY_INV;
1583         }
1584     } else {
1585         /*
1586          * Check if the programming of context-entry.rid2pasid
1587          * and corresponding pasid setting is valid, and thus
1588          * avoids to check pasid entry fetching result in future
1589          * helper function calling.
1590          */
1591         ret_fr = vtd_ce_rid2pasid_check(s, ce);
1592         if (ret_fr) {
1593             return ret_fr;
1594         }
1595     }
1596 
1597     return 0;
1598 }
1599 
1600 static int vtd_sync_shadow_page_hook(const IOMMUTLBEvent *event,
1601                                      void *private)
1602 {
1603     memory_region_notify_iommu(private, 0, *event);
1604     return 0;
1605 }
1606 
1607 static uint16_t vtd_get_domain_id(IntelIOMMUState *s,
1608                                   VTDContextEntry *ce,
1609                                   uint32_t pasid)
1610 {
1611     VTDPASIDEntry pe;
1612 
1613     if (s->root_scalable) {
1614         vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
1615         return VTD_SM_PASID_ENTRY_DID(pe.val[1]);
1616     }
1617 
1618     return VTD_CONTEXT_ENTRY_DID(ce->hi);
1619 }
1620 
1621 static int vtd_sync_shadow_page_table_range(VTDAddressSpace *vtd_as,
1622                                             VTDContextEntry *ce,
1623                                             hwaddr addr, hwaddr size)
1624 {
1625     IntelIOMMUState *s = vtd_as->iommu_state;
1626     vtd_page_walk_info info = {
1627         .hook_fn = vtd_sync_shadow_page_hook,
1628         .private = (void *)&vtd_as->iommu,
1629         .notify_unmap = true,
1630         .aw = s->aw_bits,
1631         .as = vtd_as,
1632         .domain_id = vtd_get_domain_id(s, ce, vtd_as->pasid),
1633     };
1634 
1635     return vtd_page_walk(s, ce, addr, addr + size, &info, vtd_as->pasid);
1636 }
1637 
1638 static int vtd_address_space_sync(VTDAddressSpace *vtd_as)
1639 {
1640     int ret;
1641     VTDContextEntry ce;
1642     IOMMUNotifier *n;
1643 
1644     /* If no MAP notifier registered, we simply invalidate all the cache */
1645     if (!vtd_as_has_map_notifier(vtd_as)) {
1646         IOMMU_NOTIFIER_FOREACH(n, &vtd_as->iommu) {
1647             memory_region_unmap_iommu_notifier_range(n);
1648         }
1649         return 0;
1650     }
1651 
1652     ret = vtd_dev_to_context_entry(vtd_as->iommu_state,
1653                                    pci_bus_num(vtd_as->bus),
1654                                    vtd_as->devfn, &ce);
1655     if (ret) {
1656         if (ret == -VTD_FR_CONTEXT_ENTRY_P) {
1657             /*
1658              * It's a valid scenario to have a context entry that is
1659              * not present.  For example, when a device is removed
1660              * from an existing domain then the context entry will be
1661              * zeroed by the guest before it was put into another
1662              * domain.  When this happens, instead of synchronizing
1663              * the shadow pages we should invalidate all existing
1664              * mappings and notify the backends.
1665              */
1666             IOMMU_NOTIFIER_FOREACH(n, &vtd_as->iommu) {
1667                 vtd_address_space_unmap(vtd_as, n);
1668             }
1669             ret = 0;
1670         }
1671         return ret;
1672     }
1673 
1674     return vtd_sync_shadow_page_table_range(vtd_as, &ce, 0, UINT64_MAX);
1675 }
1676 
1677 /*
1678  * Check if specific device is configured to bypass address
1679  * translation for DMA requests. In Scalable Mode, bypass
1680  * 1st-level translation or 2nd-level translation, it depends
1681  * on PGTT setting.
1682  */
1683 static bool vtd_dev_pt_enabled(IntelIOMMUState *s, VTDContextEntry *ce,
1684                                uint32_t pasid)
1685 {
1686     VTDPASIDEntry pe;
1687     int ret;
1688 
1689     if (s->root_scalable) {
1690         ret = vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
1691         if (ret) {
1692             /*
1693              * This error is guest triggerable. We should assumt PT
1694              * not enabled for safety.
1695              */
1696             return false;
1697         }
1698         return (VTD_PE_GET_TYPE(&pe) == VTD_SM_PASID_ENTRY_PT);
1699     }
1700 
1701     return (vtd_ce_get_type(ce) == VTD_CONTEXT_TT_PASS_THROUGH);
1702 
1703 }
1704 
1705 static bool vtd_as_pt_enabled(VTDAddressSpace *as)
1706 {
1707     IntelIOMMUState *s;
1708     VTDContextEntry ce;
1709 
1710     assert(as);
1711 
1712     s = as->iommu_state;
1713     if (vtd_dev_to_context_entry(s, pci_bus_num(as->bus), as->devfn,
1714                                  &ce)) {
1715         /*
1716          * Possibly failed to parse the context entry for some reason
1717          * (e.g., during init, or any guest configuration errors on
1718          * context entries). We should assume PT not enabled for
1719          * safety.
1720          */
1721         return false;
1722     }
1723 
1724     return vtd_dev_pt_enabled(s, &ce, as->pasid);
1725 }
1726 
1727 /* Return whether the device is using IOMMU translation. */
1728 static bool vtd_switch_address_space(VTDAddressSpace *as)
1729 {
1730     bool use_iommu, pt;
1731 
1732     assert(as);
1733 
1734     use_iommu = as->iommu_state->dmar_enabled && !vtd_as_pt_enabled(as);
1735     pt = as->iommu_state->dmar_enabled && vtd_as_pt_enabled(as);
1736 
1737     trace_vtd_switch_address_space(pci_bus_num(as->bus),
1738                                    VTD_PCI_SLOT(as->devfn),
1739                                    VTD_PCI_FUNC(as->devfn),
1740                                    use_iommu);
1741 
1742     /*
1743      * It's possible that we reach here without BQL, e.g., when called
1744      * from vtd_pt_enable_fast_path(). However the memory APIs need
1745      * it. We'd better make sure we have had it already, or, take it.
1746      */
1747     BQL_LOCK_GUARD();
1748 
1749     /* Turn off first then on the other */
1750     if (use_iommu) {
1751         memory_region_set_enabled(&as->nodmar, false);
1752         memory_region_set_enabled(MEMORY_REGION(&as->iommu), true);
1753         /*
1754          * vt-d spec v3.4 3.14:
1755          *
1756          * """
1757          * Requests-with-PASID with input address in range 0xFEEx_xxxx
1758          * are translated normally like any other request-with-PASID
1759          * through DMA-remapping hardware.
1760          * """
1761          *
1762          * Need to disable ir for as with PASID.
1763          */
1764         if (as->pasid != PCI_NO_PASID) {
1765             memory_region_set_enabled(&as->iommu_ir, false);
1766         } else {
1767             memory_region_set_enabled(&as->iommu_ir, true);
1768         }
1769     } else {
1770         memory_region_set_enabled(MEMORY_REGION(&as->iommu), false);
1771         memory_region_set_enabled(&as->nodmar, true);
1772     }
1773 
1774     /*
1775      * vtd-spec v3.4 3.14:
1776      *
1777      * """
1778      * Requests-with-PASID with input address in range 0xFEEx_xxxx are
1779      * translated normally like any other request-with-PASID through
1780      * DMA-remapping hardware. However, if such a request is processed
1781      * using pass-through translation, it will be blocked as described
1782      * in the paragraph below.
1783      *
1784      * Software must not program paging-structure entries to remap any
1785      * address to the interrupt address range. Untranslated requests
1786      * and translation requests that result in an address in the
1787      * interrupt range will be blocked with condition code LGN.4 or
1788      * SGN.8.
1789      * """
1790      *
1791      * We enable per as memory region (iommu_ir_fault) for catching
1792      * the translation for interrupt range through PASID + PT.
1793      */
1794     if (pt && as->pasid != PCI_NO_PASID) {
1795         memory_region_set_enabled(&as->iommu_ir_fault, true);
1796     } else {
1797         memory_region_set_enabled(&as->iommu_ir_fault, false);
1798     }
1799 
1800     return use_iommu;
1801 }
1802 
1803 static void vtd_switch_address_space_all(IntelIOMMUState *s)
1804 {
1805     VTDAddressSpace *vtd_as;
1806     GHashTableIter iter;
1807 
1808     g_hash_table_iter_init(&iter, s->vtd_address_spaces);
1809     while (g_hash_table_iter_next(&iter, NULL, (void **)&vtd_as)) {
1810         vtd_switch_address_space(vtd_as);
1811     }
1812 }
1813 
1814 static const bool vtd_qualified_faults[] = {
1815     [VTD_FR_RESERVED] = false,
1816     [VTD_FR_ROOT_ENTRY_P] = false,
1817     [VTD_FR_CONTEXT_ENTRY_P] = true,
1818     [VTD_FR_CONTEXT_ENTRY_INV] = true,
1819     [VTD_FR_ADDR_BEYOND_MGAW] = true,
1820     [VTD_FR_WRITE] = true,
1821     [VTD_FR_READ] = true,
1822     [VTD_FR_PAGING_ENTRY_INV] = true,
1823     [VTD_FR_ROOT_TABLE_INV] = false,
1824     [VTD_FR_CONTEXT_TABLE_INV] = false,
1825     [VTD_FR_INTERRUPT_ADDR] = true,
1826     [VTD_FR_ROOT_ENTRY_RSVD] = false,
1827     [VTD_FR_PAGING_ENTRY_RSVD] = true,
1828     [VTD_FR_CONTEXT_ENTRY_TT] = true,
1829     [VTD_FR_PASID_DIR_ACCESS_ERR] = false,
1830     [VTD_FR_PASID_DIR_ENTRY_P] = true,
1831     [VTD_FR_PASID_TABLE_ACCESS_ERR] = false,
1832     [VTD_FR_PASID_ENTRY_P] = true,
1833     [VTD_FR_PASID_TABLE_ENTRY_INV] = true,
1834     [VTD_FR_FS_PAGING_ENTRY_INV] = true,
1835     [VTD_FR_FS_PAGING_ENTRY_P] = true,
1836     [VTD_FR_FS_PAGING_ENTRY_RSVD] = true,
1837     [VTD_FR_PASID_ENTRY_FSPTPTR_INV] = true,
1838     [VTD_FR_FS_NON_CANONICAL] = true,
1839     [VTD_FR_FS_PAGING_ENTRY_US] = true,
1840     [VTD_FR_SM_WRITE] = true,
1841     [VTD_FR_SM_INTERRUPT_ADDR] = true,
1842     [VTD_FR_FS_BIT_UPDATE_FAILED] = true,
1843     [VTD_FR_MAX] = false,
1844 };
1845 
1846 /* To see if a fault condition is "qualified", which is reported to software
1847  * only if the FPD field in the context-entry used to process the faulting
1848  * request is 0.
1849  */
1850 static inline bool vtd_is_qualified_fault(VTDFaultReason fault)
1851 {
1852     return vtd_qualified_faults[fault];
1853 }
1854 
1855 static inline bool vtd_is_interrupt_addr(hwaddr addr)
1856 {
1857     return VTD_INTERRUPT_ADDR_FIRST <= addr && addr <= VTD_INTERRUPT_ADDR_LAST;
1858 }
1859 
1860 static gboolean vtd_find_as_by_sid_and_pasid(gpointer key, gpointer value,
1861                                              gpointer user_data)
1862 {
1863     struct vtd_as_key *as_key = (struct vtd_as_key *)key;
1864     struct vtd_as_raw_key *target = (struct vtd_as_raw_key *)user_data;
1865     uint16_t sid = PCI_BUILD_BDF(pci_bus_num(as_key->bus), as_key->devfn);
1866 
1867     return (as_key->pasid == target->pasid) && (sid == target->sid);
1868 }
1869 
1870 static VTDAddressSpace *vtd_get_as_by_sid_and_pasid(IntelIOMMUState *s,
1871                                                     uint16_t sid,
1872                                                     uint32_t pasid)
1873 {
1874     struct vtd_as_raw_key key = {
1875         .sid = sid,
1876         .pasid = pasid
1877     };
1878 
1879     return g_hash_table_find(s->vtd_address_spaces,
1880                              vtd_find_as_by_sid_and_pasid, &key);
1881 }
1882 
1883 static VTDAddressSpace *vtd_get_as_by_sid(IntelIOMMUState *s, uint16_t sid)
1884 {
1885     return vtd_get_as_by_sid_and_pasid(s, sid, PCI_NO_PASID);
1886 }
1887 
1888 static void vtd_pt_enable_fast_path(IntelIOMMUState *s, uint16_t source_id)
1889 {
1890     VTDAddressSpace *vtd_as;
1891     bool success = false;
1892 
1893     vtd_as = vtd_get_as_by_sid(s, source_id);
1894     if (!vtd_as) {
1895         goto out;
1896     }
1897 
1898     if (vtd_switch_address_space(vtd_as) == false) {
1899         /* We switched off IOMMU region successfully. */
1900         success = true;
1901     }
1902 
1903 out:
1904     trace_vtd_pt_enable_fast_path(source_id, success);
1905 }
1906 
1907 /*
1908  * Rsvd field masks for fpte:
1909  *     vtd_fpte_rsvd 4k pages
1910  *     vtd_fpte_rsvd_large large pages
1911  *
1912  * We support only 4-level page tables.
1913  */
1914 #define VTD_FPTE_RSVD_LEN 5
1915 static uint64_t vtd_fpte_rsvd[VTD_FPTE_RSVD_LEN];
1916 static uint64_t vtd_fpte_rsvd_large[VTD_FPTE_RSVD_LEN];
1917 
1918 static bool vtd_flpte_nonzero_rsvd(uint64_t flpte, uint32_t level)
1919 {
1920     uint64_t rsvd_mask;
1921 
1922     /*
1923      * We should have caught a guest-mis-programmed level earlier,
1924      * via vtd_is_fl_level_supported.
1925      */
1926     assert(level < VTD_FPTE_RSVD_LEN);
1927     /*
1928      * Zero level doesn't exist. The smallest level is VTD_PT_LEVEL=1 and
1929      * checked by vtd_is_last_pte().
1930      */
1931     assert(level);
1932 
1933     if ((level == VTD_PD_LEVEL || level == VTD_PDP_LEVEL) &&
1934         (flpte & VTD_PT_PAGE_SIZE_MASK)) {
1935         /* large page */
1936         rsvd_mask = vtd_fpte_rsvd_large[level];
1937     } else {
1938         rsvd_mask = vtd_fpte_rsvd[level];
1939     }
1940 
1941     return flpte & rsvd_mask;
1942 }
1943 
1944 static inline bool vtd_flpte_present(uint64_t flpte)
1945 {
1946     return !!(flpte & VTD_FL_P);
1947 }
1948 
1949 /* Return true if IOVA is canonical, otherwise false. */
1950 static bool vtd_iova_fl_check_canonical(IntelIOMMUState *s, uint64_t iova,
1951                                         VTDContextEntry *ce, uint32_t pasid)
1952 {
1953     uint64_t iova_limit = vtd_iova_limit(s, ce, s->aw_bits, pasid);
1954     uint64_t upper_bits_mask = ~(iova_limit - 1);
1955     uint64_t upper_bits = iova & upper_bits_mask;
1956     bool msb = ((iova & (iova_limit >> 1)) != 0);
1957 
1958     if (msb) {
1959         return upper_bits == upper_bits_mask;
1960     } else {
1961         return !upper_bits;
1962     }
1963 }
1964 
1965 static MemTxResult vtd_set_flag_in_pte(dma_addr_t base_addr, uint32_t index,
1966                                        uint64_t pte, uint64_t flag)
1967 {
1968     if (pte & flag) {
1969         return MEMTX_OK;
1970     }
1971     pte |= flag;
1972     pte = cpu_to_le64(pte);
1973     return dma_memory_write(&address_space_memory,
1974                             base_addr + index * sizeof(pte),
1975                             &pte, sizeof(pte),
1976                             MEMTXATTRS_UNSPECIFIED);
1977 }
1978 
1979 /*
1980  * Given the @iova, get relevant @flptep. @flpte_level will be the last level
1981  * of the translation, can be used for deciding the size of large page.
1982  */
1983 static int vtd_iova_to_flpte(IntelIOMMUState *s, VTDContextEntry *ce,
1984                              uint64_t iova, bool is_write,
1985                              uint64_t *flptep, uint32_t *flpte_level,
1986                              bool *reads, bool *writes, uint8_t aw_bits,
1987                              uint32_t pasid)
1988 {
1989     dma_addr_t addr = vtd_get_iova_pgtbl_base(s, ce, pasid);
1990     uint32_t offset;
1991     uint64_t flpte, flag_ad = VTD_FL_A;
1992     *flpte_level = vtd_get_iova_level(s, ce, pasid);
1993 
1994     if (!vtd_iova_fl_check_canonical(s, iova, ce, pasid)) {
1995         error_report_once("%s: detected non canonical IOVA (iova=0x%" PRIx64 ","
1996                           "pasid=0x%" PRIx32 ")", __func__, iova, pasid);
1997         return -VTD_FR_FS_NON_CANONICAL;
1998     }
1999 
2000     while (true) {
2001         offset = vtd_iova_level_offset(iova, *flpte_level);
2002         flpte = vtd_get_pte(addr, offset);
2003 
2004         if (flpte == (uint64_t)-1) {
2005             if (*flpte_level == vtd_get_iova_level(s, ce, pasid)) {
2006                 /* Invalid programming of pasid-entry */
2007                 return -VTD_FR_PASID_ENTRY_FSPTPTR_INV;
2008             } else {
2009                 return -VTD_FR_FS_PAGING_ENTRY_INV;
2010             }
2011         }
2012 
2013         if (!vtd_flpte_present(flpte)) {
2014             *reads = false;
2015             *writes = false;
2016             return -VTD_FR_FS_PAGING_ENTRY_P;
2017         }
2018 
2019         /* No emulated device supports supervisor privilege request yet */
2020         if (!(flpte & VTD_FL_US)) {
2021             *reads = false;
2022             *writes = false;
2023             return -VTD_FR_FS_PAGING_ENTRY_US;
2024         }
2025 
2026         *reads = true;
2027         *writes = (*writes) && (flpte & VTD_FL_RW);
2028         if (is_write && !(flpte & VTD_FL_RW)) {
2029             return -VTD_FR_SM_WRITE;
2030         }
2031         if (vtd_flpte_nonzero_rsvd(flpte, *flpte_level)) {
2032             error_report_once("%s: detected flpte reserved non-zero "
2033                               "iova=0x%" PRIx64 ", level=0x%" PRIx32
2034                               "flpte=0x%" PRIx64 ", pasid=0x%" PRIX32 ")",
2035                               __func__, iova, *flpte_level, flpte, pasid);
2036             return -VTD_FR_FS_PAGING_ENTRY_RSVD;
2037         }
2038 
2039         if (vtd_is_last_pte(flpte, *flpte_level) && is_write) {
2040             flag_ad |= VTD_FL_D;
2041         }
2042 
2043         if (vtd_set_flag_in_pte(addr, offset, flpte, flag_ad) != MEMTX_OK) {
2044             return -VTD_FR_FS_BIT_UPDATE_FAILED;
2045         }
2046 
2047         if (vtd_is_last_pte(flpte, *flpte_level)) {
2048             *flptep = flpte;
2049             return 0;
2050         }
2051 
2052         addr = vtd_get_pte_addr(flpte, aw_bits);
2053         (*flpte_level)--;
2054     }
2055 }
2056 
2057 static void vtd_report_fault(IntelIOMMUState *s,
2058                              int err, bool is_fpd_set,
2059                              uint16_t source_id,
2060                              hwaddr addr,
2061                              bool is_write,
2062                              bool is_pasid,
2063                              uint32_t pasid)
2064 {
2065     if (is_fpd_set && vtd_is_qualified_fault(err)) {
2066         trace_vtd_fault_disabled();
2067     } else {
2068         vtd_report_dmar_fault(s, source_id, addr, err, is_write,
2069                               is_pasid, pasid);
2070     }
2071 }
2072 
2073 /* Map dev to context-entry then do a paging-structures walk to do a iommu
2074  * translation.
2075  *
2076  * Called from RCU critical section.
2077  *
2078  * @bus_num: The bus number
2079  * @devfn: The devfn, which is the  combined of device and function number
2080  * @is_write: The access is a write operation
2081  * @entry: IOMMUTLBEntry that contain the addr to be translated and result
2082  *
2083  * Returns true if translation is successful, otherwise false.
2084  */
2085 static bool vtd_do_iommu_translate(VTDAddressSpace *vtd_as, PCIBus *bus,
2086                                    uint8_t devfn, hwaddr addr, bool is_write,
2087                                    IOMMUTLBEntry *entry)
2088 {
2089     IntelIOMMUState *s = vtd_as->iommu_state;
2090     VTDContextEntry ce;
2091     uint8_t bus_num = pci_bus_num(bus);
2092     VTDContextCacheEntry *cc_entry;
2093     uint64_t pte, page_mask;
2094     uint32_t level = UINT32_MAX;
2095     uint32_t pasid = vtd_as->pasid;
2096     uint16_t source_id = PCI_BUILD_BDF(bus_num, devfn);
2097     int ret_fr;
2098     bool is_fpd_set = false;
2099     bool reads = true;
2100     bool writes = true;
2101     uint8_t access_flags, pgtt;
2102     bool rid2pasid = (pasid == PCI_NO_PASID) && s->root_scalable;
2103     VTDIOTLBEntry *iotlb_entry;
2104     uint64_t xlat, size;
2105 
2106     /*
2107      * We have standalone memory region for interrupt addresses, we
2108      * should never receive translation requests in this region.
2109      */
2110     assert(!vtd_is_interrupt_addr(addr));
2111 
2112     vtd_iommu_lock(s);
2113 
2114     cc_entry = &vtd_as->context_cache_entry;
2115 
2116     /* Try to fetch pte from IOTLB, we don't need RID2PASID logic */
2117     if (!rid2pasid) {
2118         iotlb_entry = vtd_lookup_iotlb(s, source_id, pasid, addr);
2119         if (iotlb_entry) {
2120             trace_vtd_iotlb_page_hit(source_id, addr, iotlb_entry->pte,
2121                                      iotlb_entry->domain_id);
2122             pte = iotlb_entry->pte;
2123             access_flags = iotlb_entry->access_flags;
2124             page_mask = iotlb_entry->mask;
2125             goto out;
2126         }
2127     }
2128 
2129     /* Try to fetch context-entry from cache first */
2130     if (cc_entry->context_cache_gen == s->context_cache_gen) {
2131         trace_vtd_iotlb_cc_hit(bus_num, devfn, cc_entry->context_entry.hi,
2132                                cc_entry->context_entry.lo,
2133                                cc_entry->context_cache_gen);
2134         ce = cc_entry->context_entry;
2135         is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;
2136         if (!is_fpd_set && s->root_scalable) {
2137             ret_fr = vtd_ce_get_pasid_fpd(s, &ce, &is_fpd_set, pasid);
2138             if (ret_fr) {
2139                 vtd_report_fault(s, -ret_fr, is_fpd_set,
2140                                  source_id, addr, is_write,
2141                                  false, 0);
2142                 goto error;
2143             }
2144         }
2145     } else {
2146         ret_fr = vtd_dev_to_context_entry(s, bus_num, devfn, &ce);
2147         is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;
2148         if (!ret_fr && !is_fpd_set && s->root_scalable) {
2149             ret_fr = vtd_ce_get_pasid_fpd(s, &ce, &is_fpd_set, pasid);
2150         }
2151         if (ret_fr) {
2152             vtd_report_fault(s, -ret_fr, is_fpd_set,
2153                              source_id, addr, is_write,
2154                              false, 0);
2155             goto error;
2156         }
2157         /* Update context-cache */
2158         trace_vtd_iotlb_cc_update(bus_num, devfn, ce.hi, ce.lo,
2159                                   cc_entry->context_cache_gen,
2160                                   s->context_cache_gen);
2161         cc_entry->context_entry = ce;
2162         cc_entry->context_cache_gen = s->context_cache_gen;
2163     }
2164 
2165     if (rid2pasid) {
2166         pasid = VTD_CE_GET_RID2PASID(&ce);
2167     }
2168 
2169     /*
2170      * We don't need to translate for pass-through context entries.
2171      * Also, let's ignore IOTLB caching as well for PT devices.
2172      */
2173     if (vtd_dev_pt_enabled(s, &ce, pasid)) {
2174         entry->iova = addr & VTD_PAGE_MASK_4K;
2175         entry->translated_addr = entry->iova;
2176         entry->addr_mask = ~VTD_PAGE_MASK_4K;
2177         entry->perm = IOMMU_RW;
2178         trace_vtd_translate_pt(source_id, entry->iova);
2179 
2180         /*
2181          * When this happens, it means firstly caching-mode is not
2182          * enabled, and this is the first passthrough translation for
2183          * the device. Let's enable the fast path for passthrough.
2184          *
2185          * When passthrough is disabled again for the device, we can
2186          * capture it via the context entry invalidation, then the
2187          * IOMMU region can be swapped back.
2188          */
2189         vtd_pt_enable_fast_path(s, source_id);
2190         vtd_iommu_unlock(s);
2191         return true;
2192     }
2193 
2194     /* Try to fetch pte from IOTLB for RID2PASID slow path */
2195     if (rid2pasid) {
2196         iotlb_entry = vtd_lookup_iotlb(s, source_id, pasid, addr);
2197         if (iotlb_entry) {
2198             trace_vtd_iotlb_page_hit(source_id, addr, iotlb_entry->pte,
2199                                      iotlb_entry->domain_id);
2200             pte = iotlb_entry->pte;
2201             access_flags = iotlb_entry->access_flags;
2202             page_mask = iotlb_entry->mask;
2203             goto out;
2204         }
2205     }
2206 
2207     if (s->flts && s->root_scalable) {
2208         ret_fr = vtd_iova_to_flpte(s, &ce, addr, is_write, &pte, &level,
2209                                    &reads, &writes, s->aw_bits, pasid);
2210         pgtt = VTD_SM_PASID_ENTRY_FLT;
2211     } else {
2212         ret_fr = vtd_iova_to_slpte(s, &ce, addr, is_write, &pte, &level,
2213                                    &reads, &writes, s->aw_bits, pasid);
2214         pgtt = VTD_SM_PASID_ENTRY_SLT;
2215     }
2216     if (!ret_fr) {
2217         xlat = vtd_get_pte_addr(pte, s->aw_bits);
2218         size = ~vtd_pt_level_page_mask(level) + 1;
2219 
2220         /*
2221          * Per VT-d spec 4.1 section 3.15: Untranslated requests and translation
2222          * requests that result in an address in the interrupt range will be
2223          * blocked with condition code LGN.4 or SGN.8.
2224          */
2225         if ((xlat <= VTD_INTERRUPT_ADDR_LAST &&
2226              xlat + size - 1 >= VTD_INTERRUPT_ADDR_FIRST)) {
2227             error_report_once("%s: xlat address is in interrupt range "
2228                               "(iova=0x%" PRIx64 ", level=0x%" PRIx32 ", "
2229                               "pte=0x%" PRIx64 ", write=%d, "
2230                               "xlat=0x%" PRIx64 ", size=0x%" PRIx64 ", "
2231                               "pasid=0x%" PRIx32 ")",
2232                               __func__, addr, level, pte, is_write,
2233                               xlat, size, pasid);
2234             ret_fr = s->scalable_mode ? -VTD_FR_SM_INTERRUPT_ADDR :
2235                                         -VTD_FR_INTERRUPT_ADDR;
2236         }
2237     }
2238 
2239     if (ret_fr) {
2240         vtd_report_fault(s, -ret_fr, is_fpd_set, source_id,
2241                          addr, is_write, pasid != PCI_NO_PASID, pasid);
2242         goto error;
2243     }
2244 
2245     page_mask = vtd_pt_level_page_mask(level);
2246     access_flags = IOMMU_ACCESS_FLAG(reads, writes);
2247     vtd_update_iotlb(s, source_id, vtd_get_domain_id(s, &ce, pasid),
2248                      addr, pte, access_flags, level, pasid, pgtt);
2249 out:
2250     vtd_iommu_unlock(s);
2251     entry->iova = addr & page_mask;
2252     entry->translated_addr = vtd_get_pte_addr(pte, s->aw_bits) & page_mask;
2253     entry->addr_mask = ~page_mask;
2254     entry->perm = (is_write ? access_flags : (access_flags & (~IOMMU_WO)));
2255     return true;
2256 
2257 error:
2258     vtd_iommu_unlock(s);
2259     entry->iova = 0;
2260     entry->translated_addr = 0;
2261     /*
2262      * Set the mask for ATS (the range must be present even when the
2263      * translation fails : PCIe rev 5 10.2.3.5)
2264      */
2265     entry->addr_mask = (level != UINT32_MAX) ?
2266                        (~vtd_pt_level_page_mask(level)) : (~VTD_PAGE_MASK_4K);
2267     entry->perm = IOMMU_NONE;
2268     return false;
2269 }
2270 
2271 static void vtd_root_table_setup(IntelIOMMUState *s)
2272 {
2273     s->root = vtd_get_quad_raw(s, DMAR_RTADDR_REG);
2274     s->root &= VTD_RTADDR_ADDR_MASK(s->aw_bits);
2275 
2276     vtd_update_scalable_state(s);
2277 
2278     trace_vtd_reg_dmar_root(s->root, s->root_scalable);
2279 }
2280 
2281 static void vtd_iec_notify_all(IntelIOMMUState *s, bool global,
2282                                uint32_t index, uint32_t mask)
2283 {
2284     x86_iommu_iec_notify_all(X86_IOMMU_DEVICE(s), global, index, mask);
2285 }
2286 
2287 static void vtd_interrupt_remap_table_setup(IntelIOMMUState *s)
2288 {
2289     uint64_t value = 0;
2290     value = vtd_get_quad_raw(s, DMAR_IRTA_REG);
2291     s->intr_size = 1UL << ((value & VTD_IRTA_SIZE_MASK) + 1);
2292     s->intr_root = value & VTD_IRTA_ADDR_MASK(s->aw_bits);
2293     s->intr_eime = value & VTD_IRTA_EIME;
2294 
2295     /* Notify global invalidation */
2296     vtd_iec_notify_all(s, true, 0, 0);
2297 
2298     trace_vtd_reg_ir_root(s->intr_root, s->intr_size);
2299 }
2300 
2301 static void vtd_iommu_replay_all(IntelIOMMUState *s)
2302 {
2303     VTDAddressSpace *vtd_as;
2304 
2305     QLIST_FOREACH(vtd_as, &s->vtd_as_with_notifiers, next) {
2306         vtd_address_space_sync(vtd_as);
2307     }
2308 }
2309 
2310 static void vtd_context_global_invalidate(IntelIOMMUState *s)
2311 {
2312     trace_vtd_inv_desc_cc_global();
2313     /* Protects context cache */
2314     vtd_iommu_lock(s);
2315     s->context_cache_gen++;
2316     if (s->context_cache_gen == VTD_CONTEXT_CACHE_GEN_MAX) {
2317         vtd_reset_context_cache_locked(s);
2318     }
2319     vtd_iommu_unlock(s);
2320     vtd_address_space_refresh_all(s);
2321     /*
2322      * From VT-d spec 6.5.2.1, a global context entry invalidation
2323      * should be followed by a IOTLB global invalidation, so we should
2324      * be safe even without this. Hoewever, let's replay the region as
2325      * well to be safer, and go back here when we need finer tunes for
2326      * VT-d emulation codes.
2327      */
2328     vtd_iommu_replay_all(s);
2329 }
2330 
2331 /* Do a context-cache device-selective invalidation.
2332  * @func_mask: FM field after shifting
2333  */
2334 static void vtd_context_device_invalidate(IntelIOMMUState *s,
2335                                           uint16_t source_id,
2336                                           uint16_t func_mask)
2337 {
2338     GHashTableIter as_it;
2339     uint16_t mask;
2340     VTDAddressSpace *vtd_as;
2341     uint8_t bus_n, devfn;
2342 
2343     trace_vtd_inv_desc_cc_devices(source_id, func_mask);
2344 
2345     switch (func_mask & 3) {
2346     case 0:
2347         mask = 0;   /* No bits in the SID field masked */
2348         break;
2349     case 1:
2350         mask = 4;   /* Mask bit 2 in the SID field */
2351         break;
2352     case 2:
2353         mask = 6;   /* Mask bit 2:1 in the SID field */
2354         break;
2355     case 3:
2356         mask = 7;   /* Mask bit 2:0 in the SID field */
2357         break;
2358     default:
2359         g_assert_not_reached();
2360     }
2361     mask = ~mask;
2362 
2363     bus_n = VTD_SID_TO_BUS(source_id);
2364     devfn = VTD_SID_TO_DEVFN(source_id);
2365 
2366     g_hash_table_iter_init(&as_it, s->vtd_address_spaces);
2367     while (g_hash_table_iter_next(&as_it, NULL, (void **)&vtd_as)) {
2368         if ((pci_bus_num(vtd_as->bus) == bus_n) &&
2369             (vtd_as->devfn & mask) == (devfn & mask)) {
2370             trace_vtd_inv_desc_cc_device(bus_n, VTD_PCI_SLOT(vtd_as->devfn),
2371                                          VTD_PCI_FUNC(vtd_as->devfn));
2372             vtd_iommu_lock(s);
2373             vtd_as->context_cache_entry.context_cache_gen = 0;
2374             vtd_iommu_unlock(s);
2375             /*
2376              * Do switch address space when needed, in case if the
2377              * device passthrough bit is switched.
2378              */
2379             vtd_switch_address_space(vtd_as);
2380             /*
2381              * So a device is moving out of (or moving into) a
2382              * domain, resync the shadow page table.
2383              * This won't bring bad even if we have no such
2384              * notifier registered - the IOMMU notification
2385              * framework will skip MAP notifications if that
2386              * happened.
2387              */
2388             vtd_address_space_sync(vtd_as);
2389         }
2390     }
2391 }
2392 
2393 /* Context-cache invalidation
2394  * Returns the Context Actual Invalidation Granularity.
2395  * @val: the content of the CCMD_REG
2396  */
2397 static uint64_t vtd_context_cache_invalidate(IntelIOMMUState *s, uint64_t val)
2398 {
2399     uint64_t caig;
2400     uint64_t type = val & VTD_CCMD_CIRG_MASK;
2401 
2402     switch (type) {
2403     case VTD_CCMD_DOMAIN_INVL:
2404         /* Fall through */
2405     case VTD_CCMD_GLOBAL_INVL:
2406         caig = VTD_CCMD_GLOBAL_INVL_A;
2407         vtd_context_global_invalidate(s);
2408         break;
2409 
2410     case VTD_CCMD_DEVICE_INVL:
2411         caig = VTD_CCMD_DEVICE_INVL_A;
2412         vtd_context_device_invalidate(s, VTD_CCMD_SID(val), VTD_CCMD_FM(val));
2413         break;
2414 
2415     default:
2416         error_report_once("%s: invalid context: 0x%" PRIx64,
2417                           __func__, val);
2418         caig = 0;
2419     }
2420     return caig;
2421 }
2422 
2423 static void vtd_iotlb_global_invalidate(IntelIOMMUState *s)
2424 {
2425     trace_vtd_inv_desc_iotlb_global();
2426     vtd_reset_iotlb(s);
2427     vtd_iommu_replay_all(s);
2428 }
2429 
2430 static void vtd_iotlb_domain_invalidate(IntelIOMMUState *s, uint16_t domain_id)
2431 {
2432     VTDContextEntry ce;
2433     VTDAddressSpace *vtd_as;
2434 
2435     trace_vtd_inv_desc_iotlb_domain(domain_id);
2436 
2437     vtd_iommu_lock(s);
2438     g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_domain,
2439                                 &domain_id);
2440     vtd_iommu_unlock(s);
2441 
2442     QLIST_FOREACH(vtd_as, &s->vtd_as_with_notifiers, next) {
2443         if (!vtd_dev_to_context_entry(s, pci_bus_num(vtd_as->bus),
2444                                       vtd_as->devfn, &ce) &&
2445             domain_id == vtd_get_domain_id(s, &ce, vtd_as->pasid)) {
2446             vtd_address_space_sync(vtd_as);
2447         }
2448     }
2449 }
2450 
2451 /*
2452  * There is no pasid field in iotlb invalidation descriptor, so PCI_NO_PASID
2453  * is passed as parameter. Piotlb invalidation supports pasid, pasid in its
2454  * descriptor is passed which should not be PCI_NO_PASID.
2455  */
2456 static void vtd_iotlb_page_invalidate_notify(IntelIOMMUState *s,
2457                                              uint16_t domain_id, hwaddr addr,
2458                                              uint8_t am, uint32_t pasid)
2459 {
2460     VTDAddressSpace *vtd_as;
2461     VTDContextEntry ce;
2462     int ret;
2463     hwaddr size = (1 << am) * VTD_PAGE_SIZE;
2464 
2465     QLIST_FOREACH(vtd_as, &(s->vtd_as_with_notifiers), next) {
2466         ret = vtd_dev_to_context_entry(s, pci_bus_num(vtd_as->bus),
2467                                        vtd_as->devfn, &ce);
2468         if (!ret && domain_id == vtd_get_domain_id(s, &ce, vtd_as->pasid)) {
2469             uint32_t rid2pasid = PCI_NO_PASID;
2470 
2471             if (s->root_scalable) {
2472                 rid2pasid = VTD_CE_GET_RID2PASID(&ce);
2473             }
2474 
2475             /*
2476              * In legacy mode, vtd_as->pasid == pasid is always true.
2477              * In scalable mode, for vtd address space backing a PCI
2478              * device without pasid, needs to compare pasid with
2479              * rid2pasid of this device.
2480              */
2481             if (!(vtd_as->pasid == pasid ||
2482                   (vtd_as->pasid == PCI_NO_PASID && pasid == rid2pasid))) {
2483                 continue;
2484             }
2485 
2486             if (vtd_as_has_map_notifier(vtd_as)) {
2487                 /*
2488                  * When stage-1 translation is off, as long as we have MAP
2489                  * notifications registered in any of our IOMMU notifiers,
2490                  * we need to sync the shadow page table. Otherwise VFIO
2491                  * device attaches to nested page table instead of shadow
2492                  * page table, so no need to sync.
2493                  */
2494                 if (!s->flts || !s->root_scalable) {
2495                     vtd_sync_shadow_page_table_range(vtd_as, &ce, addr, size);
2496                 }
2497             } else {
2498                 /*
2499                  * For UNMAP-only notifiers, we don't need to walk the
2500                  * page tables.  We just deliver the PSI down to
2501                  * invalidate caches.
2502                  */
2503                 const IOMMUTLBEvent event = {
2504                     .type = IOMMU_NOTIFIER_UNMAP,
2505                     .entry = {
2506                         .target_as = &address_space_memory,
2507                         .iova = addr,
2508                         .translated_addr = 0,
2509                         .addr_mask = size - 1,
2510                         .perm = IOMMU_NONE,
2511                         .pasid = vtd_as->pasid,
2512                     },
2513                 };
2514                 memory_region_notify_iommu(&vtd_as->iommu, 0, event);
2515             }
2516         }
2517     }
2518 }
2519 
2520 static void vtd_iotlb_page_invalidate(IntelIOMMUState *s, uint16_t domain_id,
2521                                       hwaddr addr, uint8_t am)
2522 {
2523     VTDIOTLBPageInvInfo info;
2524 
2525     trace_vtd_inv_desc_iotlb_pages(domain_id, addr, am);
2526 
2527     assert(am <= VTD_MAMV);
2528     info.domain_id = domain_id;
2529     info.addr = addr;
2530     info.mask = ~((1 << am) - 1);
2531     vtd_iommu_lock(s);
2532     g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_page, &info);
2533     vtd_iommu_unlock(s);
2534     vtd_iotlb_page_invalidate_notify(s, domain_id, addr, am, PCI_NO_PASID);
2535 }
2536 
2537 /* Flush IOTLB
2538  * Returns the IOTLB Actual Invalidation Granularity.
2539  * @val: the content of the IOTLB_REG
2540  */
2541 static uint64_t vtd_iotlb_flush(IntelIOMMUState *s, uint64_t val)
2542 {
2543     uint64_t iaig;
2544     uint64_t type = val & VTD_TLB_FLUSH_GRANU_MASK;
2545     uint16_t domain_id;
2546     hwaddr addr;
2547     uint8_t am;
2548 
2549     switch (type) {
2550     case VTD_TLB_GLOBAL_FLUSH:
2551         iaig = VTD_TLB_GLOBAL_FLUSH_A;
2552         vtd_iotlb_global_invalidate(s);
2553         break;
2554 
2555     case VTD_TLB_DSI_FLUSH:
2556         domain_id = VTD_TLB_DID(val);
2557         iaig = VTD_TLB_DSI_FLUSH_A;
2558         vtd_iotlb_domain_invalidate(s, domain_id);
2559         break;
2560 
2561     case VTD_TLB_PSI_FLUSH:
2562         domain_id = VTD_TLB_DID(val);
2563         addr = vtd_get_quad_raw(s, DMAR_IVA_REG);
2564         am = VTD_IVA_AM(addr);
2565         addr = VTD_IVA_ADDR(addr);
2566         if (am > VTD_MAMV) {
2567             error_report_once("%s: address mask overflow: 0x%" PRIx64,
2568                               __func__, vtd_get_quad_raw(s, DMAR_IVA_REG));
2569             iaig = 0;
2570             break;
2571         }
2572         iaig = VTD_TLB_PSI_FLUSH_A;
2573         vtd_iotlb_page_invalidate(s, domain_id, addr, am);
2574         break;
2575 
2576     default:
2577         error_report_once("%s: invalid granularity: 0x%" PRIx64,
2578                           __func__, val);
2579         iaig = 0;
2580     }
2581     return iaig;
2582 }
2583 
2584 static void vtd_fetch_inv_desc(IntelIOMMUState *s);
2585 
2586 static inline bool vtd_queued_inv_disable_check(IntelIOMMUState *s)
2587 {
2588     return s->qi_enabled && (s->iq_tail == s->iq_head) &&
2589            (s->iq_last_desc_type == VTD_INV_DESC_WAIT);
2590 }
2591 
2592 static void vtd_handle_gcmd_qie(IntelIOMMUState *s, bool en)
2593 {
2594     uint64_t iqa_val = vtd_get_quad_raw(s, DMAR_IQA_REG);
2595 
2596     trace_vtd_inv_qi_enable(en);
2597 
2598     if (en) {
2599         s->iq = iqa_val & VTD_IQA_IQA_MASK(s->aw_bits);
2600         /* 2^(x+8) entries */
2601         s->iq_size = 1UL << ((iqa_val & VTD_IQA_QS) + 8 - (s->iq_dw ? 1 : 0));
2602         s->qi_enabled = true;
2603         trace_vtd_inv_qi_setup(s->iq, s->iq_size);
2604         /* Ok - report back to driver */
2605         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_QIES);
2606 
2607         if (s->iq_tail != 0) {
2608             /*
2609              * This is a spec violation but Windows guests are known to set up
2610              * Queued Invalidation this way so we allow the write and process
2611              * Invalidation Descriptors right away.
2612              */
2613             trace_vtd_warn_invalid_qi_tail(s->iq_tail);
2614             if (!(vtd_get_long_raw(s, DMAR_FSTS_REG) & VTD_FSTS_IQE)) {
2615                 vtd_fetch_inv_desc(s);
2616             }
2617         }
2618     } else {
2619         if (vtd_queued_inv_disable_check(s)) {
2620             /* disable Queued Invalidation */
2621             vtd_set_quad_raw(s, DMAR_IQH_REG, 0);
2622             s->iq_head = 0;
2623             s->qi_enabled = false;
2624             /* Ok - report back to driver */
2625             vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_QIES, 0);
2626         } else {
2627             error_report_once("%s: detected improper state when disable QI "
2628                               "(head=0x%x, tail=0x%x, last_type=%d)",
2629                               __func__,
2630                               s->iq_head, s->iq_tail, s->iq_last_desc_type);
2631         }
2632     }
2633 }
2634 
2635 /* Set Root Table Pointer */
2636 static void vtd_handle_gcmd_srtp(IntelIOMMUState *s)
2637 {
2638     vtd_root_table_setup(s);
2639     /* Ok - report back to driver */
2640     vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_RTPS);
2641     vtd_reset_caches(s);
2642     vtd_address_space_refresh_all(s);
2643 }
2644 
2645 /* Set Interrupt Remap Table Pointer */
2646 static void vtd_handle_gcmd_sirtp(IntelIOMMUState *s)
2647 {
2648     vtd_interrupt_remap_table_setup(s);
2649     /* Ok - report back to driver */
2650     vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_IRTPS);
2651 }
2652 
2653 /* Handle Translation Enable/Disable */
2654 static void vtd_handle_gcmd_te(IntelIOMMUState *s, bool en)
2655 {
2656     if (s->dmar_enabled == en) {
2657         return;
2658     }
2659 
2660     trace_vtd_dmar_enable(en);
2661 
2662     if (en) {
2663         s->dmar_enabled = true;
2664         /* Ok - report back to driver */
2665         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_TES);
2666     } else {
2667         s->dmar_enabled = false;
2668 
2669         /* Clear the index of Fault Recording Register */
2670         s->next_frcd_reg = 0;
2671         /* Ok - report back to driver */
2672         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_TES, 0);
2673     }
2674 
2675     vtd_reset_caches(s);
2676     vtd_address_space_refresh_all(s);
2677 }
2678 
2679 /* Handle Interrupt Remap Enable/Disable */
2680 static void vtd_handle_gcmd_ire(IntelIOMMUState *s, bool en)
2681 {
2682     trace_vtd_ir_enable(en);
2683 
2684     if (en) {
2685         s->intr_enabled = true;
2686         /* Ok - report back to driver */
2687         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_IRES);
2688     } else {
2689         s->intr_enabled = false;
2690         /* Ok - report back to driver */
2691         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_IRES, 0);
2692     }
2693 }
2694 
2695 /* Handle write to Global Command Register */
2696 static void vtd_handle_gcmd_write(IntelIOMMUState *s)
2697 {
2698     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
2699     uint32_t status = vtd_get_long_raw(s, DMAR_GSTS_REG);
2700     uint32_t val = vtd_get_long_raw(s, DMAR_GCMD_REG);
2701     uint32_t changed = status ^ val;
2702 
2703     trace_vtd_reg_write_gcmd(status, val);
2704     if ((changed & VTD_GCMD_TE) && s->dma_translation) {
2705         /* Translation enable/disable */
2706         vtd_handle_gcmd_te(s, val & VTD_GCMD_TE);
2707     }
2708     if (val & VTD_GCMD_SRTP) {
2709         /* Set/update the root-table pointer */
2710         vtd_handle_gcmd_srtp(s);
2711     }
2712     if (changed & VTD_GCMD_QIE) {
2713         /* Queued Invalidation Enable */
2714         vtd_handle_gcmd_qie(s, val & VTD_GCMD_QIE);
2715     }
2716     if (val & VTD_GCMD_SIRTP) {
2717         /* Set/update the interrupt remapping root-table pointer */
2718         vtd_handle_gcmd_sirtp(s);
2719     }
2720     if ((changed & VTD_GCMD_IRE) &&
2721         x86_iommu_ir_supported(x86_iommu)) {
2722         /* Interrupt remap enable/disable */
2723         vtd_handle_gcmd_ire(s, val & VTD_GCMD_IRE);
2724     }
2725 }
2726 
2727 /* Handle write to Context Command Register */
2728 static void vtd_handle_ccmd_write(IntelIOMMUState *s)
2729 {
2730     uint64_t ret;
2731     uint64_t val = vtd_get_quad_raw(s, DMAR_CCMD_REG);
2732 
2733     /* Context-cache invalidation request */
2734     if (val & VTD_CCMD_ICC) {
2735         if (s->qi_enabled) {
2736             error_report_once("Queued Invalidation enabled, "
2737                               "should not use register-based invalidation");
2738             return;
2739         }
2740         ret = vtd_context_cache_invalidate(s, val);
2741         /* Invalidation completed. Change something to show */
2742         vtd_set_clear_mask_quad(s, DMAR_CCMD_REG, VTD_CCMD_ICC, 0ULL);
2743         ret = vtd_set_clear_mask_quad(s, DMAR_CCMD_REG, VTD_CCMD_CAIG_MASK,
2744                                       ret);
2745     }
2746 }
2747 
2748 /* Handle write to IOTLB Invalidation Register */
2749 static void vtd_handle_iotlb_write(IntelIOMMUState *s)
2750 {
2751     uint64_t ret;
2752     uint64_t val = vtd_get_quad_raw(s, DMAR_IOTLB_REG);
2753 
2754     /* IOTLB invalidation request */
2755     if (val & VTD_TLB_IVT) {
2756         if (s->qi_enabled) {
2757             error_report_once("Queued Invalidation enabled, "
2758                               "should not use register-based invalidation");
2759             return;
2760         }
2761         ret = vtd_iotlb_flush(s, val);
2762         /* Invalidation completed. Change something to show */
2763         vtd_set_clear_mask_quad(s, DMAR_IOTLB_REG, VTD_TLB_IVT, 0ULL);
2764         ret = vtd_set_clear_mask_quad(s, DMAR_IOTLB_REG,
2765                                       VTD_TLB_FLUSH_GRANU_MASK_A, ret);
2766     }
2767 }
2768 
2769 /* Fetch an Invalidation Descriptor from the Invalidation Queue */
2770 static bool vtd_get_inv_desc(IntelIOMMUState *s,
2771                              VTDInvDesc *inv_desc)
2772 {
2773     dma_addr_t base_addr = s->iq;
2774     uint32_t offset = s->iq_head;
2775     uint32_t dw = s->iq_dw ? 32 : 16;
2776     dma_addr_t addr = base_addr + offset * dw;
2777 
2778     if (dma_memory_read(&address_space_memory, addr,
2779                         inv_desc, dw, MEMTXATTRS_UNSPECIFIED)) {
2780         error_report_once("Read INV DESC failed.");
2781         return false;
2782     }
2783     inv_desc->lo = le64_to_cpu(inv_desc->lo);
2784     inv_desc->hi = le64_to_cpu(inv_desc->hi);
2785     if (dw == 32) {
2786         inv_desc->val[2] = le64_to_cpu(inv_desc->val[2]);
2787         inv_desc->val[3] = le64_to_cpu(inv_desc->val[3]);
2788     }
2789     return true;
2790 }
2791 
2792 static bool vtd_inv_desc_reserved_check(IntelIOMMUState *s,
2793                                         VTDInvDesc *inv_desc,
2794                                         uint64_t mask[4], bool dw,
2795                                         const char *func_name,
2796                                         const char *desc_type)
2797 {
2798     if (s->iq_dw) {
2799         if (inv_desc->val[0] & mask[0] || inv_desc->val[1] & mask[1] ||
2800             inv_desc->val[2] & mask[2] || inv_desc->val[3] & mask[3]) {
2801             error_report("%s: invalid %s desc val[3]: 0x%"PRIx64
2802                          " val[2]: 0x%"PRIx64" val[1]=0x%"PRIx64
2803                          " val[0]=0x%"PRIx64" (reserved nonzero)",
2804                          func_name, desc_type, inv_desc->val[3],
2805                          inv_desc->val[2], inv_desc->val[1],
2806                          inv_desc->val[0]);
2807             return false;
2808         }
2809     } else {
2810         if (dw) {
2811             error_report("%s: 256-bit %s desc in 128-bit invalidation queue",
2812                          func_name, desc_type);
2813             return false;
2814         }
2815 
2816         if (inv_desc->lo & mask[0] || inv_desc->hi & mask[1]) {
2817             error_report("%s: invalid %s desc: hi=%"PRIx64", lo=%"PRIx64
2818                          " (reserved nonzero)", func_name, desc_type,
2819                          inv_desc->hi, inv_desc->lo);
2820             return false;
2821         }
2822     }
2823 
2824     return true;
2825 }
2826 
2827 static bool vtd_process_wait_desc(IntelIOMMUState *s, VTDInvDesc *inv_desc)
2828 {
2829     uint64_t mask[4] = {VTD_INV_DESC_WAIT_RSVD_LO, VTD_INV_DESC_WAIT_RSVD_HI,
2830                         VTD_INV_DESC_ALL_ONE, VTD_INV_DESC_ALL_ONE};
2831 
2832     if (!vtd_inv_desc_reserved_check(s, inv_desc, mask, false,
2833                                      __func__, "wait")) {
2834         return false;
2835     }
2836 
2837     if (inv_desc->lo & VTD_INV_DESC_WAIT_SW) {
2838         /* Status Write */
2839         uint32_t status_data = (uint32_t)(inv_desc->lo >>
2840                                VTD_INV_DESC_WAIT_DATA_SHIFT);
2841 
2842         assert(!(inv_desc->lo & VTD_INV_DESC_WAIT_IF));
2843 
2844         /* FIXME: need to be masked with HAW? */
2845         dma_addr_t status_addr = inv_desc->hi;
2846         trace_vtd_inv_desc_wait_sw(status_addr, status_data);
2847         status_data = cpu_to_le32(status_data);
2848         if (dma_memory_write(&address_space_memory, status_addr,
2849                              &status_data, sizeof(status_data),
2850                              MEMTXATTRS_UNSPECIFIED)) {
2851             trace_vtd_inv_desc_wait_write_fail(inv_desc->hi, inv_desc->lo);
2852             return false;
2853         }
2854     } else if (inv_desc->lo & VTD_INV_DESC_WAIT_IF) {
2855         /* Interrupt flag */
2856         vtd_generate_completion_event(s);
2857     } else {
2858         error_report_once("%s: invalid wait desc: hi=%"PRIx64", lo=%"PRIx64
2859                           " (unknown type)", __func__, inv_desc->hi,
2860                           inv_desc->lo);
2861         return false;
2862     }
2863     return true;
2864 }
2865 
2866 static bool vtd_process_context_cache_desc(IntelIOMMUState *s,
2867                                            VTDInvDesc *inv_desc)
2868 {
2869     uint16_t sid, fmask;
2870     uint64_t mask[4] = {VTD_INV_DESC_CC_RSVD, VTD_INV_DESC_ALL_ONE,
2871                         VTD_INV_DESC_ALL_ONE, VTD_INV_DESC_ALL_ONE};
2872 
2873     if (!vtd_inv_desc_reserved_check(s, inv_desc, mask, false,
2874                                      __func__, "cc inv")) {
2875         return false;
2876     }
2877 
2878     switch (inv_desc->lo & VTD_INV_DESC_CC_G) {
2879     case VTD_INV_DESC_CC_DOMAIN:
2880         trace_vtd_inv_desc_cc_domain(
2881             (uint16_t)VTD_INV_DESC_CC_DID(inv_desc->lo));
2882         /* Fall through */
2883     case VTD_INV_DESC_CC_GLOBAL:
2884         vtd_context_global_invalidate(s);
2885         break;
2886 
2887     case VTD_INV_DESC_CC_DEVICE:
2888         sid = VTD_INV_DESC_CC_SID(inv_desc->lo);
2889         fmask = VTD_INV_DESC_CC_FM(inv_desc->lo);
2890         vtd_context_device_invalidate(s, sid, fmask);
2891         break;
2892 
2893     default:
2894         error_report_once("%s: invalid cc inv desc: hi=%"PRIx64", lo=%"PRIx64
2895                           " (invalid type)", __func__, inv_desc->hi,
2896                           inv_desc->lo);
2897         return false;
2898     }
2899     return true;
2900 }
2901 
2902 static bool vtd_process_iotlb_desc(IntelIOMMUState *s, VTDInvDesc *inv_desc)
2903 {
2904     uint16_t domain_id;
2905     uint8_t am;
2906     hwaddr addr;
2907     uint64_t mask[4] = {VTD_INV_DESC_IOTLB_RSVD_LO, VTD_INV_DESC_IOTLB_RSVD_HI,
2908                         VTD_INV_DESC_ALL_ONE, VTD_INV_DESC_ALL_ONE};
2909 
2910     if (!vtd_inv_desc_reserved_check(s, inv_desc, mask, false,
2911                                      __func__, "iotlb inv")) {
2912         return false;
2913     }
2914 
2915     switch (inv_desc->lo & VTD_INV_DESC_IOTLB_G) {
2916     case VTD_INV_DESC_IOTLB_GLOBAL:
2917         vtd_iotlb_global_invalidate(s);
2918         break;
2919 
2920     case VTD_INV_DESC_IOTLB_DOMAIN:
2921         domain_id = VTD_INV_DESC_IOTLB_DID(inv_desc->lo);
2922         vtd_iotlb_domain_invalidate(s, domain_id);
2923         break;
2924 
2925     case VTD_INV_DESC_IOTLB_PAGE:
2926         domain_id = VTD_INV_DESC_IOTLB_DID(inv_desc->lo);
2927         addr = VTD_INV_DESC_IOTLB_ADDR(inv_desc->hi);
2928         am = VTD_INV_DESC_IOTLB_AM(inv_desc->hi);
2929         if (am > VTD_MAMV) {
2930             error_report_once("%s: invalid iotlb inv desc: hi=0x%"PRIx64
2931                               ", lo=0x%"PRIx64" (am=%u > VTD_MAMV=%u)",
2932                               __func__, inv_desc->hi, inv_desc->lo,
2933                               am, (unsigned)VTD_MAMV);
2934             return false;
2935         }
2936         vtd_iotlb_page_invalidate(s, domain_id, addr, am);
2937         break;
2938 
2939     default:
2940         error_report_once("%s: invalid iotlb inv desc: hi=0x%"PRIx64
2941                           ", lo=0x%"PRIx64" (type mismatch: 0x%llx)",
2942                           __func__, inv_desc->hi, inv_desc->lo,
2943                           inv_desc->lo & VTD_INV_DESC_IOTLB_G);
2944         return false;
2945     }
2946     return true;
2947 }
2948 
2949 static gboolean vtd_hash_remove_by_pasid(gpointer key, gpointer value,
2950                                          gpointer user_data)
2951 {
2952     VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value;
2953     VTDIOTLBPageInvInfo *info = (VTDIOTLBPageInvInfo *)user_data;
2954 
2955     return ((entry->domain_id == info->domain_id) &&
2956             (entry->pasid == info->pasid));
2957 }
2958 
2959 static void vtd_piotlb_pasid_invalidate(IntelIOMMUState *s,
2960                                         uint16_t domain_id, uint32_t pasid)
2961 {
2962     VTDIOTLBPageInvInfo info;
2963     VTDAddressSpace *vtd_as;
2964     VTDContextEntry ce;
2965 
2966     info.domain_id = domain_id;
2967     info.pasid = pasid;
2968 
2969     vtd_iommu_lock(s);
2970     g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_pasid,
2971                                 &info);
2972     vtd_iommu_unlock(s);
2973 
2974     QLIST_FOREACH(vtd_as, &s->vtd_as_with_notifiers, next) {
2975         if (!vtd_dev_to_context_entry(s, pci_bus_num(vtd_as->bus),
2976                                       vtd_as->devfn, &ce) &&
2977             domain_id == vtd_get_domain_id(s, &ce, vtd_as->pasid)) {
2978             uint32_t rid2pasid = VTD_CE_GET_RID2PASID(&ce);
2979 
2980             if ((vtd_as->pasid != PCI_NO_PASID || pasid != rid2pasid) &&
2981                 vtd_as->pasid != pasid) {
2982                 continue;
2983             }
2984 
2985             if (!s->flts || !vtd_as_has_map_notifier(vtd_as)) {
2986                 vtd_address_space_sync(vtd_as);
2987             }
2988         }
2989     }
2990 }
2991 
2992 static void vtd_piotlb_page_invalidate(IntelIOMMUState *s, uint16_t domain_id,
2993                                        uint32_t pasid, hwaddr addr, uint8_t am)
2994 {
2995     VTDIOTLBPageInvInfo info;
2996 
2997     info.domain_id = domain_id;
2998     info.pasid = pasid;
2999     info.addr = addr;
3000     info.mask = ~((1 << am) - 1);
3001 
3002     vtd_iommu_lock(s);
3003     g_hash_table_foreach_remove(s->iotlb,
3004                                 vtd_hash_remove_by_page_piotlb, &info);
3005     vtd_iommu_unlock(s);
3006 
3007     vtd_iotlb_page_invalidate_notify(s, domain_id, addr, am, pasid);
3008 }
3009 
3010 static bool vtd_process_piotlb_desc(IntelIOMMUState *s,
3011                                     VTDInvDesc *inv_desc)
3012 {
3013     uint16_t domain_id;
3014     uint32_t pasid;
3015     hwaddr addr;
3016     uint8_t am;
3017     uint64_t mask[4] = {VTD_INV_DESC_PIOTLB_RSVD_VAL0,
3018                         VTD_INV_DESC_PIOTLB_RSVD_VAL1,
3019                         VTD_INV_DESC_ALL_ONE, VTD_INV_DESC_ALL_ONE};
3020 
3021     if (!vtd_inv_desc_reserved_check(s, inv_desc, mask, true,
3022                                      __func__, "piotlb inv")) {
3023         return false;
3024     }
3025 
3026     domain_id = VTD_INV_DESC_PIOTLB_DID(inv_desc->val[0]);
3027     pasid = VTD_INV_DESC_PIOTLB_PASID(inv_desc->val[0]);
3028     switch (inv_desc->val[0] & VTD_INV_DESC_PIOTLB_G) {
3029     case VTD_INV_DESC_PIOTLB_ALL_IN_PASID:
3030         vtd_piotlb_pasid_invalidate(s, domain_id, pasid);
3031         break;
3032 
3033     case VTD_INV_DESC_PIOTLB_PSI_IN_PASID:
3034         am = VTD_INV_DESC_PIOTLB_AM(inv_desc->val[1]);
3035         addr = (hwaddr) VTD_INV_DESC_PIOTLB_ADDR(inv_desc->val[1]);
3036         vtd_piotlb_page_invalidate(s, domain_id, pasid, addr, am);
3037         break;
3038 
3039     default:
3040         error_report_once("%s: invalid piotlb inv desc: hi=0x%"PRIx64
3041                           ", lo=0x%"PRIx64" (type mismatch: 0x%llx)",
3042                           __func__, inv_desc->val[1], inv_desc->val[0],
3043                           inv_desc->val[0] & VTD_INV_DESC_IOTLB_G);
3044         return false;
3045     }
3046     return true;
3047 }
3048 
3049 static bool vtd_process_inv_iec_desc(IntelIOMMUState *s,
3050                                      VTDInvDesc *inv_desc)
3051 {
3052     uint64_t mask[4] = {VTD_INV_DESC_IEC_RSVD, VTD_INV_DESC_ALL_ONE,
3053                         VTD_INV_DESC_ALL_ONE, VTD_INV_DESC_ALL_ONE};
3054 
3055     if (!vtd_inv_desc_reserved_check(s, inv_desc, mask, false,
3056                                      __func__, "iec inv")) {
3057         return false;
3058     }
3059 
3060     trace_vtd_inv_desc_iec(inv_desc->iec.granularity,
3061                            inv_desc->iec.index,
3062                            inv_desc->iec.index_mask);
3063 
3064     vtd_iec_notify_all(s, !inv_desc->iec.granularity,
3065                        inv_desc->iec.index,
3066                        inv_desc->iec.index_mask);
3067     return true;
3068 }
3069 
3070 static void do_invalidate_device_tlb(VTDAddressSpace *vtd_dev_as,
3071                                      bool size, hwaddr addr)
3072 {
3073     /*
3074      * According to ATS spec table 2.4:
3075      * S = 0, bits 15:12 = xxxx     range size: 4K
3076      * S = 1, bits 15:12 = xxx0     range size: 8K
3077      * S = 1, bits 15:12 = xx01     range size: 16K
3078      * S = 1, bits 15:12 = x011     range size: 32K
3079      * S = 1, bits 15:12 = 0111     range size: 64K
3080      * ...
3081      */
3082 
3083     IOMMUTLBEvent event;
3084     uint64_t sz;
3085 
3086     if (size) {
3087         sz = (VTD_PAGE_SIZE * 2) << cto64(addr >> VTD_PAGE_SHIFT);
3088         addr &= ~(sz - 1);
3089     } else {
3090         sz = VTD_PAGE_SIZE;
3091     }
3092 
3093     event.type = IOMMU_NOTIFIER_DEVIOTLB_UNMAP;
3094     event.entry.target_as = &vtd_dev_as->as;
3095     event.entry.addr_mask = sz - 1;
3096     event.entry.iova = addr;
3097     event.entry.perm = IOMMU_NONE;
3098     event.entry.translated_addr = 0;
3099     event.entry.pasid = vtd_dev_as->pasid;
3100     memory_region_notify_iommu(&vtd_dev_as->iommu, 0, event);
3101 }
3102 
3103 static bool vtd_process_device_piotlb_desc(IntelIOMMUState *s,
3104                                            VTDInvDesc *inv_desc)
3105 {
3106     uint16_t sid;
3107     VTDAddressSpace *vtd_dev_as;
3108     bool size;
3109     bool global;
3110     hwaddr addr;
3111     uint32_t pasid;
3112     uint64_t mask[4] = {VTD_INV_DESC_PASID_DEVICE_IOTLB_RSVD_VAL0,
3113                         VTD_INV_DESC_PASID_DEVICE_IOTLB_RSVD_VAL1,
3114                         VTD_INV_DESC_ALL_ONE, VTD_INV_DESC_ALL_ONE};
3115 
3116     if (!vtd_inv_desc_reserved_check(s, inv_desc, mask, true,
3117                                      __func__, "device piotlb inv")) {
3118         return false;
3119     }
3120 
3121     global = VTD_INV_DESC_PASID_DEVICE_IOTLB_GLOBAL(inv_desc->hi);
3122     size = VTD_INV_DESC_PASID_DEVICE_IOTLB_SIZE(inv_desc->hi);
3123     addr = VTD_INV_DESC_PASID_DEVICE_IOTLB_ADDR(inv_desc->hi);
3124     sid = VTD_INV_DESC_PASID_DEVICE_IOTLB_SID(inv_desc->lo);
3125     if (global) {
3126         QLIST_FOREACH(vtd_dev_as, &s->vtd_as_with_notifiers, next) {
3127             if ((vtd_dev_as->pasid != PCI_NO_PASID) &&
3128                 (PCI_BUILD_BDF(pci_bus_num(vtd_dev_as->bus),
3129                                            vtd_dev_as->devfn) == sid)) {
3130                 do_invalidate_device_tlb(vtd_dev_as, size, addr);
3131             }
3132         }
3133     } else {
3134         pasid = VTD_INV_DESC_PASID_DEVICE_IOTLB_PASID(inv_desc->lo);
3135         vtd_dev_as = vtd_get_as_by_sid_and_pasid(s, sid, pasid);
3136         if (!vtd_dev_as) {
3137             return true;
3138         }
3139 
3140         do_invalidate_device_tlb(vtd_dev_as, size, addr);
3141     }
3142 
3143     return true;
3144 }
3145 
3146 static bool vtd_process_device_iotlb_desc(IntelIOMMUState *s,
3147                                           VTDInvDesc *inv_desc)
3148 {
3149     VTDAddressSpace *vtd_dev_as;
3150     hwaddr addr;
3151     uint16_t sid;
3152     bool size;
3153     uint64_t mask[4] = {VTD_INV_DESC_DEVICE_IOTLB_RSVD_LO,
3154                         VTD_INV_DESC_DEVICE_IOTLB_RSVD_HI,
3155                         VTD_INV_DESC_ALL_ONE, VTD_INV_DESC_ALL_ONE};
3156 
3157     if (!vtd_inv_desc_reserved_check(s, inv_desc, mask, false,
3158                                      __func__, "dev-iotlb inv")) {
3159         return false;
3160     }
3161 
3162     addr = VTD_INV_DESC_DEVICE_IOTLB_ADDR(inv_desc->hi);
3163     sid = VTD_INV_DESC_DEVICE_IOTLB_SID(inv_desc->lo);
3164     size = VTD_INV_DESC_DEVICE_IOTLB_SIZE(inv_desc->hi);
3165 
3166     /*
3167      * Using sid is OK since the guest should have finished the
3168      * initialization of both the bus and device.
3169      */
3170     vtd_dev_as = vtd_get_as_by_sid(s, sid);
3171     if (!vtd_dev_as) {
3172         goto done;
3173     }
3174 
3175     do_invalidate_device_tlb(vtd_dev_as, size, addr);
3176 
3177 done:
3178     return true;
3179 }
3180 
3181 static bool vtd_process_inv_desc(IntelIOMMUState *s)
3182 {
3183     VTDInvDesc inv_desc;
3184     uint8_t desc_type;
3185 
3186     trace_vtd_inv_qi_head(s->iq_head);
3187     if (!vtd_get_inv_desc(s, &inv_desc)) {
3188         s->iq_last_desc_type = VTD_INV_DESC_NONE;
3189         return false;
3190     }
3191 
3192     desc_type = VTD_INV_DESC_TYPE(inv_desc.lo);
3193     /* FIXME: should update at first or at last? */
3194     s->iq_last_desc_type = desc_type;
3195 
3196     switch (desc_type) {
3197     case VTD_INV_DESC_CC:
3198         trace_vtd_inv_desc("context-cache", inv_desc.hi, inv_desc.lo);
3199         if (!vtd_process_context_cache_desc(s, &inv_desc)) {
3200             return false;
3201         }
3202         break;
3203 
3204     case VTD_INV_DESC_IOTLB:
3205         trace_vtd_inv_desc("iotlb", inv_desc.hi, inv_desc.lo);
3206         if (!vtd_process_iotlb_desc(s, &inv_desc)) {
3207             return false;
3208         }
3209         break;
3210 
3211     case VTD_INV_DESC_PIOTLB:
3212         trace_vtd_inv_desc("p-iotlb", inv_desc.val[1], inv_desc.val[0]);
3213         if (!vtd_process_piotlb_desc(s, &inv_desc)) {
3214             return false;
3215         }
3216         break;
3217 
3218     case VTD_INV_DESC_WAIT:
3219         trace_vtd_inv_desc("wait", inv_desc.hi, inv_desc.lo);
3220         if (!vtd_process_wait_desc(s, &inv_desc)) {
3221             return false;
3222         }
3223         break;
3224 
3225     case VTD_INV_DESC_IEC:
3226         trace_vtd_inv_desc("iec", inv_desc.hi, inv_desc.lo);
3227         if (!vtd_process_inv_iec_desc(s, &inv_desc)) {
3228             return false;
3229         }
3230         break;
3231 
3232     case VTD_INV_DESC_DEV_PIOTLB:
3233         trace_vtd_inv_desc("device-piotlb", inv_desc.hi, inv_desc.lo);
3234         if (!vtd_process_device_piotlb_desc(s, &inv_desc)) {
3235             return false;
3236         }
3237         break;
3238 
3239     case VTD_INV_DESC_DEVICE:
3240         trace_vtd_inv_desc("device", inv_desc.hi, inv_desc.lo);
3241         if (!vtd_process_device_iotlb_desc(s, &inv_desc)) {
3242             return false;
3243         }
3244         break;
3245 
3246     /*
3247      * TODO: the entity of below two cases will be implemented in future series.
3248      * To make guest (which integrates scalable mode support patch set in
3249      * iommu driver) work, just return true is enough so far.
3250      */
3251     case VTD_INV_DESC_PC:
3252         if (s->scalable_mode) {
3253             break;
3254         }
3255     /* fallthrough */
3256     default:
3257         error_report_once("%s: invalid inv desc: hi=%"PRIx64", lo=%"PRIx64
3258                           " (unknown type)", __func__, inv_desc.hi,
3259                           inv_desc.lo);
3260         return false;
3261     }
3262     s->iq_head++;
3263     if (s->iq_head == s->iq_size) {
3264         s->iq_head = 0;
3265     }
3266     return true;
3267 }
3268 
3269 /* Try to fetch and process more Invalidation Descriptors */
3270 static void vtd_fetch_inv_desc(IntelIOMMUState *s)
3271 {
3272     int qi_shift;
3273 
3274     /* Refer to 10.4.23 of VT-d spec 3.0 */
3275     qi_shift = s->iq_dw ? VTD_IQH_QH_SHIFT_5 : VTD_IQH_QH_SHIFT_4;
3276 
3277     trace_vtd_inv_qi_fetch();
3278 
3279     if (s->iq_tail >= s->iq_size) {
3280         /* Detects an invalid Tail pointer */
3281         error_report_once("%s: detected invalid QI tail "
3282                           "(tail=0x%x, size=0x%x)",
3283                           __func__, s->iq_tail, s->iq_size);
3284         vtd_handle_inv_queue_error(s);
3285         return;
3286     }
3287     while (s->iq_head != s->iq_tail) {
3288         if (!vtd_process_inv_desc(s)) {
3289             /* Invalidation Queue Errors */
3290             vtd_handle_inv_queue_error(s);
3291             break;
3292         }
3293         /* Must update the IQH_REG in time */
3294         vtd_set_quad_raw(s, DMAR_IQH_REG,
3295                          (((uint64_t)(s->iq_head)) << qi_shift) &
3296                          VTD_IQH_QH_MASK);
3297     }
3298 }
3299 
3300 /* Handle write to Invalidation Queue Tail Register */
3301 static void vtd_handle_iqt_write(IntelIOMMUState *s)
3302 {
3303     uint64_t val = vtd_get_quad_raw(s, DMAR_IQT_REG);
3304 
3305     if (s->iq_dw && (val & VTD_IQT_QT_256_RSV_BIT)) {
3306         error_report_once("%s: RSV bit is set: val=0x%"PRIx64,
3307                           __func__, val);
3308         vtd_handle_inv_queue_error(s);
3309         return;
3310     }
3311     s->iq_tail = VTD_IQT_QT(s->iq_dw, val);
3312     trace_vtd_inv_qi_tail(s->iq_tail);
3313 
3314     if (s->qi_enabled && !(vtd_get_long_raw(s, DMAR_FSTS_REG) & VTD_FSTS_IQE)) {
3315         /* Process Invalidation Queue here */
3316         vtd_fetch_inv_desc(s);
3317     }
3318 }
3319 
3320 static void vtd_handle_fsts_write(IntelIOMMUState *s)
3321 {
3322     uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
3323     uint32_t fectl_reg = vtd_get_long_raw(s, DMAR_FECTL_REG);
3324     uint32_t status_fields = VTD_FSTS_PFO | VTD_FSTS_PPF | VTD_FSTS_IQE;
3325 
3326     if ((fectl_reg & VTD_FECTL_IP) && !(fsts_reg & status_fields)) {
3327         vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
3328         trace_vtd_fsts_clear_ip();
3329     }
3330     /* FIXME: when IQE is Clear, should we try to fetch some Invalidation
3331      * Descriptors if there are any when Queued Invalidation is enabled?
3332      */
3333 }
3334 
3335 static void vtd_handle_fectl_write(IntelIOMMUState *s)
3336 {
3337     uint32_t fectl_reg;
3338     /* FIXME: when software clears the IM field, check the IP field. But do we
3339      * need to compare the old value and the new value to conclude that
3340      * software clears the IM field? Or just check if the IM field is zero?
3341      */
3342     fectl_reg = vtd_get_long_raw(s, DMAR_FECTL_REG);
3343 
3344     trace_vtd_reg_write_fectl(fectl_reg);
3345 
3346     if ((fectl_reg & VTD_FECTL_IP) && !(fectl_reg & VTD_FECTL_IM)) {
3347         vtd_generate_interrupt(s, DMAR_FEADDR_REG, DMAR_FEDATA_REG);
3348         vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
3349     }
3350 }
3351 
3352 static void vtd_handle_ics_write(IntelIOMMUState *s)
3353 {
3354     uint32_t ics_reg = vtd_get_long_raw(s, DMAR_ICS_REG);
3355     uint32_t iectl_reg = vtd_get_long_raw(s, DMAR_IECTL_REG);
3356 
3357     if ((iectl_reg & VTD_IECTL_IP) && !(ics_reg & VTD_ICS_IWC)) {
3358         trace_vtd_reg_ics_clear_ip();
3359         vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
3360     }
3361 }
3362 
3363 static void vtd_handle_iectl_write(IntelIOMMUState *s)
3364 {
3365     uint32_t iectl_reg;
3366     /* FIXME: when software clears the IM field, check the IP field. But do we
3367      * need to compare the old value and the new value to conclude that
3368      * software clears the IM field? Or just check if the IM field is zero?
3369      */
3370     iectl_reg = vtd_get_long_raw(s, DMAR_IECTL_REG);
3371 
3372     trace_vtd_reg_write_iectl(iectl_reg);
3373 
3374     if ((iectl_reg & VTD_IECTL_IP) && !(iectl_reg & VTD_IECTL_IM)) {
3375         vtd_generate_interrupt(s, DMAR_IEADDR_REG, DMAR_IEDATA_REG);
3376         vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
3377     }
3378 }
3379 
3380 static uint64_t vtd_mem_read(void *opaque, hwaddr addr, unsigned size)
3381 {
3382     IntelIOMMUState *s = opaque;
3383     uint64_t val;
3384 
3385     trace_vtd_reg_read(addr, size);
3386 
3387     if (addr + size > DMAR_REG_SIZE) {
3388         error_report_once("%s: MMIO over range: addr=0x%" PRIx64
3389                           " size=0x%x", __func__, addr, size);
3390         return (uint64_t)-1;
3391     }
3392 
3393     switch (addr) {
3394     /* Root Table Address Register, 64-bit */
3395     case DMAR_RTADDR_REG:
3396         val = vtd_get_quad_raw(s, DMAR_RTADDR_REG);
3397         if (size == 4) {
3398             val = val & ((1ULL << 32) - 1);
3399         }
3400         break;
3401 
3402     case DMAR_RTADDR_REG_HI:
3403         assert(size == 4);
3404         val = vtd_get_quad_raw(s, DMAR_RTADDR_REG) >> 32;
3405         break;
3406 
3407     /* Invalidation Queue Address Register, 64-bit */
3408     case DMAR_IQA_REG:
3409         val = s->iq |
3410               (vtd_get_quad(s, DMAR_IQA_REG) &
3411               (VTD_IQA_QS | VTD_IQA_DW_MASK));
3412         if (size == 4) {
3413             val = val & ((1ULL << 32) - 1);
3414         }
3415         break;
3416 
3417     case DMAR_IQA_REG_HI:
3418         assert(size == 4);
3419         val = s->iq >> 32;
3420         break;
3421 
3422     default:
3423         if (size == 4) {
3424             val = vtd_get_long(s, addr);
3425         } else {
3426             val = vtd_get_quad(s, addr);
3427         }
3428     }
3429 
3430     return val;
3431 }
3432 
3433 static void vtd_mem_write(void *opaque, hwaddr addr,
3434                           uint64_t val, unsigned size)
3435 {
3436     IntelIOMMUState *s = opaque;
3437 
3438     trace_vtd_reg_write(addr, size, val);
3439 
3440     if (addr + size > DMAR_REG_SIZE) {
3441         error_report_once("%s: MMIO over range: addr=0x%" PRIx64
3442                           " size=0x%x", __func__, addr, size);
3443         return;
3444     }
3445 
3446     switch (addr) {
3447     /* Global Command Register, 32-bit */
3448     case DMAR_GCMD_REG:
3449         vtd_set_long(s, addr, val);
3450         vtd_handle_gcmd_write(s);
3451         break;
3452 
3453     /* Context Command Register, 64-bit */
3454     case DMAR_CCMD_REG:
3455         if (size == 4) {
3456             vtd_set_long(s, addr, val);
3457         } else {
3458             vtd_set_quad(s, addr, val);
3459             vtd_handle_ccmd_write(s);
3460         }
3461         break;
3462 
3463     case DMAR_CCMD_REG_HI:
3464         assert(size == 4);
3465         vtd_set_long(s, addr, val);
3466         vtd_handle_ccmd_write(s);
3467         break;
3468 
3469     /* IOTLB Invalidation Register, 64-bit */
3470     case DMAR_IOTLB_REG:
3471         if (size == 4) {
3472             vtd_set_long(s, addr, val);
3473         } else {
3474             vtd_set_quad(s, addr, val);
3475             vtd_handle_iotlb_write(s);
3476         }
3477         break;
3478 
3479     case DMAR_IOTLB_REG_HI:
3480         assert(size == 4);
3481         vtd_set_long(s, addr, val);
3482         vtd_handle_iotlb_write(s);
3483         break;
3484 
3485     /* Invalidate Address Register, 64-bit */
3486     case DMAR_IVA_REG:
3487         if (size == 4) {
3488             vtd_set_long(s, addr, val);
3489         } else {
3490             vtd_set_quad(s, addr, val);
3491         }
3492         break;
3493 
3494     case DMAR_IVA_REG_HI:
3495         assert(size == 4);
3496         vtd_set_long(s, addr, val);
3497         break;
3498 
3499     /* Fault Status Register, 32-bit */
3500     case DMAR_FSTS_REG:
3501         assert(size == 4);
3502         vtd_set_long(s, addr, val);
3503         vtd_handle_fsts_write(s);
3504         break;
3505 
3506     /* Fault Event Control Register, 32-bit */
3507     case DMAR_FECTL_REG:
3508         assert(size == 4);
3509         vtd_set_long(s, addr, val);
3510         vtd_handle_fectl_write(s);
3511         break;
3512 
3513     /* Fault Event Data Register, 32-bit */
3514     case DMAR_FEDATA_REG:
3515         assert(size == 4);
3516         vtd_set_long(s, addr, val);
3517         break;
3518 
3519     /* Fault Event Address Register, 32-bit */
3520     case DMAR_FEADDR_REG:
3521         if (size == 4) {
3522             vtd_set_long(s, addr, val);
3523         } else {
3524             /*
3525              * While the register is 32-bit only, some guests (Xen...) write to
3526              * it with 64-bit.
3527              */
3528             vtd_set_quad(s, addr, val);
3529         }
3530         break;
3531 
3532     /* Fault Event Upper Address Register, 32-bit */
3533     case DMAR_FEUADDR_REG:
3534         assert(size == 4);
3535         vtd_set_long(s, addr, val);
3536         break;
3537 
3538     /* Protected Memory Enable Register, 32-bit */
3539     case DMAR_PMEN_REG:
3540         assert(size == 4);
3541         vtd_set_long(s, addr, val);
3542         break;
3543 
3544     /* Root Table Address Register, 64-bit */
3545     case DMAR_RTADDR_REG:
3546         if (size == 4) {
3547             vtd_set_long(s, addr, val);
3548         } else {
3549             vtd_set_quad(s, addr, val);
3550         }
3551         break;
3552 
3553     case DMAR_RTADDR_REG_HI:
3554         assert(size == 4);
3555         vtd_set_long(s, addr, val);
3556         break;
3557 
3558     /* Invalidation Queue Tail Register, 64-bit */
3559     case DMAR_IQT_REG:
3560         if (size == 4) {
3561             vtd_set_long(s, addr, val);
3562         } else {
3563             vtd_set_quad(s, addr, val);
3564         }
3565         vtd_handle_iqt_write(s);
3566         break;
3567 
3568     case DMAR_IQT_REG_HI:
3569         assert(size == 4);
3570         vtd_set_long(s, addr, val);
3571         /* 19:63 of IQT_REG is RsvdZ, do nothing here */
3572         break;
3573 
3574     /* Invalidation Queue Address Register, 64-bit */
3575     case DMAR_IQA_REG:
3576         if (size == 4) {
3577             vtd_set_long(s, addr, val);
3578         } else {
3579             vtd_set_quad(s, addr, val);
3580         }
3581         vtd_update_iq_dw(s);
3582         break;
3583 
3584     case DMAR_IQA_REG_HI:
3585         assert(size == 4);
3586         vtd_set_long(s, addr, val);
3587         break;
3588 
3589     /* Invalidation Completion Status Register, 32-bit */
3590     case DMAR_ICS_REG:
3591         assert(size == 4);
3592         vtd_set_long(s, addr, val);
3593         vtd_handle_ics_write(s);
3594         break;
3595 
3596     /* Invalidation Event Control Register, 32-bit */
3597     case DMAR_IECTL_REG:
3598         assert(size == 4);
3599         vtd_set_long(s, addr, val);
3600         vtd_handle_iectl_write(s);
3601         break;
3602 
3603     /* Invalidation Event Data Register, 32-bit */
3604     case DMAR_IEDATA_REG:
3605         assert(size == 4);
3606         vtd_set_long(s, addr, val);
3607         break;
3608 
3609     /* Invalidation Event Address Register, 32-bit */
3610     case DMAR_IEADDR_REG:
3611         assert(size == 4);
3612         vtd_set_long(s, addr, val);
3613         break;
3614 
3615     /* Invalidation Event Upper Address Register, 32-bit */
3616     case DMAR_IEUADDR_REG:
3617         assert(size == 4);
3618         vtd_set_long(s, addr, val);
3619         break;
3620 
3621     /* Fault Recording Registers, 128-bit */
3622     case DMAR_FRCD_REG_0_0:
3623         if (size == 4) {
3624             vtd_set_long(s, addr, val);
3625         } else {
3626             vtd_set_quad(s, addr, val);
3627         }
3628         break;
3629 
3630     case DMAR_FRCD_REG_0_1:
3631         assert(size == 4);
3632         vtd_set_long(s, addr, val);
3633         break;
3634 
3635     case DMAR_FRCD_REG_0_2:
3636         if (size == 4) {
3637             vtd_set_long(s, addr, val);
3638         } else {
3639             vtd_set_quad(s, addr, val);
3640             /* May clear bit 127 (Fault), update PPF */
3641             vtd_update_fsts_ppf(s);
3642         }
3643         break;
3644 
3645     case DMAR_FRCD_REG_0_3:
3646         assert(size == 4);
3647         vtd_set_long(s, addr, val);
3648         /* May clear bit 127 (Fault), update PPF */
3649         vtd_update_fsts_ppf(s);
3650         break;
3651 
3652     case DMAR_IRTA_REG:
3653         if (size == 4) {
3654             vtd_set_long(s, addr, val);
3655         } else {
3656             vtd_set_quad(s, addr, val);
3657         }
3658         break;
3659 
3660     case DMAR_IRTA_REG_HI:
3661         assert(size == 4);
3662         vtd_set_long(s, addr, val);
3663         break;
3664 
3665     default:
3666         if (size == 4) {
3667             vtd_set_long(s, addr, val);
3668         } else {
3669             vtd_set_quad(s, addr, val);
3670         }
3671     }
3672 }
3673 
3674 static IOMMUTLBEntry vtd_iommu_translate(IOMMUMemoryRegion *iommu, hwaddr addr,
3675                                          IOMMUAccessFlags flag, int iommu_idx)
3676 {
3677     VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu);
3678     IntelIOMMUState *s = vtd_as->iommu_state;
3679     IOMMUTLBEntry iotlb = {
3680         /* We'll fill in the rest later. */
3681         .target_as = &address_space_memory,
3682         .pasid = vtd_as->pasid,
3683     };
3684     bool success;
3685 
3686     if (likely(s->dmar_enabled)) {
3687         success = vtd_do_iommu_translate(vtd_as, vtd_as->bus, vtd_as->devfn,
3688                                          addr, flag & IOMMU_WO, &iotlb);
3689     } else {
3690         /* DMAR disabled, passthrough, use 4k-page*/
3691         iotlb.iova = addr & VTD_PAGE_MASK_4K;
3692         iotlb.translated_addr = addr & VTD_PAGE_MASK_4K;
3693         iotlb.addr_mask = ~VTD_PAGE_MASK_4K;
3694         iotlb.perm = IOMMU_RW;
3695         success = true;
3696     }
3697 
3698     if (likely(success)) {
3699         trace_vtd_dmar_translate(pci_bus_num(vtd_as->bus),
3700                                  VTD_PCI_SLOT(vtd_as->devfn),
3701                                  VTD_PCI_FUNC(vtd_as->devfn),
3702                                  iotlb.iova, iotlb.translated_addr,
3703                                  iotlb.addr_mask);
3704     } else {
3705         error_report_once("%s: detected translation failure "
3706                           "(dev=%02x:%02x:%02x, iova=0x%" PRIx64 ")",
3707                           __func__, pci_bus_num(vtd_as->bus),
3708                           VTD_PCI_SLOT(vtd_as->devfn),
3709                           VTD_PCI_FUNC(vtd_as->devfn),
3710                           addr);
3711     }
3712 
3713     return iotlb;
3714 }
3715 
3716 static int vtd_iommu_notify_flag_changed(IOMMUMemoryRegion *iommu,
3717                                          IOMMUNotifierFlag old,
3718                                          IOMMUNotifierFlag new,
3719                                          Error **errp)
3720 {
3721     VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu);
3722     IntelIOMMUState *s = vtd_as->iommu_state;
3723     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
3724 
3725     /* TODO: add support for VFIO and vhost users */
3726     if (s->snoop_control) {
3727         error_setg_errno(errp, ENOTSUP,
3728                          "Snoop Control with vhost or VFIO is not supported");
3729         return -ENOTSUP;
3730     }
3731     if (!s->caching_mode && (new & IOMMU_NOTIFIER_MAP)) {
3732         error_setg_errno(errp, ENOTSUP,
3733                          "device %02x.%02x.%x requires caching mode",
3734                          pci_bus_num(vtd_as->bus), PCI_SLOT(vtd_as->devfn),
3735                          PCI_FUNC(vtd_as->devfn));
3736         return -ENOTSUP;
3737     }
3738     if (!x86_iommu->dt_supported && (new & IOMMU_NOTIFIER_DEVIOTLB_UNMAP)) {
3739         error_setg_errno(errp, ENOTSUP,
3740                          "device %02x.%02x.%x requires device IOTLB mode",
3741                          pci_bus_num(vtd_as->bus), PCI_SLOT(vtd_as->devfn),
3742                          PCI_FUNC(vtd_as->devfn));
3743         return -ENOTSUP;
3744     }
3745 
3746     /* Update per-address-space notifier flags */
3747     vtd_as->notifier_flags = new;
3748 
3749     if (old == IOMMU_NOTIFIER_NONE) {
3750         QLIST_INSERT_HEAD(&s->vtd_as_with_notifiers, vtd_as, next);
3751     } else if (new == IOMMU_NOTIFIER_NONE) {
3752         QLIST_REMOVE(vtd_as, next);
3753     }
3754     return 0;
3755 }
3756 
3757 static int vtd_post_load(void *opaque, int version_id)
3758 {
3759     IntelIOMMUState *iommu = opaque;
3760 
3761     /*
3762      * We don't need to migrate the root_scalable because we can
3763      * simply do the calculation after the loading is complete.  We
3764      * can actually do similar things with root, dmar_enabled, etc.
3765      * however since we've had them already so we'd better keep them
3766      * for compatibility of migration.
3767      */
3768     vtd_update_scalable_state(iommu);
3769 
3770     vtd_update_iq_dw(iommu);
3771 
3772     /*
3773      * Memory regions are dynamically turned on/off depending on
3774      * context entry configurations from the guest. After migration,
3775      * we need to make sure the memory regions are still correct.
3776      */
3777     vtd_switch_address_space_all(iommu);
3778 
3779     return 0;
3780 }
3781 
3782 static const VMStateDescription vtd_vmstate = {
3783     .name = "iommu-intel",
3784     .version_id = 1,
3785     .minimum_version_id = 1,
3786     .priority = MIG_PRI_IOMMU,
3787     .post_load = vtd_post_load,
3788     .fields = (const VMStateField[]) {
3789         VMSTATE_UINT64(root, IntelIOMMUState),
3790         VMSTATE_UINT64(intr_root, IntelIOMMUState),
3791         VMSTATE_UINT64(iq, IntelIOMMUState),
3792         VMSTATE_UINT32(intr_size, IntelIOMMUState),
3793         VMSTATE_UINT16(iq_head, IntelIOMMUState),
3794         VMSTATE_UINT16(iq_tail, IntelIOMMUState),
3795         VMSTATE_UINT16(iq_size, IntelIOMMUState),
3796         VMSTATE_UINT16(next_frcd_reg, IntelIOMMUState),
3797         VMSTATE_UINT8_ARRAY(csr, IntelIOMMUState, DMAR_REG_SIZE),
3798         VMSTATE_UINT8(iq_last_desc_type, IntelIOMMUState),
3799         VMSTATE_UNUSED(1),      /* bool root_extended is obsolete by VT-d */
3800         VMSTATE_BOOL(dmar_enabled, IntelIOMMUState),
3801         VMSTATE_BOOL(qi_enabled, IntelIOMMUState),
3802         VMSTATE_BOOL(intr_enabled, IntelIOMMUState),
3803         VMSTATE_BOOL(intr_eime, IntelIOMMUState),
3804         VMSTATE_END_OF_LIST()
3805     }
3806 };
3807 
3808 static const MemoryRegionOps vtd_mem_ops = {
3809     .read = vtd_mem_read,
3810     .write = vtd_mem_write,
3811     .endianness = DEVICE_LITTLE_ENDIAN,
3812     .impl = {
3813         .min_access_size = 4,
3814         .max_access_size = 8,
3815     },
3816     .valid = {
3817         .min_access_size = 4,
3818         .max_access_size = 8,
3819     },
3820 };
3821 
3822 static const Property vtd_properties[] = {
3823     DEFINE_PROP_UINT32("version", IntelIOMMUState, version, 0),
3824     DEFINE_PROP_ON_OFF_AUTO("eim", IntelIOMMUState, intr_eim,
3825                             ON_OFF_AUTO_AUTO),
3826     DEFINE_PROP_BOOL("x-buggy-eim", IntelIOMMUState, buggy_eim, false),
3827     DEFINE_PROP_UINT8("aw-bits", IntelIOMMUState, aw_bits,
3828                       VTD_HOST_ADDRESS_WIDTH),
3829     DEFINE_PROP_BOOL("caching-mode", IntelIOMMUState, caching_mode, FALSE),
3830     DEFINE_PROP_BOOL("x-scalable-mode", IntelIOMMUState, scalable_mode, FALSE),
3831     DEFINE_PROP_BOOL("x-flts", IntelIOMMUState, flts, FALSE),
3832     DEFINE_PROP_BOOL("snoop-control", IntelIOMMUState, snoop_control, false),
3833     DEFINE_PROP_BOOL("x-pasid-mode", IntelIOMMUState, pasid, false),
3834     DEFINE_PROP_BOOL("dma-drain", IntelIOMMUState, dma_drain, true),
3835     DEFINE_PROP_BOOL("dma-translation", IntelIOMMUState, dma_translation, true),
3836     DEFINE_PROP_BOOL("stale-tm", IntelIOMMUState, stale_tm, false),
3837     DEFINE_PROP_BOOL("fs1gp", IntelIOMMUState, fs1gp, true),
3838 };
3839 
3840 /* Read IRTE entry with specific index */
3841 static bool vtd_irte_get(IntelIOMMUState *iommu, uint16_t index,
3842                          VTD_IR_TableEntry *entry, uint16_t sid,
3843                          bool do_fault)
3844 {
3845     static const uint16_t vtd_svt_mask[VTD_SQ_MAX] = \
3846         {0xffff, 0xfffb, 0xfff9, 0xfff8};
3847     dma_addr_t addr = 0x00;
3848     uint16_t mask, source_id;
3849     uint8_t bus, bus_max, bus_min;
3850 
3851     if (index >= iommu->intr_size) {
3852         error_report_once("%s: index too large: ind=0x%x",
3853                           __func__, index);
3854         if (do_fault) {
3855             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_INDEX_OVER, index);
3856         }
3857         return false;
3858     }
3859 
3860     addr = iommu->intr_root + index * sizeof(*entry);
3861     if (dma_memory_read(&address_space_memory, addr,
3862                         entry, sizeof(*entry), MEMTXATTRS_UNSPECIFIED)) {
3863         error_report_once("%s: read failed: ind=0x%x addr=0x%" PRIx64,
3864                           __func__, index, addr);
3865         if (do_fault) {
3866             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_ROOT_INVAL, index);
3867         }
3868         return false;
3869     }
3870 
3871     entry->data[0] = le64_to_cpu(entry->data[0]);
3872     entry->data[1] = le64_to_cpu(entry->data[1]);
3873 
3874     trace_vtd_ir_irte_get(index, entry->data[1], entry->data[0]);
3875 
3876     /*
3877      * The remaining potential fault conditions are "qualified" by the
3878      * Fault Processing Disable bit in the IRTE. Even "not present".
3879      * So just clear the do_fault flag if PFD is set, which will
3880      * prevent faults being raised.
3881      */
3882     if (entry->irte.fault_disable) {
3883         do_fault = false;
3884     }
3885 
3886     if (!entry->irte.present) {
3887         error_report_once("%s: detected non-present IRTE "
3888                           "(index=%u, high=0x%" PRIx64 ", low=0x%" PRIx64 ")",
3889                           __func__, index, entry->data[1], entry->data[0]);
3890         if (do_fault) {
3891             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_ENTRY_P, index);
3892         }
3893         return false;
3894     }
3895 
3896     if (entry->irte.__reserved_0 || entry->irte.__reserved_1 ||
3897         entry->irte.__reserved_2) {
3898         error_report_once("%s: detected non-zero reserved IRTE "
3899                           "(index=%u, high=0x%" PRIx64 ", low=0x%" PRIx64 ")",
3900                           __func__, index, entry->data[1], entry->data[0]);
3901         if (do_fault) {
3902             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_IRTE_RSVD, index);
3903         }
3904         return false;
3905     }
3906 
3907     if (sid != X86_IOMMU_SID_INVALID) {
3908         /* Validate IRTE SID */
3909         source_id = entry->irte.source_id;
3910         switch (entry->irte.sid_vtype) {
3911         case VTD_SVT_NONE:
3912             break;
3913 
3914         case VTD_SVT_ALL:
3915             mask = vtd_svt_mask[entry->irte.sid_q];
3916             if ((source_id & mask) != (sid & mask)) {
3917                 error_report_once("%s: invalid IRTE SID "
3918                                   "(index=%u, sid=%u, source_id=%u)",
3919                                   __func__, index, sid, source_id);
3920                 if (do_fault) {
3921                     vtd_report_ir_fault(iommu, sid, VTD_FR_IR_SID_ERR, index);
3922                 }
3923                 return false;
3924             }
3925             break;
3926 
3927         case VTD_SVT_BUS:
3928             bus_max = source_id >> 8;
3929             bus_min = source_id & 0xff;
3930             bus = sid >> 8;
3931             if (bus > bus_max || bus < bus_min) {
3932                 error_report_once("%s: invalid SVT_BUS "
3933                                   "(index=%u, bus=%u, min=%u, max=%u)",
3934                                   __func__, index, bus, bus_min, bus_max);
3935                 if (do_fault) {
3936                     vtd_report_ir_fault(iommu, sid, VTD_FR_IR_SID_ERR, index);
3937                 }
3938                 return false;
3939             }
3940             break;
3941 
3942         default:
3943             error_report_once("%s: detected invalid IRTE SVT "
3944                               "(index=%u, type=%d)", __func__,
3945                               index, entry->irte.sid_vtype);
3946             /* Take this as verification failure. */
3947             if (do_fault) {
3948                 vtd_report_ir_fault(iommu, sid, VTD_FR_IR_SID_ERR, index);
3949             }
3950             return false;
3951         }
3952     }
3953 
3954     return true;
3955 }
3956 
3957 /* Fetch IRQ information of specific IR index */
3958 static bool vtd_remap_irq_get(IntelIOMMUState *iommu, uint16_t index,
3959                               X86IOMMUIrq *irq, uint16_t sid, bool do_fault)
3960 {
3961     VTD_IR_TableEntry irte = {};
3962 
3963     if (!vtd_irte_get(iommu, index, &irte, sid, do_fault)) {
3964         return false;
3965     }
3966 
3967     irq->trigger_mode = irte.irte.trigger_mode;
3968     irq->vector = irte.irte.vector;
3969     irq->delivery_mode = irte.irte.delivery_mode;
3970     irq->dest = irte.irte.dest_id;
3971     if (!iommu->intr_eime) {
3972 #define  VTD_IR_APIC_DEST_MASK         (0xff00ULL)
3973 #define  VTD_IR_APIC_DEST_SHIFT        (8)
3974         irq->dest = (irq->dest & VTD_IR_APIC_DEST_MASK) >>
3975             VTD_IR_APIC_DEST_SHIFT;
3976     }
3977     irq->dest_mode = irte.irte.dest_mode;
3978     irq->redir_hint = irte.irte.redir_hint;
3979 
3980     trace_vtd_ir_remap(index, irq->trigger_mode, irq->vector,
3981                        irq->delivery_mode, irq->dest, irq->dest_mode);
3982 
3983     return true;
3984 }
3985 
3986 /* Interrupt remapping for MSI/MSI-X entry */
3987 static int vtd_interrupt_remap_msi(IntelIOMMUState *iommu,
3988                                    MSIMessage *origin,
3989                                    MSIMessage *translated,
3990                                    uint16_t sid, bool do_fault)
3991 {
3992     VTD_IR_MSIAddress addr;
3993     uint16_t index;
3994     X86IOMMUIrq irq = {};
3995 
3996     assert(origin && translated);
3997 
3998     trace_vtd_ir_remap_msi_req(origin->address, origin->data);
3999 
4000     if (!iommu || !iommu->intr_enabled) {
4001         memcpy(translated, origin, sizeof(*origin));
4002         goto out;
4003     }
4004 
4005     if (origin->address & VTD_MSI_ADDR_HI_MASK) {
4006         error_report_once("%s: MSI address high 32 bits non-zero detected: "
4007                           "address=0x%" PRIx64, __func__, origin->address);
4008         if (do_fault) {
4009             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_REQ_RSVD, 0);
4010         }
4011         return -EINVAL;
4012     }
4013 
4014     addr.data = origin->address & VTD_MSI_ADDR_LO_MASK;
4015     if (addr.addr.__head != 0xfee) {
4016         error_report_once("%s: MSI address low 32 bit invalid: 0x%" PRIx32,
4017                           __func__, addr.data);
4018         if (do_fault) {
4019             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_REQ_RSVD, 0);
4020         }
4021         return -EINVAL;
4022     }
4023 
4024     /* This is compatible mode. */
4025     if (addr.addr.int_mode != VTD_IR_INT_FORMAT_REMAP) {
4026         memcpy(translated, origin, sizeof(*origin));
4027         goto out;
4028     }
4029 
4030     index = addr.addr.index_h << 15 | addr.addr.index_l;
4031 
4032 #define  VTD_IR_MSI_DATA_SUBHANDLE       (0x0000ffff)
4033 #define  VTD_IR_MSI_DATA_RESERVED        (0xffff0000)
4034 
4035     if (addr.addr.sub_valid) {
4036         /* See VT-d spec 5.1.2.2 and 5.1.3 on subhandle */
4037         index += origin->data & VTD_IR_MSI_DATA_SUBHANDLE;
4038     }
4039 
4040     if (!vtd_remap_irq_get(iommu, index, &irq, sid, do_fault)) {
4041         return -EINVAL;
4042     }
4043 
4044     if (addr.addr.sub_valid) {
4045         trace_vtd_ir_remap_type("MSI");
4046         if (origin->data & VTD_IR_MSI_DATA_RESERVED) {
4047             error_report_once("%s: invalid IR MSI "
4048                               "(sid=%u, address=0x%" PRIx64
4049                               ", data=0x%" PRIx32 ")",
4050                               __func__, sid, origin->address, origin->data);
4051             if (do_fault) {
4052                 vtd_report_ir_fault(iommu, sid, VTD_FR_IR_REQ_RSVD, 0);
4053             }
4054             return -EINVAL;
4055         }
4056     } else {
4057         uint8_t vector = origin->data & 0xff;
4058         uint8_t trigger_mode = (origin->data >> MSI_DATA_TRIGGER_SHIFT) & 0x1;
4059 
4060         trace_vtd_ir_remap_type("IOAPIC");
4061         /* IOAPIC entry vector should be aligned with IRTE vector
4062          * (see vt-d spec 5.1.5.1). */
4063         if (vector != irq.vector) {
4064             trace_vtd_warn_ir_vector(sid, index, vector, irq.vector);
4065         }
4066 
4067         /* The Trigger Mode field must match the Trigger Mode in the IRTE.
4068          * (see vt-d spec 5.1.5.1). */
4069         if (trigger_mode != irq.trigger_mode) {
4070             trace_vtd_warn_ir_trigger(sid, index, trigger_mode,
4071                                       irq.trigger_mode);
4072         }
4073     }
4074 
4075     /*
4076      * We'd better keep the last two bits, assuming that guest OS
4077      * might modify it. Keep it does not hurt after all.
4078      */
4079     irq.msi_addr_last_bits = addr.addr.__not_care;
4080 
4081     /* Translate X86IOMMUIrq to MSI message */
4082     x86_iommu_irq_to_msi_message(&irq, translated);
4083 
4084 out:
4085     trace_vtd_ir_remap_msi(origin->address, origin->data,
4086                            translated->address, translated->data);
4087     return 0;
4088 }
4089 
4090 static int vtd_int_remap(X86IOMMUState *iommu, MSIMessage *src,
4091                          MSIMessage *dst, uint16_t sid)
4092 {
4093     return vtd_interrupt_remap_msi(INTEL_IOMMU_DEVICE(iommu),
4094                                    src, dst, sid, false);
4095 }
4096 
4097 static MemTxResult vtd_mem_ir_read(void *opaque, hwaddr addr,
4098                                    uint64_t *data, unsigned size,
4099                                    MemTxAttrs attrs)
4100 {
4101     return MEMTX_OK;
4102 }
4103 
4104 static MemTxResult vtd_mem_ir_write(void *opaque, hwaddr addr,
4105                                     uint64_t value, unsigned size,
4106                                     MemTxAttrs attrs)
4107 {
4108     int ret = 0;
4109     MSIMessage from = {}, to = {};
4110     uint16_t sid = X86_IOMMU_SID_INVALID;
4111 
4112     from.address = (uint64_t) addr + VTD_INTERRUPT_ADDR_FIRST;
4113     from.data = (uint32_t) value;
4114 
4115     if (!attrs.unspecified) {
4116         /* We have explicit Source ID */
4117         sid = attrs.requester_id;
4118     }
4119 
4120     ret = vtd_interrupt_remap_msi(opaque, &from, &to, sid, true);
4121     if (ret) {
4122         /* Drop this interrupt */
4123         return MEMTX_ERROR;
4124     }
4125 
4126     apic_get_class(NULL)->send_msi(&to);
4127 
4128     return MEMTX_OK;
4129 }
4130 
4131 static const MemoryRegionOps vtd_mem_ir_ops = {
4132     .read_with_attrs = vtd_mem_ir_read,
4133     .write_with_attrs = vtd_mem_ir_write,
4134     .endianness = DEVICE_LITTLE_ENDIAN,
4135     .impl = {
4136         .min_access_size = 4,
4137         .max_access_size = 4,
4138     },
4139     .valid = {
4140         .min_access_size = 4,
4141         .max_access_size = 4,
4142     },
4143 };
4144 
4145 static void vtd_report_ir_illegal_access(VTDAddressSpace *vtd_as,
4146                                          hwaddr addr, bool is_write)
4147 {
4148     IntelIOMMUState *s = vtd_as->iommu_state;
4149     uint8_t bus_n = pci_bus_num(vtd_as->bus);
4150     uint16_t sid = PCI_BUILD_BDF(bus_n, vtd_as->devfn);
4151     bool is_fpd_set = false;
4152     VTDContextEntry ce;
4153 
4154     assert(vtd_as->pasid != PCI_NO_PASID);
4155 
4156     /* Try out best to fetch FPD, we can't do anything more */
4157     if (vtd_dev_to_context_entry(s, bus_n, vtd_as->devfn, &ce) == 0) {
4158         is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;
4159         if (!is_fpd_set && s->root_scalable) {
4160             vtd_ce_get_pasid_fpd(s, &ce, &is_fpd_set, vtd_as->pasid);
4161         }
4162     }
4163 
4164     vtd_report_fault(s, VTD_FR_SM_INTERRUPT_ADDR,
4165                      is_fpd_set, sid, addr, is_write,
4166                      true, vtd_as->pasid);
4167 }
4168 
4169 static MemTxResult vtd_mem_ir_fault_read(void *opaque, hwaddr addr,
4170                                          uint64_t *data, unsigned size,
4171                                          MemTxAttrs attrs)
4172 {
4173     vtd_report_ir_illegal_access(opaque, addr, false);
4174 
4175     return MEMTX_ERROR;
4176 }
4177 
4178 static MemTxResult vtd_mem_ir_fault_write(void *opaque, hwaddr addr,
4179                                           uint64_t value, unsigned size,
4180                                           MemTxAttrs attrs)
4181 {
4182     vtd_report_ir_illegal_access(opaque, addr, true);
4183 
4184     return MEMTX_ERROR;
4185 }
4186 
4187 static const MemoryRegionOps vtd_mem_ir_fault_ops = {
4188     .read_with_attrs = vtd_mem_ir_fault_read,
4189     .write_with_attrs = vtd_mem_ir_fault_write,
4190     .endianness = DEVICE_LITTLE_ENDIAN,
4191     .impl = {
4192         .min_access_size = 1,
4193         .max_access_size = 8,
4194     },
4195     .valid = {
4196         .min_access_size = 1,
4197         .max_access_size = 8,
4198     },
4199 };
4200 
4201 VTDAddressSpace *vtd_find_add_as(IntelIOMMUState *s, PCIBus *bus,
4202                                  int devfn, unsigned int pasid)
4203 {
4204     /*
4205      * We can't simply use sid here since the bus number might not be
4206      * initialized by the guest.
4207      */
4208     struct vtd_as_key key = {
4209         .bus = bus,
4210         .devfn = devfn,
4211         .pasid = pasid,
4212     };
4213     VTDAddressSpace *vtd_dev_as;
4214     char name[128];
4215 
4216     vtd_iommu_lock(s);
4217     vtd_dev_as = g_hash_table_lookup(s->vtd_address_spaces, &key);
4218     vtd_iommu_unlock(s);
4219 
4220     if (!vtd_dev_as) {
4221         struct vtd_as_key *new_key;
4222         /* Slow path */
4223 
4224         /*
4225          * memory_region_add_subregion_overlap requires the bql,
4226          * make sure we own it.
4227          */
4228         BQL_LOCK_GUARD();
4229         vtd_iommu_lock(s);
4230 
4231         /* Check again as we released the lock for a moment */
4232         vtd_dev_as = g_hash_table_lookup(s->vtd_address_spaces, &key);
4233         if (vtd_dev_as) {
4234             vtd_iommu_unlock(s);
4235             return vtd_dev_as;
4236         }
4237 
4238         /* Still nothing, allocate a new address space */
4239         new_key = g_malloc(sizeof(*new_key));
4240 
4241         new_key->bus = bus;
4242         new_key->devfn = devfn;
4243         new_key->pasid = pasid;
4244 
4245         if (pasid == PCI_NO_PASID) {
4246             snprintf(name, sizeof(name), "vtd-%02x.%x", PCI_SLOT(devfn),
4247                      PCI_FUNC(devfn));
4248         } else {
4249             snprintf(name, sizeof(name), "vtd-%02x.%x-pasid-%x", PCI_SLOT(devfn),
4250                      PCI_FUNC(devfn), pasid);
4251         }
4252 
4253         vtd_dev_as = g_new0(VTDAddressSpace, 1);
4254 
4255         vtd_dev_as->bus = bus;
4256         vtd_dev_as->devfn = (uint8_t)devfn;
4257         vtd_dev_as->pasid = pasid;
4258         vtd_dev_as->iommu_state = s;
4259         vtd_dev_as->context_cache_entry.context_cache_gen = 0;
4260         vtd_dev_as->iova_tree = iova_tree_new();
4261 
4262         memory_region_init(&vtd_dev_as->root, OBJECT(s), name, UINT64_MAX);
4263         address_space_init(&vtd_dev_as->as, &vtd_dev_as->root, "vtd-root");
4264 
4265         /*
4266          * Build the DMAR-disabled container with aliases to the
4267          * shared MRs.  Note that aliasing to a shared memory region
4268          * could help the memory API to detect same FlatViews so we
4269          * can have devices to share the same FlatView when DMAR is
4270          * disabled (either by not providing "intel_iommu=on" or with
4271          * "iommu=pt").  It will greatly reduce the total number of
4272          * FlatViews of the system hence VM runs faster.
4273          */
4274         memory_region_init_alias(&vtd_dev_as->nodmar, OBJECT(s),
4275                                  "vtd-nodmar", &s->mr_nodmar, 0,
4276                                  memory_region_size(&s->mr_nodmar));
4277 
4278         /*
4279          * Build the per-device DMAR-enabled container.
4280          *
4281          * TODO: currently we have per-device IOMMU memory region only
4282          * because we have per-device IOMMU notifiers for devices.  If
4283          * one day we can abstract the IOMMU notifiers out of the
4284          * memory regions then we can also share the same memory
4285          * region here just like what we've done above with the nodmar
4286          * region.
4287          */
4288         strcat(name, "-dmar");
4289         memory_region_init_iommu(&vtd_dev_as->iommu, sizeof(vtd_dev_as->iommu),
4290                                  TYPE_INTEL_IOMMU_MEMORY_REGION, OBJECT(s),
4291                                  name, UINT64_MAX);
4292         memory_region_init_alias(&vtd_dev_as->iommu_ir, OBJECT(s), "vtd-ir",
4293                                  &s->mr_ir, 0, memory_region_size(&s->mr_ir));
4294         memory_region_add_subregion_overlap(MEMORY_REGION(&vtd_dev_as->iommu),
4295                                             VTD_INTERRUPT_ADDR_FIRST,
4296                                             &vtd_dev_as->iommu_ir, 1);
4297 
4298         /*
4299          * This region is used for catching fault to access interrupt
4300          * range via passthrough + PASID. See also
4301          * vtd_switch_address_space(). We can't use alias since we
4302          * need to know the sid which is valid for MSI who uses
4303          * bus_master_as (see msi_send_message()).
4304          */
4305         memory_region_init_io(&vtd_dev_as->iommu_ir_fault, OBJECT(s),
4306                               &vtd_mem_ir_fault_ops, vtd_dev_as, "vtd-no-ir",
4307                               VTD_INTERRUPT_ADDR_SIZE);
4308         /*
4309          * Hook to root since when PT is enabled vtd_dev_as->iommu
4310          * will be disabled.
4311          */
4312         memory_region_add_subregion_overlap(MEMORY_REGION(&vtd_dev_as->root),
4313                                             VTD_INTERRUPT_ADDR_FIRST,
4314                                             &vtd_dev_as->iommu_ir_fault, 2);
4315 
4316         /*
4317          * Hook both the containers under the root container, we
4318          * switch between DMAR & noDMAR by enable/disable
4319          * corresponding sub-containers
4320          */
4321         memory_region_add_subregion_overlap(&vtd_dev_as->root, 0,
4322                                             MEMORY_REGION(&vtd_dev_as->iommu),
4323                                             0);
4324         memory_region_add_subregion_overlap(&vtd_dev_as->root, 0,
4325                                             &vtd_dev_as->nodmar, 0);
4326 
4327         vtd_switch_address_space(vtd_dev_as);
4328 
4329         g_hash_table_insert(s->vtd_address_spaces, new_key, vtd_dev_as);
4330 
4331         vtd_iommu_unlock(s);
4332     }
4333     return vtd_dev_as;
4334 }
4335 
4336 static bool vtd_check_hiod(IntelIOMMUState *s, HostIOMMUDevice *hiod,
4337                            Error **errp)
4338 {
4339     HostIOMMUDeviceClass *hiodc = HOST_IOMMU_DEVICE_GET_CLASS(hiod);
4340     int ret;
4341 
4342     if (!hiodc->get_cap) {
4343         error_setg(errp, ".get_cap() not implemented");
4344         return false;
4345     }
4346 
4347     /* Common checks */
4348     ret = hiodc->get_cap(hiod, HOST_IOMMU_DEVICE_CAP_AW_BITS, errp);
4349     if (ret < 0) {
4350         return false;
4351     }
4352     if (s->aw_bits > ret) {
4353         error_setg(errp, "aw-bits %d > host aw-bits %d", s->aw_bits, ret);
4354         return false;
4355     }
4356 
4357     if (!s->flts) {
4358         /* All checks requested by VTD stage-2 translation pass */
4359         return true;
4360     }
4361 
4362     error_setg(errp, "host device is uncompatible with stage-1 translation");
4363     return false;
4364 }
4365 
4366 static bool vtd_dev_set_iommu_device(PCIBus *bus, void *opaque, int devfn,
4367                                      HostIOMMUDevice *hiod, Error **errp)
4368 {
4369     IntelIOMMUState *s = opaque;
4370     struct vtd_as_key key = {
4371         .bus = bus,
4372         .devfn = devfn,
4373     };
4374     struct vtd_as_key *new_key;
4375 
4376     assert(hiod);
4377 
4378     vtd_iommu_lock(s);
4379 
4380     if (g_hash_table_lookup(s->vtd_host_iommu_dev, &key)) {
4381         error_setg(errp, "Host IOMMU device already exist");
4382         vtd_iommu_unlock(s);
4383         return false;
4384     }
4385 
4386     if (!vtd_check_hiod(s, hiod, errp)) {
4387         vtd_iommu_unlock(s);
4388         return false;
4389     }
4390 
4391     new_key = g_malloc(sizeof(*new_key));
4392     new_key->bus = bus;
4393     new_key->devfn = devfn;
4394 
4395     object_ref(hiod);
4396     g_hash_table_insert(s->vtd_host_iommu_dev, new_key, hiod);
4397 
4398     vtd_iommu_unlock(s);
4399 
4400     return true;
4401 }
4402 
4403 static void vtd_dev_unset_iommu_device(PCIBus *bus, void *opaque, int devfn)
4404 {
4405     IntelIOMMUState *s = opaque;
4406     struct vtd_as_key key = {
4407         .bus = bus,
4408         .devfn = devfn,
4409     };
4410 
4411     vtd_iommu_lock(s);
4412 
4413     if (!g_hash_table_lookup(s->vtd_host_iommu_dev, &key)) {
4414         vtd_iommu_unlock(s);
4415         return;
4416     }
4417 
4418     g_hash_table_remove(s->vtd_host_iommu_dev, &key);
4419 
4420     vtd_iommu_unlock(s);
4421 }
4422 
4423 /* Unmap the whole range in the notifier's scope. */
4424 static void vtd_address_space_unmap(VTDAddressSpace *as, IOMMUNotifier *n)
4425 {
4426     hwaddr total, remain;
4427     hwaddr start = n->start;
4428     hwaddr end = n->end;
4429     IntelIOMMUState *s = as->iommu_state;
4430     DMAMap map;
4431 
4432     /*
4433      * Note: all the codes in this function has a assumption that IOVA
4434      * bits are no more than VTD_MGAW bits (which is restricted by
4435      * VT-d spec), otherwise we need to consider overflow of 64 bits.
4436      */
4437 
4438     if (end > VTD_ADDRESS_SIZE(s->aw_bits) - 1) {
4439         /*
4440          * Don't need to unmap regions that is bigger than the whole
4441          * VT-d supported address space size
4442          */
4443         end = VTD_ADDRESS_SIZE(s->aw_bits) - 1;
4444     }
4445 
4446     assert(start <= end);
4447     total = remain = end - start + 1;
4448 
4449     while (remain >= VTD_PAGE_SIZE) {
4450         IOMMUTLBEvent event;
4451         uint64_t mask = dma_aligned_pow2_mask(start, end, s->aw_bits);
4452         uint64_t size = mask + 1;
4453 
4454         assert(size);
4455 
4456         event.type = IOMMU_NOTIFIER_UNMAP;
4457         event.entry.iova = start;
4458         event.entry.addr_mask = mask;
4459         event.entry.target_as = &address_space_memory;
4460         event.entry.perm = IOMMU_NONE;
4461         /* This field is meaningless for unmap */
4462         event.entry.translated_addr = 0;
4463 
4464         memory_region_notify_iommu_one(n, &event);
4465 
4466         start += size;
4467         remain -= size;
4468     }
4469 
4470     assert(!remain);
4471 
4472     trace_vtd_as_unmap_whole(pci_bus_num(as->bus),
4473                              VTD_PCI_SLOT(as->devfn),
4474                              VTD_PCI_FUNC(as->devfn),
4475                              n->start, total);
4476 
4477     map.iova = n->start;
4478     map.size = total - 1; /* Inclusive */
4479     iova_tree_remove(as->iova_tree, map);
4480 }
4481 
4482 static void vtd_address_space_unmap_all(IntelIOMMUState *s)
4483 {
4484     VTDAddressSpace *vtd_as;
4485     IOMMUNotifier *n;
4486 
4487     QLIST_FOREACH(vtd_as, &s->vtd_as_with_notifiers, next) {
4488         IOMMU_NOTIFIER_FOREACH(n, &vtd_as->iommu) {
4489             vtd_address_space_unmap(vtd_as, n);
4490         }
4491     }
4492 }
4493 
4494 static void vtd_address_space_refresh_all(IntelIOMMUState *s)
4495 {
4496     vtd_address_space_unmap_all(s);
4497     vtd_switch_address_space_all(s);
4498 }
4499 
4500 static int vtd_replay_hook(const IOMMUTLBEvent *event, void *private)
4501 {
4502     memory_region_notify_iommu_one(private, event);
4503     return 0;
4504 }
4505 
4506 static void vtd_iommu_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n)
4507 {
4508     VTDAddressSpace *vtd_as = container_of(iommu_mr, VTDAddressSpace, iommu);
4509     IntelIOMMUState *s = vtd_as->iommu_state;
4510     uint8_t bus_n = pci_bus_num(vtd_as->bus);
4511     VTDContextEntry ce;
4512     DMAMap map = { .iova = 0, .size = HWADDR_MAX };
4513 
4514     /* replay is protected by BQL, page walk will re-setup it safely */
4515     iova_tree_remove(vtd_as->iova_tree, map);
4516 
4517     if (vtd_dev_to_context_entry(s, bus_n, vtd_as->devfn, &ce) == 0) {
4518         trace_vtd_replay_ce_valid(s->root_scalable ? "scalable mode" :
4519                                   "legacy mode",
4520                                   bus_n, PCI_SLOT(vtd_as->devfn),
4521                                   PCI_FUNC(vtd_as->devfn),
4522                                   vtd_get_domain_id(s, &ce, vtd_as->pasid),
4523                                   ce.hi, ce.lo);
4524         if (n->notifier_flags & IOMMU_NOTIFIER_MAP) {
4525             /* This is required only for MAP typed notifiers */
4526             vtd_page_walk_info info = {
4527                 .hook_fn = vtd_replay_hook,
4528                 .private = (void *)n,
4529                 .notify_unmap = false,
4530                 .aw = s->aw_bits,
4531                 .as = vtd_as,
4532                 .domain_id = vtd_get_domain_id(s, &ce, vtd_as->pasid),
4533             };
4534 
4535             vtd_page_walk(s, &ce, 0, ~0ULL, &info, vtd_as->pasid);
4536         }
4537     } else {
4538         trace_vtd_replay_ce_invalid(bus_n, PCI_SLOT(vtd_as->devfn),
4539                                     PCI_FUNC(vtd_as->devfn));
4540     }
4541 }
4542 
4543 static void vtd_cap_init(IntelIOMMUState *s)
4544 {
4545     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
4546 
4547     s->cap = VTD_CAP_FRO | VTD_CAP_NFR | VTD_CAP_ND |
4548              VTD_CAP_MAMV | VTD_CAP_PSI | VTD_CAP_SLLPS |
4549              VTD_CAP_MGAW(s->aw_bits);
4550     if (s->dma_drain) {
4551         s->cap |= VTD_CAP_DRAIN;
4552     }
4553     if (s->dma_translation) {
4554             if (s->aw_bits >= VTD_HOST_AW_39BIT) {
4555                     s->cap |= VTD_CAP_SAGAW_39bit;
4556             }
4557             if (s->aw_bits >= VTD_HOST_AW_48BIT) {
4558                     s->cap |= VTD_CAP_SAGAW_48bit;
4559             }
4560     }
4561     s->ecap = VTD_ECAP_QI | VTD_ECAP_IRO;
4562 
4563     if (x86_iommu_ir_supported(x86_iommu)) {
4564         s->ecap |= VTD_ECAP_IR | VTD_ECAP_MHMV;
4565         if (s->intr_eim == ON_OFF_AUTO_ON) {
4566             s->ecap |= VTD_ECAP_EIM;
4567         }
4568         assert(s->intr_eim != ON_OFF_AUTO_AUTO);
4569     }
4570 
4571     if (x86_iommu->dt_supported) {
4572         s->ecap |= VTD_ECAP_DT;
4573     }
4574 
4575     if (x86_iommu->pt_supported) {
4576         s->ecap |= VTD_ECAP_PT;
4577     }
4578 
4579     if (s->caching_mode) {
4580         s->cap |= VTD_CAP_CM;
4581     }
4582 
4583     /* TODO: read cap/ecap from host to decide which cap to be exposed. */
4584     if (s->flts) {
4585         s->ecap |= VTD_ECAP_SMTS | VTD_ECAP_FLTS;
4586         if (s->fs1gp) {
4587             s->cap |= VTD_CAP_FS1GP;
4588         }
4589     } else if (s->scalable_mode) {
4590         s->ecap |= VTD_ECAP_SMTS | VTD_ECAP_SRS | VTD_ECAP_SLTS;
4591     }
4592 
4593     if (s->snoop_control) {
4594         s->ecap |= VTD_ECAP_SC;
4595     }
4596 
4597     if (s->pasid) {
4598         s->ecap |= VTD_ECAP_PASID | VTD_ECAP_PSS;
4599     }
4600 }
4601 
4602 /*
4603  * Do the initialization. It will also be called when reset, so pay
4604  * attention when adding new initialization stuff.
4605  */
4606 static void vtd_init(IntelIOMMUState *s)
4607 {
4608     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
4609 
4610     memset(s->csr, 0, DMAR_REG_SIZE);
4611     memset(s->wmask, 0, DMAR_REG_SIZE);
4612     memset(s->w1cmask, 0, DMAR_REG_SIZE);
4613     memset(s->womask, 0, DMAR_REG_SIZE);
4614 
4615     s->root = 0;
4616     s->root_scalable = false;
4617     s->dmar_enabled = false;
4618     s->intr_enabled = false;
4619     s->iq_head = 0;
4620     s->iq_tail = 0;
4621     s->iq = 0;
4622     s->iq_size = 0;
4623     s->qi_enabled = false;
4624     s->iq_last_desc_type = VTD_INV_DESC_NONE;
4625     s->iq_dw = false;
4626     s->next_frcd_reg = 0;
4627 
4628     vtd_cap_init(s);
4629 
4630     /*
4631      * Rsvd field masks for spte
4632      */
4633     vtd_spte_rsvd[0] = ~0ULL;
4634     vtd_spte_rsvd[1] = VTD_SPTE_PAGE_L1_RSVD_MASK(s->aw_bits,
4635                                         x86_iommu->dt_supported && s->stale_tm);
4636     vtd_spte_rsvd[2] = VTD_SPTE_PAGE_L2_RSVD_MASK(s->aw_bits);
4637     vtd_spte_rsvd[3] = VTD_SPTE_PAGE_L3_RSVD_MASK(s->aw_bits);
4638     vtd_spte_rsvd[4] = VTD_SPTE_PAGE_L4_RSVD_MASK(s->aw_bits);
4639 
4640     vtd_spte_rsvd_large[2] = VTD_SPTE_LPAGE_L2_RSVD_MASK(s->aw_bits,
4641                                         x86_iommu->dt_supported && s->stale_tm);
4642     vtd_spte_rsvd_large[3] = VTD_SPTE_LPAGE_L3_RSVD_MASK(s->aw_bits,
4643                                         x86_iommu->dt_supported && s->stale_tm);
4644 
4645     /*
4646      * Rsvd field masks for fpte
4647      */
4648     vtd_fpte_rsvd[0] = ~0ULL;
4649     vtd_fpte_rsvd[1] = VTD_FPTE_PAGE_L1_RSVD_MASK(s->aw_bits);
4650     vtd_fpte_rsvd[2] = VTD_FPTE_PAGE_L2_RSVD_MASK(s->aw_bits);
4651     vtd_fpte_rsvd[3] = VTD_FPTE_PAGE_L3_RSVD_MASK(s->aw_bits);
4652     vtd_fpte_rsvd[4] = VTD_FPTE_PAGE_L4_RSVD_MASK(s->aw_bits);
4653 
4654     vtd_fpte_rsvd_large[2] = VTD_FPTE_LPAGE_L2_RSVD_MASK(s->aw_bits);
4655     vtd_fpte_rsvd_large[3] = VTD_FPTE_LPAGE_L3_RSVD_MASK(s->aw_bits);
4656 
4657     if (s->scalable_mode || s->snoop_control) {
4658         vtd_spte_rsvd[1] &= ~VTD_SPTE_SNP;
4659         vtd_spte_rsvd_large[2] &= ~VTD_SPTE_SNP;
4660         vtd_spte_rsvd_large[3] &= ~VTD_SPTE_SNP;
4661     }
4662 
4663     vtd_reset_caches(s);
4664 
4665     /* Define registers with default values and bit semantics */
4666     vtd_define_long(s, DMAR_VER_REG, 0x10UL, 0, 0);
4667     vtd_define_quad(s, DMAR_CAP_REG, s->cap, 0, 0);
4668     vtd_define_quad(s, DMAR_ECAP_REG, s->ecap, 0, 0);
4669     vtd_define_long(s, DMAR_GCMD_REG, 0, 0xff800000UL, 0);
4670     vtd_define_long_wo(s, DMAR_GCMD_REG, 0xff800000UL);
4671     vtd_define_long(s, DMAR_GSTS_REG, 0, 0, 0);
4672     vtd_define_quad(s, DMAR_RTADDR_REG, 0, 0xfffffffffffffc00ULL, 0);
4673     vtd_define_quad(s, DMAR_CCMD_REG, 0, 0xe0000003ffffffffULL, 0);
4674     vtd_define_quad_wo(s, DMAR_CCMD_REG, 0x3ffff0000ULL);
4675 
4676     /* Advanced Fault Logging not supported */
4677     vtd_define_long(s, DMAR_FSTS_REG, 0, 0, 0x11UL);
4678     vtd_define_long(s, DMAR_FECTL_REG, 0x80000000UL, 0x80000000UL, 0);
4679     vtd_define_long(s, DMAR_FEDATA_REG, 0, 0x0000ffffUL, 0);
4680     vtd_define_long(s, DMAR_FEADDR_REG, 0, 0xfffffffcUL, 0);
4681 
4682     /* Treated as RsvdZ when EIM in ECAP_REG is not supported
4683      * vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0xffffffffUL, 0);
4684      */
4685     vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0, 0);
4686 
4687     /* Treated as RO for implementations that PLMR and PHMR fields reported
4688      * as Clear in the CAP_REG.
4689      * vtd_define_long(s, DMAR_PMEN_REG, 0, 0x80000000UL, 0);
4690      */
4691     vtd_define_long(s, DMAR_PMEN_REG, 0, 0, 0);
4692 
4693     vtd_define_quad(s, DMAR_IQH_REG, 0, 0, 0);
4694     vtd_define_quad(s, DMAR_IQT_REG, 0, 0x7fff0ULL, 0);
4695     vtd_define_quad(s, DMAR_IQA_REG, 0, 0xfffffffffffff807ULL, 0);
4696     vtd_define_long(s, DMAR_ICS_REG, 0, 0, 0x1UL);
4697     vtd_define_long(s, DMAR_IECTL_REG, 0x80000000UL, 0x80000000UL, 0);
4698     vtd_define_long(s, DMAR_IEDATA_REG, 0, 0xffffffffUL, 0);
4699     vtd_define_long(s, DMAR_IEADDR_REG, 0, 0xfffffffcUL, 0);
4700     /* Treadted as RsvdZ when EIM in ECAP_REG is not supported */
4701     vtd_define_long(s, DMAR_IEUADDR_REG, 0, 0, 0);
4702 
4703     /* IOTLB registers */
4704     vtd_define_quad(s, DMAR_IOTLB_REG, 0, 0Xb003ffff00000000ULL, 0);
4705     vtd_define_quad(s, DMAR_IVA_REG, 0, 0xfffffffffffff07fULL, 0);
4706     vtd_define_quad_wo(s, DMAR_IVA_REG, 0xfffffffffffff07fULL);
4707 
4708     /* Fault Recording Registers, 128-bit */
4709     vtd_define_quad(s, DMAR_FRCD_REG_0_0, 0, 0, 0);
4710     vtd_define_quad(s, DMAR_FRCD_REG_0_2, 0, 0, 0x8000000000000000ULL);
4711 
4712     /*
4713      * Interrupt remapping registers.
4714      */
4715     vtd_define_quad(s, DMAR_IRTA_REG, 0, 0xfffffffffffff80fULL, 0);
4716 }
4717 
4718 /* Should not reset address_spaces when reset because devices will still use
4719  * the address space they got at first (won't ask the bus again).
4720  */
4721 static void vtd_reset_exit(Object *obj, ResetType type)
4722 {
4723     IntelIOMMUState *s = INTEL_IOMMU_DEVICE(obj);
4724 
4725     trace_vtd_reset_exit();
4726     vtd_init(s);
4727     vtd_address_space_refresh_all(s);
4728 }
4729 
4730 static AddressSpace *vtd_host_dma_iommu(PCIBus *bus, void *opaque, int devfn)
4731 {
4732     IntelIOMMUState *s = opaque;
4733     VTDAddressSpace *vtd_as;
4734 
4735     assert(0 <= devfn && devfn < PCI_DEVFN_MAX);
4736 
4737     vtd_as = vtd_find_add_as(s, bus, devfn, PCI_NO_PASID);
4738     return &vtd_as->as;
4739 }
4740 
4741 static IOMMUTLBEntry vtd_iommu_ats_do_translate(IOMMUMemoryRegion *iommu,
4742                                                 hwaddr addr,
4743                                                 IOMMUAccessFlags flags)
4744 {
4745     IOMMUTLBEntry entry;
4746     VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu);
4747 
4748     if (vtd_is_interrupt_addr(addr)) {
4749         vtd_report_ir_illegal_access(vtd_as, addr, flags & IOMMU_WO);
4750         entry.target_as = &address_space_memory;
4751         entry.iova = 0;
4752         entry.translated_addr = 0;
4753         entry.addr_mask = ~VTD_PAGE_MASK_4K;
4754         entry.perm = IOMMU_NONE;
4755         entry.pasid = PCI_NO_PASID;
4756     } else {
4757         entry = vtd_iommu_translate(iommu, addr, flags, 0);
4758     }
4759 
4760     return entry;
4761 }
4762 
4763 static ssize_t vtd_ats_request_translation(PCIBus *bus, void *opaque,
4764                                            int devfn, uint32_t pasid,
4765                                            bool priv_req, bool exec_req,
4766                                            hwaddr addr, size_t length,
4767                                            bool no_write, IOMMUTLBEntry *result,
4768                                            size_t result_length,
4769                                            uint32_t *err_count)
4770 {
4771     IntelIOMMUState *s = opaque;
4772     VTDAddressSpace *vtd_as;
4773     IOMMUAccessFlags flags = IOMMU_ACCESS_FLAG_FULL(true, !no_write, exec_req,
4774                                                     priv_req, false, false);
4775     ssize_t res_index = 0;
4776     hwaddr target_address = addr + length;
4777     IOMMUTLBEntry entry;
4778 
4779     vtd_as = vtd_find_add_as(s, bus, devfn, pasid);
4780     *err_count = 0;
4781 
4782     while ((addr < target_address) && (res_index < result_length)) {
4783         entry = vtd_iommu_ats_do_translate(&vtd_as->iommu, addr, flags);
4784         entry.perm &= ~IOMMU_GLOBAL; /* Spec 4.1.2: Global Mapping never set */
4785 
4786         if ((entry.perm & flags) != flags) {
4787             *err_count += 1; /* Less than expected */
4788         }
4789 
4790         result[res_index] = entry;
4791         res_index += 1;
4792         addr = (addr & (~entry.addr_mask)) + (entry.addr_mask + 1);
4793     }
4794 
4795     /* Buffer too small */
4796     if (addr < target_address) {
4797         return -ENOMEM;
4798     }
4799 
4800     return res_index;
4801 }
4802 
4803 static void vtd_init_iotlb_notifier(PCIBus *bus, void *opaque, int devfn,
4804                                     IOMMUNotifier *n, IOMMUNotify fn,
4805                                     void *user_opaque)
4806 {
4807     n->opaque = user_opaque;
4808     iommu_notifier_init(n, fn, IOMMU_NOTIFIER_DEVIOTLB_EVENTS, 0,
4809                         HWADDR_MAX, 0);
4810 }
4811 
4812 static void vtd_get_iotlb_info(void *opaque, uint8_t *addr_width,
4813                                uint32_t *min_page_size)
4814 {
4815     IntelIOMMUState *s = opaque;
4816 
4817     *addr_width = s->aw_bits;
4818     *min_page_size = VTD_PAGE_SIZE;
4819 }
4820 
4821 static void vtd_register_iotlb_notifier(PCIBus *bus, void *opaque,
4822                                         int devfn, uint32_t pasid,
4823                                         IOMMUNotifier *n)
4824 {
4825     IntelIOMMUState *s = opaque;
4826     VTDAddressSpace *vtd_as;
4827 
4828     vtd_as = vtd_find_add_as(s, bus, devfn, pasid);
4829     memory_region_register_iommu_notifier(MEMORY_REGION(&vtd_as->iommu), n,
4830                                           &error_fatal);
4831 }
4832 
4833 static void vtd_unregister_iotlb_notifier(PCIBus *bus, void *opaque,
4834                                           int devfn, uint32_t pasid,
4835                                           IOMMUNotifier *n)
4836 {
4837     IntelIOMMUState *s = opaque;
4838     VTDAddressSpace *vtd_as;
4839 
4840     vtd_as = vtd_find_add_as(s, bus, devfn, pasid);
4841     memory_region_unregister_iommu_notifier(MEMORY_REGION(&vtd_as->iommu), n);
4842 }
4843 
4844 static PCIIOMMUOps vtd_iommu_ops = {
4845     .get_address_space = vtd_host_dma_iommu,
4846     .set_iommu_device = vtd_dev_set_iommu_device,
4847     .unset_iommu_device = vtd_dev_unset_iommu_device,
4848     .get_iotlb_info = vtd_get_iotlb_info,
4849     .init_iotlb_notifier = vtd_init_iotlb_notifier,
4850     .register_iotlb_notifier = vtd_register_iotlb_notifier,
4851     .unregister_iotlb_notifier = vtd_unregister_iotlb_notifier,
4852     .ats_request_translation = vtd_ats_request_translation,
4853 };
4854 
4855 static bool vtd_decide_config(IntelIOMMUState *s, Error **errp)
4856 {
4857     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
4858 
4859     if (s->intr_eim == ON_OFF_AUTO_ON && !x86_iommu_ir_supported(x86_iommu)) {
4860         error_setg(errp, "eim=on cannot be selected without intremap=on");
4861         return false;
4862     }
4863 
4864     if (s->intr_eim == ON_OFF_AUTO_AUTO) {
4865         s->intr_eim = (kvm_irqchip_in_kernel() || s->buggy_eim)
4866                       && x86_iommu_ir_supported(x86_iommu) ?
4867                                               ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
4868     }
4869     if (s->intr_eim == ON_OFF_AUTO_ON && !s->buggy_eim) {
4870         if (kvm_irqchip_is_split() && !kvm_enable_x2apic()) {
4871             error_setg(errp, "eim=on requires support on the KVM side"
4872                              "(X2APIC_API, first shipped in v4.7)");
4873             return false;
4874         }
4875     }
4876 
4877     if (!s->scalable_mode && s->flts) {
4878         error_setg(errp, "x-flts is only available in scalable mode");
4879         return false;
4880     }
4881 
4882     if (!s->flts && s->aw_bits != VTD_HOST_AW_39BIT &&
4883         s->aw_bits != VTD_HOST_AW_48BIT) {
4884         error_setg(errp, "%s: supported values for aw-bits are: %d, %d",
4885                    s->scalable_mode ? "Scalable mode(flts=off)" : "Legacy mode",
4886                    VTD_HOST_AW_39BIT, VTD_HOST_AW_48BIT);
4887         return false;
4888     }
4889 
4890     if (s->flts && s->aw_bits != VTD_HOST_AW_48BIT) {
4891         error_setg(errp,
4892                    "Scalable mode(flts=on): supported value for aw-bits is: %d",
4893                    VTD_HOST_AW_48BIT);
4894         return false;
4895     }
4896 
4897     if (s->scalable_mode && !s->dma_drain) {
4898         error_setg(errp, "Need to set dma_drain for scalable mode");
4899         return false;
4900     }
4901 
4902     if (s->pasid && !s->scalable_mode) {
4903         error_setg(errp, "Need to set scalable mode for PASID");
4904         return false;
4905     }
4906 
4907     return true;
4908 }
4909 
4910 static int vtd_machine_done_notify_one(Object *child, void *unused)
4911 {
4912     IntelIOMMUState *iommu = INTEL_IOMMU_DEVICE(x86_iommu_get_default());
4913 
4914     /*
4915      * We hard-coded here because vfio-pci is the only special case
4916      * here.  Let's be more elegant in the future when we can, but so
4917      * far there seems to be no better way.
4918      */
4919     if (object_dynamic_cast(child, "vfio-pci") && !iommu->caching_mode) {
4920         vtd_panic_require_caching_mode();
4921     }
4922 
4923     return 0;
4924 }
4925 
4926 static void vtd_machine_done_hook(Notifier *notifier, void *unused)
4927 {
4928     object_child_foreach_recursive(object_get_root(),
4929                                    vtd_machine_done_notify_one, NULL);
4930 }
4931 
4932 static Notifier vtd_machine_done_notify = {
4933     .notify = vtd_machine_done_hook,
4934 };
4935 
4936 static void vtd_realize(DeviceState *dev, Error **errp)
4937 {
4938     MachineState *ms = MACHINE(qdev_get_machine());
4939     PCMachineState *pcms = PC_MACHINE(ms);
4940     X86MachineState *x86ms = X86_MACHINE(ms);
4941     PCIBus *bus = pcms->pcibus;
4942     IntelIOMMUState *s = INTEL_IOMMU_DEVICE(dev);
4943     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
4944 
4945     if (s->pasid && x86_iommu->dt_supported) {
4946         /*
4947          * PASID-based-Device-TLB Invalidate Descriptor is not
4948          * implemented and it requires support from vhost layer which
4949          * needs to be implemented in the future.
4950          */
4951         error_setg(errp, "PASID based device IOTLB is not supported");
4952         return;
4953     }
4954 
4955     if (!vtd_decide_config(s, errp)) {
4956         return;
4957     }
4958 
4959     QLIST_INIT(&s->vtd_as_with_notifiers);
4960     qemu_mutex_init(&s->iommu_lock);
4961     memory_region_init_io(&s->csrmem, OBJECT(s), &vtd_mem_ops, s,
4962                           "intel_iommu", DMAR_REG_SIZE);
4963     memory_region_add_subregion(get_system_memory(),
4964                                 Q35_HOST_BRIDGE_IOMMU_ADDR, &s->csrmem);
4965 
4966     /* Create the shared memory regions by all devices */
4967     memory_region_init(&s->mr_nodmar, OBJECT(s), "vtd-nodmar",
4968                        UINT64_MAX);
4969     memory_region_init_io(&s->mr_ir, OBJECT(s), &vtd_mem_ir_ops,
4970                           s, "vtd-ir", VTD_INTERRUPT_ADDR_SIZE);
4971     memory_region_init_alias(&s->mr_sys_alias, OBJECT(s),
4972                              "vtd-sys-alias", get_system_memory(), 0,
4973                              memory_region_size(get_system_memory()));
4974     memory_region_add_subregion_overlap(&s->mr_nodmar, 0,
4975                                         &s->mr_sys_alias, 0);
4976     memory_region_add_subregion_overlap(&s->mr_nodmar,
4977                                         VTD_INTERRUPT_ADDR_FIRST,
4978                                         &s->mr_ir, 1);
4979     /* No corresponding destroy */
4980     s->iotlb = g_hash_table_new_full(vtd_iotlb_hash, vtd_iotlb_equal,
4981                                      g_free, g_free);
4982     s->vtd_address_spaces = g_hash_table_new_full(vtd_as_hash, vtd_as_equal,
4983                                       g_free, g_free);
4984     s->vtd_host_iommu_dev = g_hash_table_new_full(vtd_hiod_hash, vtd_hiod_equal,
4985                                                   g_free, vtd_hiod_destroy);
4986     vtd_init(s);
4987     pci_setup_iommu(bus, &vtd_iommu_ops, dev);
4988     /* Pseudo address space under root PCI bus. */
4989     x86ms->ioapic_as = vtd_host_dma_iommu(bus, s, Q35_PSEUDO_DEVFN_IOAPIC);
4990     qemu_add_machine_init_done_notifier(&vtd_machine_done_notify);
4991 }
4992 
4993 static void vtd_class_init(ObjectClass *klass, const void *data)
4994 {
4995     DeviceClass *dc = DEVICE_CLASS(klass);
4996     X86IOMMUClass *x86_class = X86_IOMMU_DEVICE_CLASS(klass);
4997     ResettableClass *rc = RESETTABLE_CLASS(klass);
4998 
4999     /*
5000      * Use 'exit' reset phase to make sure all DMA requests
5001      * have been quiesced during 'enter' or 'hold' phase
5002      */
5003     rc->phases.exit = vtd_reset_exit;
5004     dc->vmsd = &vtd_vmstate;
5005     device_class_set_props(dc, vtd_properties);
5006     dc->hotpluggable = false;
5007     x86_class->realize = vtd_realize;
5008     x86_class->int_remap = vtd_int_remap;
5009     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
5010     dc->desc = "Intel IOMMU (VT-d) DMA Remapping device";
5011 }
5012 
5013 static const TypeInfo vtd_info = {
5014     .name          = TYPE_INTEL_IOMMU_DEVICE,
5015     .parent        = TYPE_X86_IOMMU_DEVICE,
5016     .instance_size = sizeof(IntelIOMMUState),
5017     .class_init    = vtd_class_init,
5018 };
5019 
5020 static void vtd_iommu_memory_region_class_init(ObjectClass *klass,
5021                                                const void *data)
5022 {
5023     IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_CLASS(klass);
5024 
5025     imrc->translate = vtd_iommu_translate;
5026     imrc->notify_flag_changed = vtd_iommu_notify_flag_changed;
5027     imrc->replay = vtd_iommu_replay;
5028 }
5029 
5030 static const TypeInfo vtd_iommu_memory_region_info = {
5031     .parent = TYPE_IOMMU_MEMORY_REGION,
5032     .name = TYPE_INTEL_IOMMU_MEMORY_REGION,
5033     .class_init = vtd_iommu_memory_region_class_init,
5034 };
5035 
5036 static void vtd_register_types(void)
5037 {
5038     type_register_static(&vtd_info);
5039     type_register_static(&vtd_iommu_memory_region_info);
5040 }
5041 
5042 type_init(vtd_register_types)
5043