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