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