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