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