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