xref: /openbmc/qemu/hw/i386/intel_iommu.c (revision e3d9c92507df61608896a579b5b0d7c218d5353e)
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 "hw/sysbus.h"
24 #include "exec/address-spaces.h"
25 #include "intel_iommu_internal.h"
26 #include "hw/pci/pci.h"
27 #include "hw/pci/pci_bus.h"
28 #include "hw/i386/pc.h"
29 #include "hw/boards.h"
30 #include "hw/i386/x86-iommu.h"
31 #include "hw/pci-host/q35.h"
32 
33 /*#define DEBUG_INTEL_IOMMU*/
34 #ifdef DEBUG_INTEL_IOMMU
35 enum {
36     DEBUG_GENERAL, DEBUG_CSR, DEBUG_INV, DEBUG_MMU, DEBUG_FLOG,
37     DEBUG_CACHE, DEBUG_IR,
38 };
39 #define VTD_DBGBIT(x)   (1 << DEBUG_##x)
40 static int vtd_dbgflags = VTD_DBGBIT(GENERAL) | VTD_DBGBIT(CSR);
41 
42 #define VTD_DPRINTF(what, fmt, ...) do { \
43     if (vtd_dbgflags & VTD_DBGBIT(what)) { \
44         fprintf(stderr, "(vtd)%s: " fmt "\n", __func__, \
45                 ## __VA_ARGS__); } \
46     } while (0)
47 #else
48 #define VTD_DPRINTF(what, fmt, ...) do {} while (0)
49 #endif
50 
51 static void vtd_define_quad(IntelIOMMUState *s, hwaddr addr, uint64_t val,
52                             uint64_t wmask, uint64_t w1cmask)
53 {
54     stq_le_p(&s->csr[addr], val);
55     stq_le_p(&s->wmask[addr], wmask);
56     stq_le_p(&s->w1cmask[addr], w1cmask);
57 }
58 
59 static void vtd_define_quad_wo(IntelIOMMUState *s, hwaddr addr, uint64_t mask)
60 {
61     stq_le_p(&s->womask[addr], mask);
62 }
63 
64 static void vtd_define_long(IntelIOMMUState *s, hwaddr addr, uint32_t val,
65                             uint32_t wmask, uint32_t w1cmask)
66 {
67     stl_le_p(&s->csr[addr], val);
68     stl_le_p(&s->wmask[addr], wmask);
69     stl_le_p(&s->w1cmask[addr], w1cmask);
70 }
71 
72 static void vtd_define_long_wo(IntelIOMMUState *s, hwaddr addr, uint32_t mask)
73 {
74     stl_le_p(&s->womask[addr], mask);
75 }
76 
77 /* "External" get/set operations */
78 static void vtd_set_quad(IntelIOMMUState *s, hwaddr addr, uint64_t val)
79 {
80     uint64_t oldval = ldq_le_p(&s->csr[addr]);
81     uint64_t wmask = ldq_le_p(&s->wmask[addr]);
82     uint64_t w1cmask = ldq_le_p(&s->w1cmask[addr]);
83     stq_le_p(&s->csr[addr],
84              ((oldval & ~wmask) | (val & wmask)) & ~(w1cmask & val));
85 }
86 
87 static void vtd_set_long(IntelIOMMUState *s, hwaddr addr, uint32_t val)
88 {
89     uint32_t oldval = ldl_le_p(&s->csr[addr]);
90     uint32_t wmask = ldl_le_p(&s->wmask[addr]);
91     uint32_t w1cmask = ldl_le_p(&s->w1cmask[addr]);
92     stl_le_p(&s->csr[addr],
93              ((oldval & ~wmask) | (val & wmask)) & ~(w1cmask & val));
94 }
95 
96 static uint64_t vtd_get_quad(IntelIOMMUState *s, hwaddr addr)
97 {
98     uint64_t val = ldq_le_p(&s->csr[addr]);
99     uint64_t womask = ldq_le_p(&s->womask[addr]);
100     return val & ~womask;
101 }
102 
103 static uint32_t vtd_get_long(IntelIOMMUState *s, hwaddr addr)
104 {
105     uint32_t val = ldl_le_p(&s->csr[addr]);
106     uint32_t womask = ldl_le_p(&s->womask[addr]);
107     return val & ~womask;
108 }
109 
110 /* "Internal" get/set operations */
111 static uint64_t vtd_get_quad_raw(IntelIOMMUState *s, hwaddr addr)
112 {
113     return ldq_le_p(&s->csr[addr]);
114 }
115 
116 static uint32_t vtd_get_long_raw(IntelIOMMUState *s, hwaddr addr)
117 {
118     return ldl_le_p(&s->csr[addr]);
119 }
120 
121 static void vtd_set_quad_raw(IntelIOMMUState *s, hwaddr addr, uint64_t val)
122 {
123     stq_le_p(&s->csr[addr], val);
124 }
125 
126 static uint32_t vtd_set_clear_mask_long(IntelIOMMUState *s, hwaddr addr,
127                                         uint32_t clear, uint32_t mask)
128 {
129     uint32_t new_val = (ldl_le_p(&s->csr[addr]) & ~clear) | mask;
130     stl_le_p(&s->csr[addr], new_val);
131     return new_val;
132 }
133 
134 static uint64_t vtd_set_clear_mask_quad(IntelIOMMUState *s, hwaddr addr,
135                                         uint64_t clear, uint64_t mask)
136 {
137     uint64_t new_val = (ldq_le_p(&s->csr[addr]) & ~clear) | mask;
138     stq_le_p(&s->csr[addr], new_val);
139     return new_val;
140 }
141 
142 /* GHashTable functions */
143 static gboolean vtd_uint64_equal(gconstpointer v1, gconstpointer v2)
144 {
145     return *((const uint64_t *)v1) == *((const uint64_t *)v2);
146 }
147 
148 static guint vtd_uint64_hash(gconstpointer v)
149 {
150     return (guint)*(const uint64_t *)v;
151 }
152 
153 static gboolean vtd_hash_remove_by_domain(gpointer key, gpointer value,
154                                           gpointer user_data)
155 {
156     VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value;
157     uint16_t domain_id = *(uint16_t *)user_data;
158     return entry->domain_id == domain_id;
159 }
160 
161 /* The shift of an addr for a certain level of paging structure */
162 static inline uint32_t vtd_slpt_level_shift(uint32_t level)
163 {
164     return VTD_PAGE_SHIFT_4K + (level - 1) * VTD_SL_LEVEL_BITS;
165 }
166 
167 static inline uint64_t vtd_slpt_level_page_mask(uint32_t level)
168 {
169     return ~((1ULL << vtd_slpt_level_shift(level)) - 1);
170 }
171 
172 static gboolean vtd_hash_remove_by_page(gpointer key, gpointer value,
173                                         gpointer user_data)
174 {
175     VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value;
176     VTDIOTLBPageInvInfo *info = (VTDIOTLBPageInvInfo *)user_data;
177     uint64_t gfn = (info->addr >> VTD_PAGE_SHIFT_4K) & info->mask;
178     uint64_t gfn_tlb = (info->addr & entry->mask) >> VTD_PAGE_SHIFT_4K;
179     return (entry->domain_id == info->domain_id) &&
180             (((entry->gfn & info->mask) == gfn) ||
181              (entry->gfn == gfn_tlb));
182 }
183 
184 /* Reset all the gen of VTDAddressSpace to zero and set the gen of
185  * IntelIOMMUState to 1.
186  */
187 static void vtd_reset_context_cache(IntelIOMMUState *s)
188 {
189     VTDAddressSpace *vtd_as;
190     VTDBus *vtd_bus;
191     GHashTableIter bus_it;
192     uint32_t devfn_it;
193 
194     g_hash_table_iter_init(&bus_it, s->vtd_as_by_busptr);
195 
196     VTD_DPRINTF(CACHE, "global context_cache_gen=1");
197     while (g_hash_table_iter_next (&bus_it, NULL, (void**)&vtd_bus)) {
198         for (devfn_it = 0; devfn_it < X86_IOMMU_PCI_DEVFN_MAX; ++devfn_it) {
199             vtd_as = vtd_bus->dev_as[devfn_it];
200             if (!vtd_as) {
201                 continue;
202             }
203             vtd_as->context_cache_entry.context_cache_gen = 0;
204         }
205     }
206     s->context_cache_gen = 1;
207 }
208 
209 static void vtd_reset_iotlb(IntelIOMMUState *s)
210 {
211     assert(s->iotlb);
212     g_hash_table_remove_all(s->iotlb);
213 }
214 
215 static uint64_t vtd_get_iotlb_key(uint64_t gfn, uint8_t source_id,
216                                   uint32_t level)
217 {
218     return gfn | ((uint64_t)(source_id) << VTD_IOTLB_SID_SHIFT) |
219            ((uint64_t)(level) << VTD_IOTLB_LVL_SHIFT);
220 }
221 
222 static uint64_t vtd_get_iotlb_gfn(hwaddr addr, uint32_t level)
223 {
224     return (addr & vtd_slpt_level_page_mask(level)) >> VTD_PAGE_SHIFT_4K;
225 }
226 
227 static VTDIOTLBEntry *vtd_lookup_iotlb(IntelIOMMUState *s, uint16_t source_id,
228                                        hwaddr addr)
229 {
230     VTDIOTLBEntry *entry;
231     uint64_t key;
232     int level;
233 
234     for (level = VTD_SL_PT_LEVEL; level < VTD_SL_PML4_LEVEL; level++) {
235         key = vtd_get_iotlb_key(vtd_get_iotlb_gfn(addr, level),
236                                 source_id, level);
237         entry = g_hash_table_lookup(s->iotlb, &key);
238         if (entry) {
239             goto out;
240         }
241     }
242 
243 out:
244     return entry;
245 }
246 
247 static void vtd_update_iotlb(IntelIOMMUState *s, uint16_t source_id,
248                              uint16_t domain_id, hwaddr addr, uint64_t slpte,
249                              bool read_flags, bool write_flags,
250                              uint32_t level)
251 {
252     VTDIOTLBEntry *entry = g_malloc(sizeof(*entry));
253     uint64_t *key = g_malloc(sizeof(*key));
254     uint64_t gfn = vtd_get_iotlb_gfn(addr, level);
255 
256     VTD_DPRINTF(CACHE, "update iotlb sid 0x%"PRIx16 " gpa 0x%"PRIx64
257                 " slpte 0x%"PRIx64 " did 0x%"PRIx16, source_id, addr, slpte,
258                 domain_id);
259     if (g_hash_table_size(s->iotlb) >= VTD_IOTLB_MAX_SIZE) {
260         VTD_DPRINTF(CACHE, "iotlb exceeds size limit, forced to reset");
261         vtd_reset_iotlb(s);
262     }
263 
264     entry->gfn = gfn;
265     entry->domain_id = domain_id;
266     entry->slpte = slpte;
267     entry->read_flags = read_flags;
268     entry->write_flags = write_flags;
269     entry->mask = vtd_slpt_level_page_mask(level);
270     *key = vtd_get_iotlb_key(gfn, source_id, level);
271     g_hash_table_replace(s->iotlb, key, entry);
272 }
273 
274 /* Given the reg addr of both the message data and address, generate an
275  * interrupt via MSI.
276  */
277 static void vtd_generate_interrupt(IntelIOMMUState *s, hwaddr mesg_addr_reg,
278                                    hwaddr mesg_data_reg)
279 {
280     hwaddr addr;
281     uint32_t data;
282 
283     assert(mesg_data_reg < DMAR_REG_SIZE);
284     assert(mesg_addr_reg < DMAR_REG_SIZE);
285 
286     addr = vtd_get_long_raw(s, mesg_addr_reg);
287     data = vtd_get_long_raw(s, mesg_data_reg);
288 
289     VTD_DPRINTF(FLOG, "msi: addr 0x%"PRIx64 " data 0x%"PRIx32, addr, data);
290     address_space_stl_le(&address_space_memory, addr, data,
291                          MEMTXATTRS_UNSPECIFIED, NULL);
292 }
293 
294 /* Generate a fault event to software via MSI if conditions are met.
295  * Notice that the value of FSTS_REG being passed to it should be the one
296  * before any update.
297  */
298 static void vtd_generate_fault_event(IntelIOMMUState *s, uint32_t pre_fsts)
299 {
300     if (pre_fsts & VTD_FSTS_PPF || pre_fsts & VTD_FSTS_PFO ||
301         pre_fsts & VTD_FSTS_IQE) {
302         VTD_DPRINTF(FLOG, "there are previous interrupt conditions "
303                     "to be serviced by software, fault event is not generated "
304                     "(FSTS_REG 0x%"PRIx32 ")", pre_fsts);
305         return;
306     }
307     vtd_set_clear_mask_long(s, DMAR_FECTL_REG, 0, VTD_FECTL_IP);
308     if (vtd_get_long_raw(s, DMAR_FECTL_REG) & VTD_FECTL_IM) {
309         VTD_DPRINTF(FLOG, "Interrupt Mask set, fault event is not generated");
310     } else {
311         vtd_generate_interrupt(s, DMAR_FEADDR_REG, DMAR_FEDATA_REG);
312         vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
313     }
314 }
315 
316 /* Check if the Fault (F) field of the Fault Recording Register referenced by
317  * @index is Set.
318  */
319 static bool vtd_is_frcd_set(IntelIOMMUState *s, uint16_t index)
320 {
321     /* Each reg is 128-bit */
322     hwaddr addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
323     addr += 8; /* Access the high 64-bit half */
324 
325     assert(index < DMAR_FRCD_REG_NR);
326 
327     return vtd_get_quad_raw(s, addr) & VTD_FRCD_F;
328 }
329 
330 /* Update the PPF field of Fault Status Register.
331  * Should be called whenever change the F field of any fault recording
332  * registers.
333  */
334 static void vtd_update_fsts_ppf(IntelIOMMUState *s)
335 {
336     uint32_t i;
337     uint32_t ppf_mask = 0;
338 
339     for (i = 0; i < DMAR_FRCD_REG_NR; i++) {
340         if (vtd_is_frcd_set(s, i)) {
341             ppf_mask = VTD_FSTS_PPF;
342             break;
343         }
344     }
345     vtd_set_clear_mask_long(s, DMAR_FSTS_REG, VTD_FSTS_PPF, ppf_mask);
346     VTD_DPRINTF(FLOG, "set PPF of FSTS_REG to %d", ppf_mask ? 1 : 0);
347 }
348 
349 static void vtd_set_frcd_and_update_ppf(IntelIOMMUState *s, uint16_t index)
350 {
351     /* Each reg is 128-bit */
352     hwaddr addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
353     addr += 8; /* Access the high 64-bit half */
354 
355     assert(index < DMAR_FRCD_REG_NR);
356 
357     vtd_set_clear_mask_quad(s, addr, 0, VTD_FRCD_F);
358     vtd_update_fsts_ppf(s);
359 }
360 
361 /* Must not update F field now, should be done later */
362 static void vtd_record_frcd(IntelIOMMUState *s, uint16_t index,
363                             uint16_t source_id, hwaddr addr,
364                             VTDFaultReason fault, bool is_write)
365 {
366     uint64_t hi = 0, lo;
367     hwaddr frcd_reg_addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
368 
369     assert(index < DMAR_FRCD_REG_NR);
370 
371     lo = VTD_FRCD_FI(addr);
372     hi = VTD_FRCD_SID(source_id) | VTD_FRCD_FR(fault);
373     if (!is_write) {
374         hi |= VTD_FRCD_T;
375     }
376     vtd_set_quad_raw(s, frcd_reg_addr, lo);
377     vtd_set_quad_raw(s, frcd_reg_addr + 8, hi);
378     VTD_DPRINTF(FLOG, "record to FRCD_REG #%"PRIu16 ": hi 0x%"PRIx64
379                 ", lo 0x%"PRIx64, index, hi, lo);
380 }
381 
382 /* Try to collapse multiple pending faults from the same requester */
383 static bool vtd_try_collapse_fault(IntelIOMMUState *s, uint16_t source_id)
384 {
385     uint32_t i;
386     uint64_t frcd_reg;
387     hwaddr addr = DMAR_FRCD_REG_OFFSET + 8; /* The high 64-bit half */
388 
389     for (i = 0; i < DMAR_FRCD_REG_NR; i++) {
390         frcd_reg = vtd_get_quad_raw(s, addr);
391         VTD_DPRINTF(FLOG, "frcd_reg #%d 0x%"PRIx64, i, frcd_reg);
392         if ((frcd_reg & VTD_FRCD_F) &&
393             ((frcd_reg & VTD_FRCD_SID_MASK) == source_id)) {
394             return true;
395         }
396         addr += 16; /* 128-bit for each */
397     }
398     return false;
399 }
400 
401 /* Log and report an DMAR (address translation) fault to software */
402 static void vtd_report_dmar_fault(IntelIOMMUState *s, uint16_t source_id,
403                                   hwaddr addr, VTDFaultReason fault,
404                                   bool is_write)
405 {
406     uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
407 
408     assert(fault < VTD_FR_MAX);
409 
410     if (fault == VTD_FR_RESERVED_ERR) {
411         /* This is not a normal fault reason case. Drop it. */
412         return;
413     }
414     VTD_DPRINTF(FLOG, "sid 0x%"PRIx16 ", fault %d, addr 0x%"PRIx64
415                 ", is_write %d", source_id, fault, addr, is_write);
416     if (fsts_reg & VTD_FSTS_PFO) {
417         VTD_DPRINTF(FLOG, "new fault is not recorded due to "
418                     "Primary Fault Overflow");
419         return;
420     }
421     if (vtd_try_collapse_fault(s, source_id)) {
422         VTD_DPRINTF(FLOG, "new fault is not recorded due to "
423                     "compression of faults");
424         return;
425     }
426     if (vtd_is_frcd_set(s, s->next_frcd_reg)) {
427         VTD_DPRINTF(FLOG, "Primary Fault Overflow and "
428                     "new fault is not recorded, set PFO field");
429         vtd_set_clear_mask_long(s, DMAR_FSTS_REG, 0, VTD_FSTS_PFO);
430         return;
431     }
432 
433     vtd_record_frcd(s, s->next_frcd_reg, source_id, addr, fault, is_write);
434 
435     if (fsts_reg & VTD_FSTS_PPF) {
436         VTD_DPRINTF(FLOG, "there are pending faults already, "
437                     "fault event is not generated");
438         vtd_set_frcd_and_update_ppf(s, s->next_frcd_reg);
439         s->next_frcd_reg++;
440         if (s->next_frcd_reg == DMAR_FRCD_REG_NR) {
441             s->next_frcd_reg = 0;
442         }
443     } else {
444         vtd_set_clear_mask_long(s, DMAR_FSTS_REG, VTD_FSTS_FRI_MASK,
445                                 VTD_FSTS_FRI(s->next_frcd_reg));
446         vtd_set_frcd_and_update_ppf(s, s->next_frcd_reg); /* Will set PPF */
447         s->next_frcd_reg++;
448         if (s->next_frcd_reg == DMAR_FRCD_REG_NR) {
449             s->next_frcd_reg = 0;
450         }
451         /* This case actually cause the PPF to be Set.
452          * So generate fault event (interrupt).
453          */
454          vtd_generate_fault_event(s, fsts_reg);
455     }
456 }
457 
458 /* Handle Invalidation Queue Errors of queued invalidation interface error
459  * conditions.
460  */
461 static void vtd_handle_inv_queue_error(IntelIOMMUState *s)
462 {
463     uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
464 
465     vtd_set_clear_mask_long(s, DMAR_FSTS_REG, 0, VTD_FSTS_IQE);
466     vtd_generate_fault_event(s, fsts_reg);
467 }
468 
469 /* Set the IWC field and try to generate an invalidation completion interrupt */
470 static void vtd_generate_completion_event(IntelIOMMUState *s)
471 {
472     VTD_DPRINTF(INV, "completes an invalidation wait command with "
473                 "Interrupt Flag");
474     if (vtd_get_long_raw(s, DMAR_ICS_REG) & VTD_ICS_IWC) {
475         VTD_DPRINTF(INV, "there is a previous interrupt condition to be "
476                     "serviced by software, "
477                     "new invalidation event is not generated");
478         return;
479     }
480     vtd_set_clear_mask_long(s, DMAR_ICS_REG, 0, VTD_ICS_IWC);
481     vtd_set_clear_mask_long(s, DMAR_IECTL_REG, 0, VTD_IECTL_IP);
482     if (vtd_get_long_raw(s, DMAR_IECTL_REG) & VTD_IECTL_IM) {
483         VTD_DPRINTF(INV, "IM filed in IECTL_REG is set, new invalidation "
484                     "event is not generated");
485         return;
486     } else {
487         /* Generate the interrupt event */
488         vtd_generate_interrupt(s, DMAR_IEADDR_REG, DMAR_IEDATA_REG);
489         vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
490     }
491 }
492 
493 static inline bool vtd_root_entry_present(VTDRootEntry *root)
494 {
495     return root->val & VTD_ROOT_ENTRY_P;
496 }
497 
498 static int vtd_get_root_entry(IntelIOMMUState *s, uint8_t index,
499                               VTDRootEntry *re)
500 {
501     dma_addr_t addr;
502 
503     addr = s->root + index * sizeof(*re);
504     if (dma_memory_read(&address_space_memory, addr, re, sizeof(*re))) {
505         VTD_DPRINTF(GENERAL, "error: fail to access root-entry at 0x%"PRIx64
506                     " + %"PRIu8, s->root, index);
507         re->val = 0;
508         return -VTD_FR_ROOT_TABLE_INV;
509     }
510     re->val = le64_to_cpu(re->val);
511     return 0;
512 }
513 
514 static inline bool vtd_context_entry_present(VTDContextEntry *context)
515 {
516     return context->lo & VTD_CONTEXT_ENTRY_P;
517 }
518 
519 static int vtd_get_context_entry_from_root(VTDRootEntry *root, uint8_t index,
520                                            VTDContextEntry *ce)
521 {
522     dma_addr_t addr;
523 
524     if (!vtd_root_entry_present(root)) {
525         VTD_DPRINTF(GENERAL, "error: root-entry is not present");
526         return -VTD_FR_ROOT_ENTRY_P;
527     }
528     addr = (root->val & VTD_ROOT_ENTRY_CTP) + index * sizeof(*ce);
529     if (dma_memory_read(&address_space_memory, addr, ce, sizeof(*ce))) {
530         VTD_DPRINTF(GENERAL, "error: fail to access context-entry at 0x%"PRIx64
531                     " + %"PRIu8,
532                     (uint64_t)(root->val & VTD_ROOT_ENTRY_CTP), index);
533         return -VTD_FR_CONTEXT_TABLE_INV;
534     }
535     ce->lo = le64_to_cpu(ce->lo);
536     ce->hi = le64_to_cpu(ce->hi);
537     return 0;
538 }
539 
540 static inline dma_addr_t vtd_get_slpt_base_from_context(VTDContextEntry *ce)
541 {
542     return ce->lo & VTD_CONTEXT_ENTRY_SLPTPTR;
543 }
544 
545 static inline uint64_t vtd_get_slpte_addr(uint64_t slpte)
546 {
547     return slpte & VTD_SL_PT_BASE_ADDR_MASK;
548 }
549 
550 /* Whether the pte indicates the address of the page frame */
551 static inline bool vtd_is_last_slpte(uint64_t slpte, uint32_t level)
552 {
553     return level == VTD_SL_PT_LEVEL || (slpte & VTD_SL_PT_PAGE_SIZE_MASK);
554 }
555 
556 /* Get the content of a spte located in @base_addr[@index] */
557 static uint64_t vtd_get_slpte(dma_addr_t base_addr, uint32_t index)
558 {
559     uint64_t slpte;
560 
561     assert(index < VTD_SL_PT_ENTRY_NR);
562 
563     if (dma_memory_read(&address_space_memory,
564                         base_addr + index * sizeof(slpte), &slpte,
565                         sizeof(slpte))) {
566         slpte = (uint64_t)-1;
567         return slpte;
568     }
569     slpte = le64_to_cpu(slpte);
570     return slpte;
571 }
572 
573 /* Given a gpa and the level of paging structure, return the offset of current
574  * level.
575  */
576 static inline uint32_t vtd_gpa_level_offset(uint64_t gpa, uint32_t level)
577 {
578     return (gpa >> vtd_slpt_level_shift(level)) &
579             ((1ULL << VTD_SL_LEVEL_BITS) - 1);
580 }
581 
582 /* Check Capability Register to see if the @level of page-table is supported */
583 static inline bool vtd_is_level_supported(IntelIOMMUState *s, uint32_t level)
584 {
585     return VTD_CAP_SAGAW_MASK & s->cap &
586            (1ULL << (level - 2 + VTD_CAP_SAGAW_SHIFT));
587 }
588 
589 /* Get the page-table level that hardware should use for the second-level
590  * page-table walk from the Address Width field of context-entry.
591  */
592 static inline uint32_t vtd_get_level_from_context_entry(VTDContextEntry *ce)
593 {
594     return 2 + (ce->hi & VTD_CONTEXT_ENTRY_AW);
595 }
596 
597 static inline uint32_t vtd_get_agaw_from_context_entry(VTDContextEntry *ce)
598 {
599     return 30 + (ce->hi & VTD_CONTEXT_ENTRY_AW) * 9;
600 }
601 
602 static const uint64_t vtd_paging_entry_rsvd_field[] = {
603     [0] = ~0ULL,
604     /* For not large page */
605     [1] = 0x800ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM),
606     [2] = 0x800ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM),
607     [3] = 0x800ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM),
608     [4] = 0x880ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM),
609     /* For large page */
610     [5] = 0x800ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM),
611     [6] = 0x1ff800ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM),
612     [7] = 0x3ffff800ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM),
613     [8] = 0x880ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM),
614 };
615 
616 static bool vtd_slpte_nonzero_rsvd(uint64_t slpte, uint32_t level)
617 {
618     if (slpte & VTD_SL_PT_PAGE_SIZE_MASK) {
619         /* Maybe large page */
620         return slpte & vtd_paging_entry_rsvd_field[level + 4];
621     } else {
622         return slpte & vtd_paging_entry_rsvd_field[level];
623     }
624 }
625 
626 /* Given the @gpa, get relevant @slptep. @slpte_level will be the last level
627  * of the translation, can be used for deciding the size of large page.
628  */
629 static int vtd_gpa_to_slpte(VTDContextEntry *ce, uint64_t gpa, bool is_write,
630                             uint64_t *slptep, uint32_t *slpte_level,
631                             bool *reads, bool *writes)
632 {
633     dma_addr_t addr = vtd_get_slpt_base_from_context(ce);
634     uint32_t level = vtd_get_level_from_context_entry(ce);
635     uint32_t offset;
636     uint64_t slpte;
637     uint32_t ce_agaw = vtd_get_agaw_from_context_entry(ce);
638     uint64_t access_right_check;
639 
640     /* Check if @gpa is above 2^X-1, where X is the minimum of MGAW in CAP_REG
641      * and AW in context-entry.
642      */
643     if (gpa & ~((1ULL << MIN(ce_agaw, VTD_MGAW)) - 1)) {
644         VTD_DPRINTF(GENERAL, "error: gpa 0x%"PRIx64 " exceeds limits", gpa);
645         return -VTD_FR_ADDR_BEYOND_MGAW;
646     }
647 
648     /* FIXME: what is the Atomics request here? */
649     access_right_check = is_write ? VTD_SL_W : VTD_SL_R;
650 
651     while (true) {
652         offset = vtd_gpa_level_offset(gpa, level);
653         slpte = vtd_get_slpte(addr, offset);
654 
655         if (slpte == (uint64_t)-1) {
656             VTD_DPRINTF(GENERAL, "error: fail to access second-level paging "
657                         "entry at level %"PRIu32 " for gpa 0x%"PRIx64,
658                         level, gpa);
659             if (level == vtd_get_level_from_context_entry(ce)) {
660                 /* Invalid programming of context-entry */
661                 return -VTD_FR_CONTEXT_ENTRY_INV;
662             } else {
663                 return -VTD_FR_PAGING_ENTRY_INV;
664             }
665         }
666         *reads = (*reads) && (slpte & VTD_SL_R);
667         *writes = (*writes) && (slpte & VTD_SL_W);
668         if (!(slpte & access_right_check)) {
669             VTD_DPRINTF(GENERAL, "error: lack of %s permission for "
670                         "gpa 0x%"PRIx64 " slpte 0x%"PRIx64,
671                         (is_write ? "write" : "read"), gpa, slpte);
672             return is_write ? -VTD_FR_WRITE : -VTD_FR_READ;
673         }
674         if (vtd_slpte_nonzero_rsvd(slpte, level)) {
675             VTD_DPRINTF(GENERAL, "error: non-zero reserved field in second "
676                         "level paging entry level %"PRIu32 " slpte 0x%"PRIx64,
677                         level, slpte);
678             return -VTD_FR_PAGING_ENTRY_RSVD;
679         }
680 
681         if (vtd_is_last_slpte(slpte, level)) {
682             *slptep = slpte;
683             *slpte_level = level;
684             return 0;
685         }
686         addr = vtd_get_slpte_addr(slpte);
687         level--;
688     }
689 }
690 
691 /* Map a device to its corresponding domain (context-entry) */
692 static int vtd_dev_to_context_entry(IntelIOMMUState *s, uint8_t bus_num,
693                                     uint8_t devfn, VTDContextEntry *ce)
694 {
695     VTDRootEntry re;
696     int ret_fr;
697 
698     ret_fr = vtd_get_root_entry(s, bus_num, &re);
699     if (ret_fr) {
700         return ret_fr;
701     }
702 
703     if (!vtd_root_entry_present(&re)) {
704         VTD_DPRINTF(GENERAL, "error: root-entry #%"PRIu8 " is not present",
705                     bus_num);
706         return -VTD_FR_ROOT_ENTRY_P;
707     } else if (re.rsvd || (re.val & VTD_ROOT_ENTRY_RSVD)) {
708         VTD_DPRINTF(GENERAL, "error: non-zero reserved field in root-entry "
709                     "hi 0x%"PRIx64 " lo 0x%"PRIx64, re.rsvd, re.val);
710         return -VTD_FR_ROOT_ENTRY_RSVD;
711     }
712 
713     ret_fr = vtd_get_context_entry_from_root(&re, devfn, ce);
714     if (ret_fr) {
715         return ret_fr;
716     }
717 
718     if (!vtd_context_entry_present(ce)) {
719         VTD_DPRINTF(GENERAL,
720                     "error: context-entry #%"PRIu8 "(bus #%"PRIu8 ") "
721                     "is not present", devfn, bus_num);
722         return -VTD_FR_CONTEXT_ENTRY_P;
723     } else if ((ce->hi & VTD_CONTEXT_ENTRY_RSVD_HI) ||
724                (ce->lo & VTD_CONTEXT_ENTRY_RSVD_LO)) {
725         VTD_DPRINTF(GENERAL,
726                     "error: non-zero reserved field in context-entry "
727                     "hi 0x%"PRIx64 " lo 0x%"PRIx64, ce->hi, ce->lo);
728         return -VTD_FR_CONTEXT_ENTRY_RSVD;
729     }
730     /* Check if the programming of context-entry is valid */
731     if (!vtd_is_level_supported(s, vtd_get_level_from_context_entry(ce))) {
732         VTD_DPRINTF(GENERAL, "error: unsupported Address Width value in "
733                     "context-entry hi 0x%"PRIx64 " lo 0x%"PRIx64,
734                     ce->hi, ce->lo);
735         return -VTD_FR_CONTEXT_ENTRY_INV;
736     } else if (ce->lo & VTD_CONTEXT_ENTRY_TT) {
737         VTD_DPRINTF(GENERAL, "error: unsupported Translation Type in "
738                     "context-entry hi 0x%"PRIx64 " lo 0x%"PRIx64,
739                     ce->hi, ce->lo);
740         return -VTD_FR_CONTEXT_ENTRY_INV;
741     }
742     return 0;
743 }
744 
745 static inline uint16_t vtd_make_source_id(uint8_t bus_num, uint8_t devfn)
746 {
747     return ((bus_num & 0xffUL) << 8) | (devfn & 0xffUL);
748 }
749 
750 static const bool vtd_qualified_faults[] = {
751     [VTD_FR_RESERVED] = false,
752     [VTD_FR_ROOT_ENTRY_P] = false,
753     [VTD_FR_CONTEXT_ENTRY_P] = true,
754     [VTD_FR_CONTEXT_ENTRY_INV] = true,
755     [VTD_FR_ADDR_BEYOND_MGAW] = true,
756     [VTD_FR_WRITE] = true,
757     [VTD_FR_READ] = true,
758     [VTD_FR_PAGING_ENTRY_INV] = true,
759     [VTD_FR_ROOT_TABLE_INV] = false,
760     [VTD_FR_CONTEXT_TABLE_INV] = false,
761     [VTD_FR_ROOT_ENTRY_RSVD] = false,
762     [VTD_FR_PAGING_ENTRY_RSVD] = true,
763     [VTD_FR_CONTEXT_ENTRY_TT] = true,
764     [VTD_FR_RESERVED_ERR] = false,
765     [VTD_FR_MAX] = false,
766 };
767 
768 /* To see if a fault condition is "qualified", which is reported to software
769  * only if the FPD field in the context-entry used to process the faulting
770  * request is 0.
771  */
772 static inline bool vtd_is_qualified_fault(VTDFaultReason fault)
773 {
774     return vtd_qualified_faults[fault];
775 }
776 
777 static inline bool vtd_is_interrupt_addr(hwaddr addr)
778 {
779     return VTD_INTERRUPT_ADDR_FIRST <= addr && addr <= VTD_INTERRUPT_ADDR_LAST;
780 }
781 
782 /* Map dev to context-entry then do a paging-structures walk to do a iommu
783  * translation.
784  *
785  * Called from RCU critical section.
786  *
787  * @bus_num: The bus number
788  * @devfn: The devfn, which is the  combined of device and function number
789  * @is_write: The access is a write operation
790  * @entry: IOMMUTLBEntry that contain the addr to be translated and result
791  */
792 static void vtd_do_iommu_translate(VTDAddressSpace *vtd_as, PCIBus *bus,
793                                    uint8_t devfn, hwaddr addr, bool is_write,
794                                    IOMMUTLBEntry *entry)
795 {
796     IntelIOMMUState *s = vtd_as->iommu_state;
797     VTDContextEntry ce;
798     uint8_t bus_num = pci_bus_num(bus);
799     VTDContextCacheEntry *cc_entry = &vtd_as->context_cache_entry;
800     uint64_t slpte, page_mask;
801     uint32_t level;
802     uint16_t source_id = vtd_make_source_id(bus_num, devfn);
803     int ret_fr;
804     bool is_fpd_set = false;
805     bool reads = true;
806     bool writes = true;
807     VTDIOTLBEntry *iotlb_entry;
808 
809     /* Check if the request is in interrupt address range */
810     if (vtd_is_interrupt_addr(addr)) {
811         if (is_write) {
812             /* FIXME: since we don't know the length of the access here, we
813              * treat Non-DWORD length write requests without PASID as
814              * interrupt requests, too. Withoud interrupt remapping support,
815              * we just use 1:1 mapping.
816              */
817             VTD_DPRINTF(MMU, "write request to interrupt address "
818                         "gpa 0x%"PRIx64, addr);
819             entry->iova = addr & VTD_PAGE_MASK_4K;
820             entry->translated_addr = addr & VTD_PAGE_MASK_4K;
821             entry->addr_mask = ~VTD_PAGE_MASK_4K;
822             entry->perm = IOMMU_WO;
823             return;
824         } else {
825             VTD_DPRINTF(GENERAL, "error: read request from interrupt address "
826                         "gpa 0x%"PRIx64, addr);
827             vtd_report_dmar_fault(s, source_id, addr, VTD_FR_READ, is_write);
828             return;
829         }
830     }
831     /* Try to fetch slpte form IOTLB */
832     iotlb_entry = vtd_lookup_iotlb(s, source_id, addr);
833     if (iotlb_entry) {
834         VTD_DPRINTF(CACHE, "hit iotlb sid 0x%"PRIx16 " gpa 0x%"PRIx64
835                     " slpte 0x%"PRIx64 " did 0x%"PRIx16, source_id, addr,
836                     iotlb_entry->slpte, iotlb_entry->domain_id);
837         slpte = iotlb_entry->slpte;
838         reads = iotlb_entry->read_flags;
839         writes = iotlb_entry->write_flags;
840         page_mask = iotlb_entry->mask;
841         goto out;
842     }
843     /* Try to fetch context-entry from cache first */
844     if (cc_entry->context_cache_gen == s->context_cache_gen) {
845         VTD_DPRINTF(CACHE, "hit context-cache bus %d devfn %d "
846                     "(hi %"PRIx64 " lo %"PRIx64 " gen %"PRIu32 ")",
847                     bus_num, devfn, cc_entry->context_entry.hi,
848                     cc_entry->context_entry.lo, cc_entry->context_cache_gen);
849         ce = cc_entry->context_entry;
850         is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;
851     } else {
852         ret_fr = vtd_dev_to_context_entry(s, bus_num, devfn, &ce);
853         is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;
854         if (ret_fr) {
855             ret_fr = -ret_fr;
856             if (is_fpd_set && vtd_is_qualified_fault(ret_fr)) {
857                 VTD_DPRINTF(FLOG, "fault processing is disabled for DMA "
858                             "requests through this context-entry "
859                             "(with FPD Set)");
860             } else {
861                 vtd_report_dmar_fault(s, source_id, addr, ret_fr, is_write);
862             }
863             return;
864         }
865         /* Update context-cache */
866         VTD_DPRINTF(CACHE, "update context-cache bus %d devfn %d "
867                     "(hi %"PRIx64 " lo %"PRIx64 " gen %"PRIu32 "->%"PRIu32 ")",
868                     bus_num, devfn, ce.hi, ce.lo,
869                     cc_entry->context_cache_gen, s->context_cache_gen);
870         cc_entry->context_entry = ce;
871         cc_entry->context_cache_gen = s->context_cache_gen;
872     }
873 
874     ret_fr = vtd_gpa_to_slpte(&ce, addr, is_write, &slpte, &level,
875                               &reads, &writes);
876     if (ret_fr) {
877         ret_fr = -ret_fr;
878         if (is_fpd_set && vtd_is_qualified_fault(ret_fr)) {
879             VTD_DPRINTF(FLOG, "fault processing is disabled for DMA requests "
880                         "through this context-entry (with FPD Set)");
881         } else {
882             vtd_report_dmar_fault(s, source_id, addr, ret_fr, is_write);
883         }
884         return;
885     }
886 
887     page_mask = vtd_slpt_level_page_mask(level);
888     vtd_update_iotlb(s, source_id, VTD_CONTEXT_ENTRY_DID(ce.hi), addr, slpte,
889                      reads, writes, level);
890 out:
891     entry->iova = addr & page_mask;
892     entry->translated_addr = vtd_get_slpte_addr(slpte) & page_mask;
893     entry->addr_mask = ~page_mask;
894     entry->perm = (writes ? 2 : 0) + (reads ? 1 : 0);
895 }
896 
897 static void vtd_root_table_setup(IntelIOMMUState *s)
898 {
899     s->root = vtd_get_quad_raw(s, DMAR_RTADDR_REG);
900     s->root_extended = s->root & VTD_RTADDR_RTT;
901     s->root &= VTD_RTADDR_ADDR_MASK;
902 
903     VTD_DPRINTF(CSR, "root_table addr 0x%"PRIx64 " %s", s->root,
904                 (s->root_extended ? "(extended)" : ""));
905 }
906 
907 static void vtd_iec_notify_all(IntelIOMMUState *s, bool global,
908                                uint32_t index, uint32_t mask)
909 {
910     x86_iommu_iec_notify_all(X86_IOMMU_DEVICE(s), global, index, mask);
911 }
912 
913 static void vtd_interrupt_remap_table_setup(IntelIOMMUState *s)
914 {
915     uint64_t value = 0;
916     value = vtd_get_quad_raw(s, DMAR_IRTA_REG);
917     s->intr_size = 1UL << ((value & VTD_IRTA_SIZE_MASK) + 1);
918     s->intr_root = value & VTD_IRTA_ADDR_MASK;
919 
920     /* Notify global invalidation */
921     vtd_iec_notify_all(s, true, 0, 0);
922 
923     VTD_DPRINTF(CSR, "int remap table addr 0x%"PRIx64 " size %"PRIu32,
924                 s->intr_root, s->intr_size);
925 }
926 
927 static void vtd_context_global_invalidate(IntelIOMMUState *s)
928 {
929     s->context_cache_gen++;
930     if (s->context_cache_gen == VTD_CONTEXT_CACHE_GEN_MAX) {
931         vtd_reset_context_cache(s);
932     }
933 }
934 
935 
936 /* Find the VTD address space currently associated with a given bus number,
937  */
938 static VTDBus *vtd_find_as_from_bus_num(IntelIOMMUState *s, uint8_t bus_num)
939 {
940     VTDBus *vtd_bus = s->vtd_as_by_bus_num[bus_num];
941     if (!vtd_bus) {
942         /* Iterate over the registered buses to find the one
943          * which currently hold this bus number, and update the bus_num lookup table:
944          */
945         GHashTableIter iter;
946 
947         g_hash_table_iter_init(&iter, s->vtd_as_by_busptr);
948         while (g_hash_table_iter_next (&iter, NULL, (void**)&vtd_bus)) {
949             if (pci_bus_num(vtd_bus->bus) == bus_num) {
950                 s->vtd_as_by_bus_num[bus_num] = vtd_bus;
951                 return vtd_bus;
952             }
953         }
954     }
955     return vtd_bus;
956 }
957 
958 /* Do a context-cache device-selective invalidation.
959  * @func_mask: FM field after shifting
960  */
961 static void vtd_context_device_invalidate(IntelIOMMUState *s,
962                                           uint16_t source_id,
963                                           uint16_t func_mask)
964 {
965     uint16_t mask;
966     VTDBus *vtd_bus;
967     VTDAddressSpace *vtd_as;
968     uint16_t devfn;
969     uint16_t devfn_it;
970 
971     switch (func_mask & 3) {
972     case 0:
973         mask = 0;   /* No bits in the SID field masked */
974         break;
975     case 1:
976         mask = 4;   /* Mask bit 2 in the SID field */
977         break;
978     case 2:
979         mask = 6;   /* Mask bit 2:1 in the SID field */
980         break;
981     case 3:
982         mask = 7;   /* Mask bit 2:0 in the SID field */
983         break;
984     }
985     VTD_DPRINTF(INV, "device-selective invalidation source 0x%"PRIx16
986                     " mask %"PRIu16, source_id, mask);
987     vtd_bus = vtd_find_as_from_bus_num(s, VTD_SID_TO_BUS(source_id));
988     if (vtd_bus) {
989         devfn = VTD_SID_TO_DEVFN(source_id);
990         for (devfn_it = 0; devfn_it < X86_IOMMU_PCI_DEVFN_MAX; ++devfn_it) {
991             vtd_as = vtd_bus->dev_as[devfn_it];
992             if (vtd_as && ((devfn_it & mask) == (devfn & mask))) {
993                 VTD_DPRINTF(INV, "invalidate context-cahce of devfn 0x%"PRIx16,
994                             devfn_it);
995                 vtd_as->context_cache_entry.context_cache_gen = 0;
996             }
997         }
998     }
999 }
1000 
1001 /* Context-cache invalidation
1002  * Returns the Context Actual Invalidation Granularity.
1003  * @val: the content of the CCMD_REG
1004  */
1005 static uint64_t vtd_context_cache_invalidate(IntelIOMMUState *s, uint64_t val)
1006 {
1007     uint64_t caig;
1008     uint64_t type = val & VTD_CCMD_CIRG_MASK;
1009 
1010     switch (type) {
1011     case VTD_CCMD_DOMAIN_INVL:
1012         VTD_DPRINTF(INV, "domain-selective invalidation domain 0x%"PRIx16,
1013                     (uint16_t)VTD_CCMD_DID(val));
1014         /* Fall through */
1015     case VTD_CCMD_GLOBAL_INVL:
1016         VTD_DPRINTF(INV, "global invalidation");
1017         caig = VTD_CCMD_GLOBAL_INVL_A;
1018         vtd_context_global_invalidate(s);
1019         break;
1020 
1021     case VTD_CCMD_DEVICE_INVL:
1022         caig = VTD_CCMD_DEVICE_INVL_A;
1023         vtd_context_device_invalidate(s, VTD_CCMD_SID(val), VTD_CCMD_FM(val));
1024         break;
1025 
1026     default:
1027         VTD_DPRINTF(GENERAL, "error: invalid granularity");
1028         caig = 0;
1029     }
1030     return caig;
1031 }
1032 
1033 static void vtd_iotlb_global_invalidate(IntelIOMMUState *s)
1034 {
1035     vtd_reset_iotlb(s);
1036 }
1037 
1038 static void vtd_iotlb_domain_invalidate(IntelIOMMUState *s, uint16_t domain_id)
1039 {
1040     g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_domain,
1041                                 &domain_id);
1042 }
1043 
1044 static void vtd_iotlb_page_invalidate(IntelIOMMUState *s, uint16_t domain_id,
1045                                       hwaddr addr, uint8_t am)
1046 {
1047     VTDIOTLBPageInvInfo info;
1048 
1049     assert(am <= VTD_MAMV);
1050     info.domain_id = domain_id;
1051     info.addr = addr;
1052     info.mask = ~((1 << am) - 1);
1053     g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_page, &info);
1054 }
1055 
1056 /* Flush IOTLB
1057  * Returns the IOTLB Actual Invalidation Granularity.
1058  * @val: the content of the IOTLB_REG
1059  */
1060 static uint64_t vtd_iotlb_flush(IntelIOMMUState *s, uint64_t val)
1061 {
1062     uint64_t iaig;
1063     uint64_t type = val & VTD_TLB_FLUSH_GRANU_MASK;
1064     uint16_t domain_id;
1065     hwaddr addr;
1066     uint8_t am;
1067 
1068     switch (type) {
1069     case VTD_TLB_GLOBAL_FLUSH:
1070         VTD_DPRINTF(INV, "global invalidation");
1071         iaig = VTD_TLB_GLOBAL_FLUSH_A;
1072         vtd_iotlb_global_invalidate(s);
1073         break;
1074 
1075     case VTD_TLB_DSI_FLUSH:
1076         domain_id = VTD_TLB_DID(val);
1077         VTD_DPRINTF(INV, "domain-selective invalidation domain 0x%"PRIx16,
1078                     domain_id);
1079         iaig = VTD_TLB_DSI_FLUSH_A;
1080         vtd_iotlb_domain_invalidate(s, domain_id);
1081         break;
1082 
1083     case VTD_TLB_PSI_FLUSH:
1084         domain_id = VTD_TLB_DID(val);
1085         addr = vtd_get_quad_raw(s, DMAR_IVA_REG);
1086         am = VTD_IVA_AM(addr);
1087         addr = VTD_IVA_ADDR(addr);
1088         VTD_DPRINTF(INV, "page-selective invalidation domain 0x%"PRIx16
1089                     " addr 0x%"PRIx64 " mask %"PRIu8, domain_id, addr, am);
1090         if (am > VTD_MAMV) {
1091             VTD_DPRINTF(GENERAL, "error: supported max address mask value is "
1092                         "%"PRIu8, (uint8_t)VTD_MAMV);
1093             iaig = 0;
1094             break;
1095         }
1096         iaig = VTD_TLB_PSI_FLUSH_A;
1097         vtd_iotlb_page_invalidate(s, domain_id, addr, am);
1098         break;
1099 
1100     default:
1101         VTD_DPRINTF(GENERAL, "error: invalid granularity");
1102         iaig = 0;
1103     }
1104     return iaig;
1105 }
1106 
1107 static inline bool vtd_queued_inv_enable_check(IntelIOMMUState *s)
1108 {
1109     return s->iq_tail == 0;
1110 }
1111 
1112 static inline bool vtd_queued_inv_disable_check(IntelIOMMUState *s)
1113 {
1114     return s->qi_enabled && (s->iq_tail == s->iq_head) &&
1115            (s->iq_last_desc_type == VTD_INV_DESC_WAIT);
1116 }
1117 
1118 static void vtd_handle_gcmd_qie(IntelIOMMUState *s, bool en)
1119 {
1120     uint64_t iqa_val = vtd_get_quad_raw(s, DMAR_IQA_REG);
1121 
1122     VTD_DPRINTF(INV, "Queued Invalidation Enable %s", (en ? "on" : "off"));
1123     if (en) {
1124         if (vtd_queued_inv_enable_check(s)) {
1125             s->iq = iqa_val & VTD_IQA_IQA_MASK;
1126             /* 2^(x+8) entries */
1127             s->iq_size = 1UL << ((iqa_val & VTD_IQA_QS) + 8);
1128             s->qi_enabled = true;
1129             VTD_DPRINTF(INV, "DMAR_IQA_REG 0x%"PRIx64, iqa_val);
1130             VTD_DPRINTF(INV, "Invalidation Queue addr 0x%"PRIx64 " size %d",
1131                         s->iq, s->iq_size);
1132             /* Ok - report back to driver */
1133             vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_QIES);
1134         } else {
1135             VTD_DPRINTF(GENERAL, "error: can't enable Queued Invalidation: "
1136                         "tail %"PRIu16, s->iq_tail);
1137         }
1138     } else {
1139         if (vtd_queued_inv_disable_check(s)) {
1140             /* disable Queued Invalidation */
1141             vtd_set_quad_raw(s, DMAR_IQH_REG, 0);
1142             s->iq_head = 0;
1143             s->qi_enabled = false;
1144             /* Ok - report back to driver */
1145             vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_QIES, 0);
1146         } else {
1147             VTD_DPRINTF(GENERAL, "error: can't disable Queued Invalidation: "
1148                         "head %"PRIu16 ", tail %"PRIu16
1149                         ", last_descriptor %"PRIu8,
1150                         s->iq_head, s->iq_tail, s->iq_last_desc_type);
1151         }
1152     }
1153 }
1154 
1155 /* Set Root Table Pointer */
1156 static void vtd_handle_gcmd_srtp(IntelIOMMUState *s)
1157 {
1158     VTD_DPRINTF(CSR, "set Root Table Pointer");
1159 
1160     vtd_root_table_setup(s);
1161     /* Ok - report back to driver */
1162     vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_RTPS);
1163 }
1164 
1165 /* Set Interrupt Remap Table Pointer */
1166 static void vtd_handle_gcmd_sirtp(IntelIOMMUState *s)
1167 {
1168     VTD_DPRINTF(CSR, "set Interrupt Remap Table Pointer");
1169 
1170     vtd_interrupt_remap_table_setup(s);
1171     /* Ok - report back to driver */
1172     vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_IRTPS);
1173 }
1174 
1175 /* Handle Translation Enable/Disable */
1176 static void vtd_handle_gcmd_te(IntelIOMMUState *s, bool en)
1177 {
1178     VTD_DPRINTF(CSR, "Translation Enable %s", (en ? "on" : "off"));
1179 
1180     if (en) {
1181         s->dmar_enabled = true;
1182         /* Ok - report back to driver */
1183         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_TES);
1184     } else {
1185         s->dmar_enabled = false;
1186 
1187         /* Clear the index of Fault Recording Register */
1188         s->next_frcd_reg = 0;
1189         /* Ok - report back to driver */
1190         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_TES, 0);
1191     }
1192 }
1193 
1194 /* Handle Interrupt Remap Enable/Disable */
1195 static void vtd_handle_gcmd_ire(IntelIOMMUState *s, bool en)
1196 {
1197     VTD_DPRINTF(CSR, "Interrupt Remap Enable %s", (en ? "on" : "off"));
1198 
1199     if (en) {
1200         s->intr_enabled = true;
1201         /* Ok - report back to driver */
1202         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_IRES);
1203     } else {
1204         s->intr_enabled = false;
1205         /* Ok - report back to driver */
1206         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_IRES, 0);
1207     }
1208 }
1209 
1210 /* Handle write to Global Command Register */
1211 static void vtd_handle_gcmd_write(IntelIOMMUState *s)
1212 {
1213     uint32_t status = vtd_get_long_raw(s, DMAR_GSTS_REG);
1214     uint32_t val = vtd_get_long_raw(s, DMAR_GCMD_REG);
1215     uint32_t changed = status ^ val;
1216 
1217     VTD_DPRINTF(CSR, "value 0x%"PRIx32 " status 0x%"PRIx32, val, status);
1218     if (changed & VTD_GCMD_TE) {
1219         /* Translation enable/disable */
1220         vtd_handle_gcmd_te(s, val & VTD_GCMD_TE);
1221     }
1222     if (val & VTD_GCMD_SRTP) {
1223         /* Set/update the root-table pointer */
1224         vtd_handle_gcmd_srtp(s);
1225     }
1226     if (changed & VTD_GCMD_QIE) {
1227         /* Queued Invalidation Enable */
1228         vtd_handle_gcmd_qie(s, val & VTD_GCMD_QIE);
1229     }
1230     if (val & VTD_GCMD_SIRTP) {
1231         /* Set/update the interrupt remapping root-table pointer */
1232         vtd_handle_gcmd_sirtp(s);
1233     }
1234     if (changed & VTD_GCMD_IRE) {
1235         /* Interrupt remap enable/disable */
1236         vtd_handle_gcmd_ire(s, val & VTD_GCMD_IRE);
1237     }
1238 }
1239 
1240 /* Handle write to Context Command Register */
1241 static void vtd_handle_ccmd_write(IntelIOMMUState *s)
1242 {
1243     uint64_t ret;
1244     uint64_t val = vtd_get_quad_raw(s, DMAR_CCMD_REG);
1245 
1246     /* Context-cache invalidation request */
1247     if (val & VTD_CCMD_ICC) {
1248         if (s->qi_enabled) {
1249             VTD_DPRINTF(GENERAL, "error: Queued Invalidation enabled, "
1250                         "should not use register-based invalidation");
1251             return;
1252         }
1253         ret = vtd_context_cache_invalidate(s, val);
1254         /* Invalidation completed. Change something to show */
1255         vtd_set_clear_mask_quad(s, DMAR_CCMD_REG, VTD_CCMD_ICC, 0ULL);
1256         ret = vtd_set_clear_mask_quad(s, DMAR_CCMD_REG, VTD_CCMD_CAIG_MASK,
1257                                       ret);
1258         VTD_DPRINTF(INV, "CCMD_REG write-back val: 0x%"PRIx64, ret);
1259     }
1260 }
1261 
1262 /* Handle write to IOTLB Invalidation Register */
1263 static void vtd_handle_iotlb_write(IntelIOMMUState *s)
1264 {
1265     uint64_t ret;
1266     uint64_t val = vtd_get_quad_raw(s, DMAR_IOTLB_REG);
1267 
1268     /* IOTLB invalidation request */
1269     if (val & VTD_TLB_IVT) {
1270         if (s->qi_enabled) {
1271             VTD_DPRINTF(GENERAL, "error: Queued Invalidation enabled, "
1272                         "should not use register-based invalidation");
1273             return;
1274         }
1275         ret = vtd_iotlb_flush(s, val);
1276         /* Invalidation completed. Change something to show */
1277         vtd_set_clear_mask_quad(s, DMAR_IOTLB_REG, VTD_TLB_IVT, 0ULL);
1278         ret = vtd_set_clear_mask_quad(s, DMAR_IOTLB_REG,
1279                                       VTD_TLB_FLUSH_GRANU_MASK_A, ret);
1280         VTD_DPRINTF(INV, "IOTLB_REG write-back val: 0x%"PRIx64, ret);
1281     }
1282 }
1283 
1284 /* Fetch an Invalidation Descriptor from the Invalidation Queue */
1285 static bool vtd_get_inv_desc(dma_addr_t base_addr, uint32_t offset,
1286                              VTDInvDesc *inv_desc)
1287 {
1288     dma_addr_t addr = base_addr + offset * sizeof(*inv_desc);
1289     if (dma_memory_read(&address_space_memory, addr, inv_desc,
1290         sizeof(*inv_desc))) {
1291         VTD_DPRINTF(GENERAL, "error: fail to fetch Invalidation Descriptor "
1292                     "base_addr 0x%"PRIx64 " offset %"PRIu32, base_addr, offset);
1293         inv_desc->lo = 0;
1294         inv_desc->hi = 0;
1295 
1296         return false;
1297     }
1298     inv_desc->lo = le64_to_cpu(inv_desc->lo);
1299     inv_desc->hi = le64_to_cpu(inv_desc->hi);
1300     return true;
1301 }
1302 
1303 static bool vtd_process_wait_desc(IntelIOMMUState *s, VTDInvDesc *inv_desc)
1304 {
1305     if ((inv_desc->hi & VTD_INV_DESC_WAIT_RSVD_HI) ||
1306         (inv_desc->lo & VTD_INV_DESC_WAIT_RSVD_LO)) {
1307         VTD_DPRINTF(GENERAL, "error: non-zero reserved field in Invalidation "
1308                     "Wait Descriptor hi 0x%"PRIx64 " lo 0x%"PRIx64,
1309                     inv_desc->hi, inv_desc->lo);
1310         return false;
1311     }
1312     if (inv_desc->lo & VTD_INV_DESC_WAIT_SW) {
1313         /* Status Write */
1314         uint32_t status_data = (uint32_t)(inv_desc->lo >>
1315                                VTD_INV_DESC_WAIT_DATA_SHIFT);
1316 
1317         assert(!(inv_desc->lo & VTD_INV_DESC_WAIT_IF));
1318 
1319         /* FIXME: need to be masked with HAW? */
1320         dma_addr_t status_addr = inv_desc->hi;
1321         VTD_DPRINTF(INV, "status data 0x%x, status addr 0x%"PRIx64,
1322                     status_data, status_addr);
1323         status_data = cpu_to_le32(status_data);
1324         if (dma_memory_write(&address_space_memory, status_addr, &status_data,
1325                              sizeof(status_data))) {
1326             VTD_DPRINTF(GENERAL, "error: fail to perform a coherent write");
1327             return false;
1328         }
1329     } else if (inv_desc->lo & VTD_INV_DESC_WAIT_IF) {
1330         /* Interrupt flag */
1331         VTD_DPRINTF(INV, "Invalidation Wait Descriptor interrupt completion");
1332         vtd_generate_completion_event(s);
1333     } else {
1334         VTD_DPRINTF(GENERAL, "error: invalid Invalidation Wait Descriptor: "
1335                     "hi 0x%"PRIx64 " lo 0x%"PRIx64, inv_desc->hi, inv_desc->lo);
1336         return false;
1337     }
1338     return true;
1339 }
1340 
1341 static bool vtd_process_context_cache_desc(IntelIOMMUState *s,
1342                                            VTDInvDesc *inv_desc)
1343 {
1344     if ((inv_desc->lo & VTD_INV_DESC_CC_RSVD) || inv_desc->hi) {
1345         VTD_DPRINTF(GENERAL, "error: non-zero reserved field in Context-cache "
1346                     "Invalidate Descriptor");
1347         return false;
1348     }
1349     switch (inv_desc->lo & VTD_INV_DESC_CC_G) {
1350     case VTD_INV_DESC_CC_DOMAIN:
1351         VTD_DPRINTF(INV, "domain-selective invalidation domain 0x%"PRIx16,
1352                     (uint16_t)VTD_INV_DESC_CC_DID(inv_desc->lo));
1353         /* Fall through */
1354     case VTD_INV_DESC_CC_GLOBAL:
1355         VTD_DPRINTF(INV, "global invalidation");
1356         vtd_context_global_invalidate(s);
1357         break;
1358 
1359     case VTD_INV_DESC_CC_DEVICE:
1360         vtd_context_device_invalidate(s, VTD_INV_DESC_CC_SID(inv_desc->lo),
1361                                       VTD_INV_DESC_CC_FM(inv_desc->lo));
1362         break;
1363 
1364     default:
1365         VTD_DPRINTF(GENERAL, "error: invalid granularity in Context-cache "
1366                     "Invalidate Descriptor hi 0x%"PRIx64  " lo 0x%"PRIx64,
1367                     inv_desc->hi, inv_desc->lo);
1368         return false;
1369     }
1370     return true;
1371 }
1372 
1373 static bool vtd_process_iotlb_desc(IntelIOMMUState *s, VTDInvDesc *inv_desc)
1374 {
1375     uint16_t domain_id;
1376     uint8_t am;
1377     hwaddr addr;
1378 
1379     if ((inv_desc->lo & VTD_INV_DESC_IOTLB_RSVD_LO) ||
1380         (inv_desc->hi & VTD_INV_DESC_IOTLB_RSVD_HI)) {
1381         VTD_DPRINTF(GENERAL, "error: non-zero reserved field in IOTLB "
1382                     "Invalidate Descriptor hi 0x%"PRIx64 " lo 0x%"PRIx64,
1383                     inv_desc->hi, inv_desc->lo);
1384         return false;
1385     }
1386 
1387     switch (inv_desc->lo & VTD_INV_DESC_IOTLB_G) {
1388     case VTD_INV_DESC_IOTLB_GLOBAL:
1389         VTD_DPRINTF(INV, "global invalidation");
1390         vtd_iotlb_global_invalidate(s);
1391         break;
1392 
1393     case VTD_INV_DESC_IOTLB_DOMAIN:
1394         domain_id = VTD_INV_DESC_IOTLB_DID(inv_desc->lo);
1395         VTD_DPRINTF(INV, "domain-selective invalidation domain 0x%"PRIx16,
1396                     domain_id);
1397         vtd_iotlb_domain_invalidate(s, domain_id);
1398         break;
1399 
1400     case VTD_INV_DESC_IOTLB_PAGE:
1401         domain_id = VTD_INV_DESC_IOTLB_DID(inv_desc->lo);
1402         addr = VTD_INV_DESC_IOTLB_ADDR(inv_desc->hi);
1403         am = VTD_INV_DESC_IOTLB_AM(inv_desc->hi);
1404         VTD_DPRINTF(INV, "page-selective invalidation domain 0x%"PRIx16
1405                     " addr 0x%"PRIx64 " mask %"PRIu8, domain_id, addr, am);
1406         if (am > VTD_MAMV) {
1407             VTD_DPRINTF(GENERAL, "error: supported max address mask value is "
1408                         "%"PRIu8, (uint8_t)VTD_MAMV);
1409             return false;
1410         }
1411         vtd_iotlb_page_invalidate(s, domain_id, addr, am);
1412         break;
1413 
1414     default:
1415         VTD_DPRINTF(GENERAL, "error: invalid granularity in IOTLB Invalidate "
1416                     "Descriptor hi 0x%"PRIx64 " lo 0x%"PRIx64,
1417                     inv_desc->hi, inv_desc->lo);
1418         return false;
1419     }
1420     return true;
1421 }
1422 
1423 static bool vtd_process_inv_iec_desc(IntelIOMMUState *s,
1424                                      VTDInvDesc *inv_desc)
1425 {
1426     VTD_DPRINTF(INV, "inv ir glob %d index %d mask %d",
1427                 inv_desc->iec.granularity,
1428                 inv_desc->iec.index,
1429                 inv_desc->iec.index_mask);
1430 
1431     vtd_iec_notify_all(s, !inv_desc->iec.granularity,
1432                        inv_desc->iec.index,
1433                        inv_desc->iec.index_mask);
1434 
1435     return true;
1436 }
1437 
1438 static bool vtd_process_inv_desc(IntelIOMMUState *s)
1439 {
1440     VTDInvDesc inv_desc;
1441     uint8_t desc_type;
1442 
1443     VTD_DPRINTF(INV, "iq head %"PRIu16, s->iq_head);
1444     if (!vtd_get_inv_desc(s->iq, s->iq_head, &inv_desc)) {
1445         s->iq_last_desc_type = VTD_INV_DESC_NONE;
1446         return false;
1447     }
1448     desc_type = inv_desc.lo & VTD_INV_DESC_TYPE;
1449     /* FIXME: should update at first or at last? */
1450     s->iq_last_desc_type = desc_type;
1451 
1452     switch (desc_type) {
1453     case VTD_INV_DESC_CC:
1454         VTD_DPRINTF(INV, "Context-cache Invalidate Descriptor hi 0x%"PRIx64
1455                     " lo 0x%"PRIx64, inv_desc.hi, inv_desc.lo);
1456         if (!vtd_process_context_cache_desc(s, &inv_desc)) {
1457             return false;
1458         }
1459         break;
1460 
1461     case VTD_INV_DESC_IOTLB:
1462         VTD_DPRINTF(INV, "IOTLB Invalidate Descriptor hi 0x%"PRIx64
1463                     " lo 0x%"PRIx64, inv_desc.hi, inv_desc.lo);
1464         if (!vtd_process_iotlb_desc(s, &inv_desc)) {
1465             return false;
1466         }
1467         break;
1468 
1469     case VTD_INV_DESC_WAIT:
1470         VTD_DPRINTF(INV, "Invalidation Wait Descriptor hi 0x%"PRIx64
1471                     " lo 0x%"PRIx64, inv_desc.hi, inv_desc.lo);
1472         if (!vtd_process_wait_desc(s, &inv_desc)) {
1473             return false;
1474         }
1475         break;
1476 
1477     case VTD_INV_DESC_IEC:
1478         VTD_DPRINTF(INV, "Invalidation Interrupt Entry Cache "
1479                     "Descriptor hi 0x%"PRIx64 " lo 0x%"PRIx64,
1480                     inv_desc.hi, inv_desc.lo);
1481         if (!vtd_process_inv_iec_desc(s, &inv_desc)) {
1482             return false;
1483         }
1484         break;
1485 
1486     default:
1487         VTD_DPRINTF(GENERAL, "error: unkonw Invalidation Descriptor type "
1488                     "hi 0x%"PRIx64 " lo 0x%"PRIx64 " type %"PRIu8,
1489                     inv_desc.hi, inv_desc.lo, desc_type);
1490         return false;
1491     }
1492     s->iq_head++;
1493     if (s->iq_head == s->iq_size) {
1494         s->iq_head = 0;
1495     }
1496     return true;
1497 }
1498 
1499 /* Try to fetch and process more Invalidation Descriptors */
1500 static void vtd_fetch_inv_desc(IntelIOMMUState *s)
1501 {
1502     VTD_DPRINTF(INV, "fetch Invalidation Descriptors");
1503     if (s->iq_tail >= s->iq_size) {
1504         /* Detects an invalid Tail pointer */
1505         VTD_DPRINTF(GENERAL, "error: iq_tail is %"PRIu16
1506                     " while iq_size is %"PRIu16, s->iq_tail, s->iq_size);
1507         vtd_handle_inv_queue_error(s);
1508         return;
1509     }
1510     while (s->iq_head != s->iq_tail) {
1511         if (!vtd_process_inv_desc(s)) {
1512             /* Invalidation Queue Errors */
1513             vtd_handle_inv_queue_error(s);
1514             break;
1515         }
1516         /* Must update the IQH_REG in time */
1517         vtd_set_quad_raw(s, DMAR_IQH_REG,
1518                          (((uint64_t)(s->iq_head)) << VTD_IQH_QH_SHIFT) &
1519                          VTD_IQH_QH_MASK);
1520     }
1521 }
1522 
1523 /* Handle write to Invalidation Queue Tail Register */
1524 static void vtd_handle_iqt_write(IntelIOMMUState *s)
1525 {
1526     uint64_t val = vtd_get_quad_raw(s, DMAR_IQT_REG);
1527 
1528     s->iq_tail = VTD_IQT_QT(val);
1529     VTD_DPRINTF(INV, "set iq tail %"PRIu16, s->iq_tail);
1530     if (s->qi_enabled && !(vtd_get_long_raw(s, DMAR_FSTS_REG) & VTD_FSTS_IQE)) {
1531         /* Process Invalidation Queue here */
1532         vtd_fetch_inv_desc(s);
1533     }
1534 }
1535 
1536 static void vtd_handle_fsts_write(IntelIOMMUState *s)
1537 {
1538     uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
1539     uint32_t fectl_reg = vtd_get_long_raw(s, DMAR_FECTL_REG);
1540     uint32_t status_fields = VTD_FSTS_PFO | VTD_FSTS_PPF | VTD_FSTS_IQE;
1541 
1542     if ((fectl_reg & VTD_FECTL_IP) && !(fsts_reg & status_fields)) {
1543         vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
1544         VTD_DPRINTF(FLOG, "all pending interrupt conditions serviced, clear "
1545                     "IP field of FECTL_REG");
1546     }
1547     /* FIXME: when IQE is Clear, should we try to fetch some Invalidation
1548      * Descriptors if there are any when Queued Invalidation is enabled?
1549      */
1550 }
1551 
1552 static void vtd_handle_fectl_write(IntelIOMMUState *s)
1553 {
1554     uint32_t fectl_reg;
1555     /* FIXME: when software clears the IM field, check the IP field. But do we
1556      * need to compare the old value and the new value to conclude that
1557      * software clears the IM field? Or just check if the IM field is zero?
1558      */
1559     fectl_reg = vtd_get_long_raw(s, DMAR_FECTL_REG);
1560     if ((fectl_reg & VTD_FECTL_IP) && !(fectl_reg & VTD_FECTL_IM)) {
1561         vtd_generate_interrupt(s, DMAR_FEADDR_REG, DMAR_FEDATA_REG);
1562         vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
1563         VTD_DPRINTF(FLOG, "IM field is cleared, generate "
1564                     "fault event interrupt");
1565     }
1566 }
1567 
1568 static void vtd_handle_ics_write(IntelIOMMUState *s)
1569 {
1570     uint32_t ics_reg = vtd_get_long_raw(s, DMAR_ICS_REG);
1571     uint32_t iectl_reg = vtd_get_long_raw(s, DMAR_IECTL_REG);
1572 
1573     if ((iectl_reg & VTD_IECTL_IP) && !(ics_reg & VTD_ICS_IWC)) {
1574         vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
1575         VTD_DPRINTF(INV, "pending completion interrupt condition serviced, "
1576                     "clear IP field of IECTL_REG");
1577     }
1578 }
1579 
1580 static void vtd_handle_iectl_write(IntelIOMMUState *s)
1581 {
1582     uint32_t iectl_reg;
1583     /* FIXME: when software clears the IM field, check the IP field. But do we
1584      * need to compare the old value and the new value to conclude that
1585      * software clears the IM field? Or just check if the IM field is zero?
1586      */
1587     iectl_reg = vtd_get_long_raw(s, DMAR_IECTL_REG);
1588     if ((iectl_reg & VTD_IECTL_IP) && !(iectl_reg & VTD_IECTL_IM)) {
1589         vtd_generate_interrupt(s, DMAR_IEADDR_REG, DMAR_IEDATA_REG);
1590         vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
1591         VTD_DPRINTF(INV, "IM field is cleared, generate "
1592                     "invalidation event interrupt");
1593     }
1594 }
1595 
1596 static uint64_t vtd_mem_read(void *opaque, hwaddr addr, unsigned size)
1597 {
1598     IntelIOMMUState *s = opaque;
1599     uint64_t val;
1600 
1601     if (addr + size > DMAR_REG_SIZE) {
1602         VTD_DPRINTF(GENERAL, "error: addr outside region: max 0x%"PRIx64
1603                     ", got 0x%"PRIx64 " %d",
1604                     (uint64_t)DMAR_REG_SIZE, addr, size);
1605         return (uint64_t)-1;
1606     }
1607 
1608     switch (addr) {
1609     /* Root Table Address Register, 64-bit */
1610     case DMAR_RTADDR_REG:
1611         if (size == 4) {
1612             val = s->root & ((1ULL << 32) - 1);
1613         } else {
1614             val = s->root;
1615         }
1616         break;
1617 
1618     case DMAR_RTADDR_REG_HI:
1619         assert(size == 4);
1620         val = s->root >> 32;
1621         break;
1622 
1623     /* Invalidation Queue Address Register, 64-bit */
1624     case DMAR_IQA_REG:
1625         val = s->iq | (vtd_get_quad(s, DMAR_IQA_REG) & VTD_IQA_QS);
1626         if (size == 4) {
1627             val = val & ((1ULL << 32) - 1);
1628         }
1629         break;
1630 
1631     case DMAR_IQA_REG_HI:
1632         assert(size == 4);
1633         val = s->iq >> 32;
1634         break;
1635 
1636     default:
1637         if (size == 4) {
1638             val = vtd_get_long(s, addr);
1639         } else {
1640             val = vtd_get_quad(s, addr);
1641         }
1642     }
1643     VTD_DPRINTF(CSR, "addr 0x%"PRIx64 " size %d val 0x%"PRIx64,
1644                 addr, size, val);
1645     return val;
1646 }
1647 
1648 static void vtd_mem_write(void *opaque, hwaddr addr,
1649                           uint64_t val, unsigned size)
1650 {
1651     IntelIOMMUState *s = opaque;
1652 
1653     if (addr + size > DMAR_REG_SIZE) {
1654         VTD_DPRINTF(GENERAL, "error: addr outside region: max 0x%"PRIx64
1655                     ", got 0x%"PRIx64 " %d",
1656                     (uint64_t)DMAR_REG_SIZE, addr, size);
1657         return;
1658     }
1659 
1660     switch (addr) {
1661     /* Global Command Register, 32-bit */
1662     case DMAR_GCMD_REG:
1663         VTD_DPRINTF(CSR, "DMAR_GCMD_REG write addr 0x%"PRIx64
1664                     ", size %d, val 0x%"PRIx64, addr, size, val);
1665         vtd_set_long(s, addr, val);
1666         vtd_handle_gcmd_write(s);
1667         break;
1668 
1669     /* Context Command Register, 64-bit */
1670     case DMAR_CCMD_REG:
1671         VTD_DPRINTF(CSR, "DMAR_CCMD_REG write addr 0x%"PRIx64
1672                     ", size %d, val 0x%"PRIx64, addr, size, val);
1673         if (size == 4) {
1674             vtd_set_long(s, addr, val);
1675         } else {
1676             vtd_set_quad(s, addr, val);
1677             vtd_handle_ccmd_write(s);
1678         }
1679         break;
1680 
1681     case DMAR_CCMD_REG_HI:
1682         VTD_DPRINTF(CSR, "DMAR_CCMD_REG_HI write addr 0x%"PRIx64
1683                     ", size %d, val 0x%"PRIx64, addr, size, val);
1684         assert(size == 4);
1685         vtd_set_long(s, addr, val);
1686         vtd_handle_ccmd_write(s);
1687         break;
1688 
1689     /* IOTLB Invalidation Register, 64-bit */
1690     case DMAR_IOTLB_REG:
1691         VTD_DPRINTF(INV, "DMAR_IOTLB_REG write addr 0x%"PRIx64
1692                     ", size %d, val 0x%"PRIx64, addr, size, val);
1693         if (size == 4) {
1694             vtd_set_long(s, addr, val);
1695         } else {
1696             vtd_set_quad(s, addr, val);
1697             vtd_handle_iotlb_write(s);
1698         }
1699         break;
1700 
1701     case DMAR_IOTLB_REG_HI:
1702         VTD_DPRINTF(INV, "DMAR_IOTLB_REG_HI write addr 0x%"PRIx64
1703                     ", size %d, val 0x%"PRIx64, addr, size, val);
1704         assert(size == 4);
1705         vtd_set_long(s, addr, val);
1706         vtd_handle_iotlb_write(s);
1707         break;
1708 
1709     /* Invalidate Address Register, 64-bit */
1710     case DMAR_IVA_REG:
1711         VTD_DPRINTF(INV, "DMAR_IVA_REG write addr 0x%"PRIx64
1712                     ", size %d, val 0x%"PRIx64, addr, size, val);
1713         if (size == 4) {
1714             vtd_set_long(s, addr, val);
1715         } else {
1716             vtd_set_quad(s, addr, val);
1717         }
1718         break;
1719 
1720     case DMAR_IVA_REG_HI:
1721         VTD_DPRINTF(INV, "DMAR_IVA_REG_HI write addr 0x%"PRIx64
1722                     ", size %d, val 0x%"PRIx64, addr, size, val);
1723         assert(size == 4);
1724         vtd_set_long(s, addr, val);
1725         break;
1726 
1727     /* Fault Status Register, 32-bit */
1728     case DMAR_FSTS_REG:
1729         VTD_DPRINTF(FLOG, "DMAR_FSTS_REG write addr 0x%"PRIx64
1730                     ", size %d, val 0x%"PRIx64, addr, size, val);
1731         assert(size == 4);
1732         vtd_set_long(s, addr, val);
1733         vtd_handle_fsts_write(s);
1734         break;
1735 
1736     /* Fault Event Control Register, 32-bit */
1737     case DMAR_FECTL_REG:
1738         VTD_DPRINTF(FLOG, "DMAR_FECTL_REG write addr 0x%"PRIx64
1739                     ", size %d, val 0x%"PRIx64, addr, size, val);
1740         assert(size == 4);
1741         vtd_set_long(s, addr, val);
1742         vtd_handle_fectl_write(s);
1743         break;
1744 
1745     /* Fault Event Data Register, 32-bit */
1746     case DMAR_FEDATA_REG:
1747         VTD_DPRINTF(FLOG, "DMAR_FEDATA_REG write addr 0x%"PRIx64
1748                     ", size %d, val 0x%"PRIx64, addr, size, val);
1749         assert(size == 4);
1750         vtd_set_long(s, addr, val);
1751         break;
1752 
1753     /* Fault Event Address Register, 32-bit */
1754     case DMAR_FEADDR_REG:
1755         VTD_DPRINTF(FLOG, "DMAR_FEADDR_REG write addr 0x%"PRIx64
1756                     ", size %d, val 0x%"PRIx64, addr, size, val);
1757         assert(size == 4);
1758         vtd_set_long(s, addr, val);
1759         break;
1760 
1761     /* Fault Event Upper Address Register, 32-bit */
1762     case DMAR_FEUADDR_REG:
1763         VTD_DPRINTF(FLOG, "DMAR_FEUADDR_REG write addr 0x%"PRIx64
1764                     ", size %d, val 0x%"PRIx64, addr, size, val);
1765         assert(size == 4);
1766         vtd_set_long(s, addr, val);
1767         break;
1768 
1769     /* Protected Memory Enable Register, 32-bit */
1770     case DMAR_PMEN_REG:
1771         VTD_DPRINTF(CSR, "DMAR_PMEN_REG write addr 0x%"PRIx64
1772                     ", size %d, val 0x%"PRIx64, addr, size, val);
1773         assert(size == 4);
1774         vtd_set_long(s, addr, val);
1775         break;
1776 
1777     /* Root Table Address Register, 64-bit */
1778     case DMAR_RTADDR_REG:
1779         VTD_DPRINTF(CSR, "DMAR_RTADDR_REG write addr 0x%"PRIx64
1780                     ", size %d, val 0x%"PRIx64, addr, size, val);
1781         if (size == 4) {
1782             vtd_set_long(s, addr, val);
1783         } else {
1784             vtd_set_quad(s, addr, val);
1785         }
1786         break;
1787 
1788     case DMAR_RTADDR_REG_HI:
1789         VTD_DPRINTF(CSR, "DMAR_RTADDR_REG_HI write addr 0x%"PRIx64
1790                     ", size %d, val 0x%"PRIx64, addr, size, val);
1791         assert(size == 4);
1792         vtd_set_long(s, addr, val);
1793         break;
1794 
1795     /* Invalidation Queue Tail Register, 64-bit */
1796     case DMAR_IQT_REG:
1797         VTD_DPRINTF(INV, "DMAR_IQT_REG write addr 0x%"PRIx64
1798                     ", size %d, val 0x%"PRIx64, addr, size, val);
1799         if (size == 4) {
1800             vtd_set_long(s, addr, val);
1801         } else {
1802             vtd_set_quad(s, addr, val);
1803         }
1804         vtd_handle_iqt_write(s);
1805         break;
1806 
1807     case DMAR_IQT_REG_HI:
1808         VTD_DPRINTF(INV, "DMAR_IQT_REG_HI write addr 0x%"PRIx64
1809                     ", size %d, val 0x%"PRIx64, addr, size, val);
1810         assert(size == 4);
1811         vtd_set_long(s, addr, val);
1812         /* 19:63 of IQT_REG is RsvdZ, do nothing here */
1813         break;
1814 
1815     /* Invalidation Queue Address Register, 64-bit */
1816     case DMAR_IQA_REG:
1817         VTD_DPRINTF(INV, "DMAR_IQA_REG write addr 0x%"PRIx64
1818                     ", size %d, val 0x%"PRIx64, addr, size, val);
1819         if (size == 4) {
1820             vtd_set_long(s, addr, val);
1821         } else {
1822             vtd_set_quad(s, addr, val);
1823         }
1824         break;
1825 
1826     case DMAR_IQA_REG_HI:
1827         VTD_DPRINTF(INV, "DMAR_IQA_REG_HI write addr 0x%"PRIx64
1828                     ", size %d, val 0x%"PRIx64, addr, size, val);
1829         assert(size == 4);
1830         vtd_set_long(s, addr, val);
1831         break;
1832 
1833     /* Invalidation Completion Status Register, 32-bit */
1834     case DMAR_ICS_REG:
1835         VTD_DPRINTF(INV, "DMAR_ICS_REG write addr 0x%"PRIx64
1836                     ", size %d, val 0x%"PRIx64, addr, size, val);
1837         assert(size == 4);
1838         vtd_set_long(s, addr, val);
1839         vtd_handle_ics_write(s);
1840         break;
1841 
1842     /* Invalidation Event Control Register, 32-bit */
1843     case DMAR_IECTL_REG:
1844         VTD_DPRINTF(INV, "DMAR_IECTL_REG write addr 0x%"PRIx64
1845                     ", size %d, val 0x%"PRIx64, addr, size, val);
1846         assert(size == 4);
1847         vtd_set_long(s, addr, val);
1848         vtd_handle_iectl_write(s);
1849         break;
1850 
1851     /* Invalidation Event Data Register, 32-bit */
1852     case DMAR_IEDATA_REG:
1853         VTD_DPRINTF(INV, "DMAR_IEDATA_REG write addr 0x%"PRIx64
1854                     ", size %d, val 0x%"PRIx64, addr, size, val);
1855         assert(size == 4);
1856         vtd_set_long(s, addr, val);
1857         break;
1858 
1859     /* Invalidation Event Address Register, 32-bit */
1860     case DMAR_IEADDR_REG:
1861         VTD_DPRINTF(INV, "DMAR_IEADDR_REG write addr 0x%"PRIx64
1862                     ", size %d, val 0x%"PRIx64, addr, size, val);
1863         assert(size == 4);
1864         vtd_set_long(s, addr, val);
1865         break;
1866 
1867     /* Invalidation Event Upper Address Register, 32-bit */
1868     case DMAR_IEUADDR_REG:
1869         VTD_DPRINTF(INV, "DMAR_IEUADDR_REG write addr 0x%"PRIx64
1870                     ", size %d, val 0x%"PRIx64, addr, size, val);
1871         assert(size == 4);
1872         vtd_set_long(s, addr, val);
1873         break;
1874 
1875     /* Fault Recording Registers, 128-bit */
1876     case DMAR_FRCD_REG_0_0:
1877         VTD_DPRINTF(FLOG, "DMAR_FRCD_REG_0_0 write addr 0x%"PRIx64
1878                     ", size %d, val 0x%"PRIx64, addr, size, val);
1879         if (size == 4) {
1880             vtd_set_long(s, addr, val);
1881         } else {
1882             vtd_set_quad(s, addr, val);
1883         }
1884         break;
1885 
1886     case DMAR_FRCD_REG_0_1:
1887         VTD_DPRINTF(FLOG, "DMAR_FRCD_REG_0_1 write addr 0x%"PRIx64
1888                     ", size %d, val 0x%"PRIx64, addr, size, val);
1889         assert(size == 4);
1890         vtd_set_long(s, addr, val);
1891         break;
1892 
1893     case DMAR_FRCD_REG_0_2:
1894         VTD_DPRINTF(FLOG, "DMAR_FRCD_REG_0_2 write addr 0x%"PRIx64
1895                     ", size %d, val 0x%"PRIx64, addr, size, val);
1896         if (size == 4) {
1897             vtd_set_long(s, addr, val);
1898         } else {
1899             vtd_set_quad(s, addr, val);
1900             /* May clear bit 127 (Fault), update PPF */
1901             vtd_update_fsts_ppf(s);
1902         }
1903         break;
1904 
1905     case DMAR_FRCD_REG_0_3:
1906         VTD_DPRINTF(FLOG, "DMAR_FRCD_REG_0_3 write addr 0x%"PRIx64
1907                     ", size %d, val 0x%"PRIx64, addr, size, val);
1908         assert(size == 4);
1909         vtd_set_long(s, addr, val);
1910         /* May clear bit 127 (Fault), update PPF */
1911         vtd_update_fsts_ppf(s);
1912         break;
1913 
1914     case DMAR_IRTA_REG:
1915         VTD_DPRINTF(IR, "DMAR_IRTA_REG write addr 0x%"PRIx64
1916                     ", size %d, val 0x%"PRIx64, addr, size, val);
1917         if (size == 4) {
1918             vtd_set_long(s, addr, val);
1919         } else {
1920             vtd_set_quad(s, addr, val);
1921         }
1922         break;
1923 
1924     case DMAR_IRTA_REG_HI:
1925         VTD_DPRINTF(IR, "DMAR_IRTA_REG_HI write addr 0x%"PRIx64
1926                     ", size %d, val 0x%"PRIx64, addr, size, val);
1927         assert(size == 4);
1928         vtd_set_long(s, addr, val);
1929         break;
1930 
1931     default:
1932         VTD_DPRINTF(GENERAL, "error: unhandled reg write addr 0x%"PRIx64
1933                     ", size %d, val 0x%"PRIx64, addr, size, val);
1934         if (size == 4) {
1935             vtd_set_long(s, addr, val);
1936         } else {
1937             vtd_set_quad(s, addr, val);
1938         }
1939     }
1940 }
1941 
1942 static IOMMUTLBEntry vtd_iommu_translate(MemoryRegion *iommu, hwaddr addr,
1943                                          bool is_write)
1944 {
1945     VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu);
1946     IntelIOMMUState *s = vtd_as->iommu_state;
1947     IOMMUTLBEntry ret = {
1948         .target_as = &address_space_memory,
1949         .iova = addr,
1950         .translated_addr = 0,
1951         .addr_mask = ~(hwaddr)0,
1952         .perm = IOMMU_NONE,
1953     };
1954 
1955     if (!s->dmar_enabled) {
1956         /* DMAR disabled, passthrough, use 4k-page*/
1957         ret.iova = addr & VTD_PAGE_MASK_4K;
1958         ret.translated_addr = addr & VTD_PAGE_MASK_4K;
1959         ret.addr_mask = ~VTD_PAGE_MASK_4K;
1960         ret.perm = IOMMU_RW;
1961         return ret;
1962     }
1963 
1964     vtd_do_iommu_translate(vtd_as, vtd_as->bus, vtd_as->devfn, addr,
1965                            is_write, &ret);
1966     VTD_DPRINTF(MMU,
1967                 "bus %"PRIu8 " slot %"PRIu8 " func %"PRIu8 " devfn %"PRIu8
1968                 " gpa 0x%"PRIx64 " hpa 0x%"PRIx64, pci_bus_num(vtd_as->bus),
1969                 VTD_PCI_SLOT(vtd_as->devfn), VTD_PCI_FUNC(vtd_as->devfn),
1970                 vtd_as->devfn, addr, ret.translated_addr);
1971     return ret;
1972 }
1973 
1974 static void vtd_iommu_notify_started(MemoryRegion *iommu)
1975 {
1976     VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu);
1977 
1978     hw_error("Device at bus %s addr %02x.%d requires iommu notifier which "
1979              "is currently not supported by intel-iommu emulation",
1980              vtd_as->bus->qbus.name, PCI_SLOT(vtd_as->devfn),
1981              PCI_FUNC(vtd_as->devfn));
1982 }
1983 
1984 static const VMStateDescription vtd_vmstate = {
1985     .name = "iommu-intel",
1986     .unmigratable = 1,
1987 };
1988 
1989 static const MemoryRegionOps vtd_mem_ops = {
1990     .read = vtd_mem_read,
1991     .write = vtd_mem_write,
1992     .endianness = DEVICE_LITTLE_ENDIAN,
1993     .impl = {
1994         .min_access_size = 4,
1995         .max_access_size = 8,
1996     },
1997     .valid = {
1998         .min_access_size = 4,
1999         .max_access_size = 8,
2000     },
2001 };
2002 
2003 static Property vtd_properties[] = {
2004     DEFINE_PROP_UINT32("version", IntelIOMMUState, version, 0),
2005     DEFINE_PROP_END_OF_LIST(),
2006 };
2007 
2008 /* Read IRTE entry with specific index */
2009 static int vtd_irte_get(IntelIOMMUState *iommu, uint16_t index,
2010                         VTD_IRTE *entry)
2011 {
2012     dma_addr_t addr = 0x00;
2013 
2014     addr = iommu->intr_root + index * sizeof(*entry);
2015     if (dma_memory_read(&address_space_memory, addr, entry,
2016                         sizeof(*entry))) {
2017         VTD_DPRINTF(GENERAL, "error: fail to access IR root at 0x%"PRIx64
2018                     " + %"PRIu16, iommu->intr_root, index);
2019         return -VTD_FR_IR_ROOT_INVAL;
2020     }
2021 
2022     if (!entry->present) {
2023         VTD_DPRINTF(GENERAL, "error: present flag not set in IRTE"
2024                     " entry index %u value 0x%"PRIx64 " 0x%"PRIx64,
2025                     index, le64_to_cpu(entry->data[1]),
2026                     le64_to_cpu(entry->data[0]));
2027         return -VTD_FR_IR_ENTRY_P;
2028     }
2029 
2030     if (entry->__reserved_0 || entry->__reserved_1 || \
2031         entry->__reserved_2) {
2032         VTD_DPRINTF(GENERAL, "error: IRTE entry index %"PRIu16
2033                     " reserved fields non-zero: 0x%"PRIx64 " 0x%"PRIx64,
2034                     index, le64_to_cpu(entry->data[1]),
2035                     le64_to_cpu(entry->data[0]));
2036         return -VTD_FR_IR_IRTE_RSVD;
2037     }
2038 
2039     /*
2040      * TODO: Check Source-ID corresponds to SVT (Source Validation
2041      * Type) bits
2042      */
2043 
2044     return 0;
2045 }
2046 
2047 /* Fetch IRQ information of specific IR index */
2048 static int vtd_remap_irq_get(IntelIOMMUState *iommu, uint16_t index, VTDIrq *irq)
2049 {
2050     VTD_IRTE irte = {};
2051     int ret = 0;
2052 
2053     ret = vtd_irte_get(iommu, index, &irte);
2054     if (ret) {
2055         return ret;
2056     }
2057 
2058     irq->trigger_mode = irte.trigger_mode;
2059     irq->vector = irte.vector;
2060     irq->delivery_mode = irte.delivery_mode;
2061     /* Not support EIM yet: please refer to vt-d 9.10 DST bits */
2062 #define  VTD_IR_APIC_DEST_MASK         (0xff00ULL)
2063 #define  VTD_IR_APIC_DEST_SHIFT        (8)
2064     irq->dest = (le32_to_cpu(irte.dest_id) & VTD_IR_APIC_DEST_MASK) >> \
2065         VTD_IR_APIC_DEST_SHIFT;
2066     irq->dest_mode = irte.dest_mode;
2067     irq->redir_hint = irte.redir_hint;
2068 
2069     VTD_DPRINTF(IR, "remapping interrupt index %d: trig:%u,vec:%u,"
2070                 "deliver:%u,dest:%u,dest_mode:%u", index,
2071                 irq->trigger_mode, irq->vector, irq->delivery_mode,
2072                 irq->dest, irq->dest_mode);
2073 
2074     return 0;
2075 }
2076 
2077 /* Generate one MSI message from VTDIrq info */
2078 static void vtd_generate_msi_message(VTDIrq *irq, MSIMessage *msg_out)
2079 {
2080     VTD_MSIMessage msg = {};
2081 
2082     /* Generate address bits */
2083     msg.dest_mode = irq->dest_mode;
2084     msg.redir_hint = irq->redir_hint;
2085     msg.dest = irq->dest;
2086     msg.__addr_head = cpu_to_le32(0xfee);
2087     /* Keep this from original MSI address bits */
2088     msg.__not_used = irq->msi_addr_last_bits;
2089 
2090     /* Generate data bits */
2091     msg.vector = irq->vector;
2092     msg.delivery_mode = irq->delivery_mode;
2093     msg.level = 1;
2094     msg.trigger_mode = irq->trigger_mode;
2095 
2096     msg_out->address = msg.msi_addr;
2097     msg_out->data = msg.msi_data;
2098 }
2099 
2100 /* Interrupt remapping for MSI/MSI-X entry */
2101 static int vtd_interrupt_remap_msi(IntelIOMMUState *iommu,
2102                                    MSIMessage *origin,
2103                                    MSIMessage *translated)
2104 {
2105     int ret = 0;
2106     VTD_IR_MSIAddress addr;
2107     uint16_t index;
2108     VTDIrq irq = {};
2109 
2110     assert(origin && translated);
2111 
2112     if (!iommu || !iommu->intr_enabled) {
2113         goto do_not_translate;
2114     }
2115 
2116     if (origin->address & VTD_MSI_ADDR_HI_MASK) {
2117         VTD_DPRINTF(GENERAL, "error: MSI addr high 32 bits nonzero"
2118                     " during interrupt remapping: 0x%"PRIx32,
2119                     (uint32_t)((origin->address & VTD_MSI_ADDR_HI_MASK) >> \
2120                     VTD_MSI_ADDR_HI_SHIFT));
2121         return -VTD_FR_IR_REQ_RSVD;
2122     }
2123 
2124     addr.data = origin->address & VTD_MSI_ADDR_LO_MASK;
2125     if (le16_to_cpu(addr.__head) != 0xfee) {
2126         VTD_DPRINTF(GENERAL, "error: MSI addr low 32 bits invalid: "
2127                     "0x%"PRIx32, addr.data);
2128         return -VTD_FR_IR_REQ_RSVD;
2129     }
2130 
2131     /* This is compatible mode. */
2132     if (addr.int_mode != VTD_IR_INT_FORMAT_REMAP) {
2133         goto do_not_translate;
2134     }
2135 
2136     index = addr.index_h << 15 | le16_to_cpu(addr.index_l);
2137 
2138 #define  VTD_IR_MSI_DATA_SUBHANDLE       (0x0000ffff)
2139 #define  VTD_IR_MSI_DATA_RESERVED        (0xffff0000)
2140 
2141     if (addr.sub_valid) {
2142         /* See VT-d spec 5.1.2.2 and 5.1.3 on subhandle */
2143         index += origin->data & VTD_IR_MSI_DATA_SUBHANDLE;
2144     }
2145 
2146     ret = vtd_remap_irq_get(iommu, index, &irq);
2147     if (ret) {
2148         return ret;
2149     }
2150 
2151     if (addr.sub_valid) {
2152         VTD_DPRINTF(IR, "received MSI interrupt");
2153         if (origin->data & VTD_IR_MSI_DATA_RESERVED) {
2154             VTD_DPRINTF(GENERAL, "error: MSI data bits non-zero for "
2155                         "interrupt remappable entry: 0x%"PRIx32,
2156                         origin->data);
2157             return -VTD_FR_IR_REQ_RSVD;
2158         }
2159     } else {
2160         uint8_t vector = origin->data & 0xff;
2161         VTD_DPRINTF(IR, "received IOAPIC interrupt");
2162         /* IOAPIC entry vector should be aligned with IRTE vector
2163          * (see vt-d spec 5.1.5.1). */
2164         if (vector != irq.vector) {
2165             VTD_DPRINTF(GENERAL, "IOAPIC vector inconsistent: "
2166                         "entry: %d, IRTE: %d, index: %d",
2167                         vector, irq.vector, index);
2168         }
2169     }
2170 
2171     /*
2172      * We'd better keep the last two bits, assuming that guest OS
2173      * might modify it. Keep it does not hurt after all.
2174      */
2175     irq.msi_addr_last_bits = addr.__not_care;
2176 
2177     /* Translate VTDIrq to MSI message */
2178     vtd_generate_msi_message(&irq, translated);
2179 
2180     VTD_DPRINTF(IR, "mapping MSI 0x%"PRIx64":0x%"PRIx32 " -> "
2181                 "0x%"PRIx64":0x%"PRIx32, origin->address, origin->data,
2182                 translated->address, translated->data);
2183     return 0;
2184 
2185 do_not_translate:
2186     memcpy(translated, origin, sizeof(*origin));
2187     return 0;
2188 }
2189 
2190 static int vtd_int_remap(X86IOMMUState *iommu, MSIMessage *src,
2191                          MSIMessage *dst, uint16_t sid)
2192 {
2193     return vtd_interrupt_remap_msi(INTEL_IOMMU_DEVICE(iommu), src, dst);
2194 }
2195 
2196 static MemTxResult vtd_mem_ir_read(void *opaque, hwaddr addr,
2197                                    uint64_t *data, unsigned size,
2198                                    MemTxAttrs attrs)
2199 {
2200     return MEMTX_OK;
2201 }
2202 
2203 static MemTxResult vtd_mem_ir_write(void *opaque, hwaddr addr,
2204                                     uint64_t value, unsigned size,
2205                                     MemTxAttrs attrs)
2206 {
2207     int ret = 0;
2208     MSIMessage from = {}, to = {};
2209 
2210     from.address = (uint64_t) addr + VTD_INTERRUPT_ADDR_FIRST;
2211     from.data = (uint32_t) value;
2212 
2213     ret = vtd_interrupt_remap_msi(opaque, &from, &to);
2214     if (ret) {
2215         /* TODO: report error */
2216         VTD_DPRINTF(GENERAL, "int remap fail for addr 0x%"PRIx64
2217                     " data 0x%"PRIx32, from.address, from.data);
2218         /* Drop this interrupt */
2219         return MEMTX_ERROR;
2220     }
2221 
2222     VTD_DPRINTF(IR, "delivering MSI 0x%"PRIx64":0x%"PRIx32
2223                 " for device sid 0x%04x",
2224                 to.address, to.data, sid);
2225 
2226     if (dma_memory_write(&address_space_memory, to.address,
2227                          &to.data, size)) {
2228         VTD_DPRINTF(GENERAL, "error: fail to write 0x%"PRIx64
2229                     " value 0x%"PRIx32, to.address, to.data);
2230     }
2231 
2232     return MEMTX_OK;
2233 }
2234 
2235 static const MemoryRegionOps vtd_mem_ir_ops = {
2236     .read_with_attrs = vtd_mem_ir_read,
2237     .write_with_attrs = vtd_mem_ir_write,
2238     .endianness = DEVICE_LITTLE_ENDIAN,
2239     .impl = {
2240         .min_access_size = 4,
2241         .max_access_size = 4,
2242     },
2243     .valid = {
2244         .min_access_size = 4,
2245         .max_access_size = 4,
2246     },
2247 };
2248 
2249 VTDAddressSpace *vtd_find_add_as(IntelIOMMUState *s, PCIBus *bus, int devfn)
2250 {
2251     uintptr_t key = (uintptr_t)bus;
2252     VTDBus *vtd_bus = g_hash_table_lookup(s->vtd_as_by_busptr, &key);
2253     VTDAddressSpace *vtd_dev_as;
2254 
2255     if (!vtd_bus) {
2256         /* No corresponding free() */
2257         vtd_bus = g_malloc0(sizeof(VTDBus) + sizeof(VTDAddressSpace *) * \
2258                             X86_IOMMU_PCI_DEVFN_MAX);
2259         vtd_bus->bus = bus;
2260         key = (uintptr_t)bus;
2261         g_hash_table_insert(s->vtd_as_by_busptr, &key, vtd_bus);
2262     }
2263 
2264     vtd_dev_as = vtd_bus->dev_as[devfn];
2265 
2266     if (!vtd_dev_as) {
2267         vtd_bus->dev_as[devfn] = vtd_dev_as = g_malloc0(sizeof(VTDAddressSpace));
2268 
2269         vtd_dev_as->bus = bus;
2270         vtd_dev_as->devfn = (uint8_t)devfn;
2271         vtd_dev_as->iommu_state = s;
2272         vtd_dev_as->context_cache_entry.context_cache_gen = 0;
2273         memory_region_init_iommu(&vtd_dev_as->iommu, OBJECT(s),
2274                                  &s->iommu_ops, "intel_iommu", UINT64_MAX);
2275         memory_region_init_io(&vtd_dev_as->iommu_ir, OBJECT(s),
2276                               &vtd_mem_ir_ops, s, "intel_iommu_ir",
2277                               VTD_INTERRUPT_ADDR_SIZE);
2278         memory_region_add_subregion(&vtd_dev_as->iommu, VTD_INTERRUPT_ADDR_FIRST,
2279                                     &vtd_dev_as->iommu_ir);
2280         address_space_init(&vtd_dev_as->as,
2281                            &vtd_dev_as->iommu, "intel_iommu");
2282     }
2283     return vtd_dev_as;
2284 }
2285 
2286 /* Do the initialization. It will also be called when reset, so pay
2287  * attention when adding new initialization stuff.
2288  */
2289 static void vtd_init(IntelIOMMUState *s)
2290 {
2291     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
2292 
2293     memset(s->csr, 0, DMAR_REG_SIZE);
2294     memset(s->wmask, 0, DMAR_REG_SIZE);
2295     memset(s->w1cmask, 0, DMAR_REG_SIZE);
2296     memset(s->womask, 0, DMAR_REG_SIZE);
2297 
2298     s->iommu_ops.translate = vtd_iommu_translate;
2299     s->iommu_ops.notify_started = vtd_iommu_notify_started;
2300     s->root = 0;
2301     s->root_extended = false;
2302     s->dmar_enabled = false;
2303     s->iq_head = 0;
2304     s->iq_tail = 0;
2305     s->iq = 0;
2306     s->iq_size = 0;
2307     s->qi_enabled = false;
2308     s->iq_last_desc_type = VTD_INV_DESC_NONE;
2309     s->next_frcd_reg = 0;
2310     s->cap = VTD_CAP_FRO | VTD_CAP_NFR | VTD_CAP_ND | VTD_CAP_MGAW |
2311              VTD_CAP_SAGAW | VTD_CAP_MAMV | VTD_CAP_PSI | VTD_CAP_SLLPS;
2312     s->ecap = VTD_ECAP_QI | VTD_ECAP_IRO;
2313 
2314     if (x86_iommu->intr_supported) {
2315         s->ecap |= VTD_ECAP_IR;
2316     }
2317 
2318     vtd_reset_context_cache(s);
2319     vtd_reset_iotlb(s);
2320 
2321     /* Define registers with default values and bit semantics */
2322     vtd_define_long(s, DMAR_VER_REG, 0x10UL, 0, 0);
2323     vtd_define_quad(s, DMAR_CAP_REG, s->cap, 0, 0);
2324     vtd_define_quad(s, DMAR_ECAP_REG, s->ecap, 0, 0);
2325     vtd_define_long(s, DMAR_GCMD_REG, 0, 0xff800000UL, 0);
2326     vtd_define_long_wo(s, DMAR_GCMD_REG, 0xff800000UL);
2327     vtd_define_long(s, DMAR_GSTS_REG, 0, 0, 0);
2328     vtd_define_quad(s, DMAR_RTADDR_REG, 0, 0xfffffffffffff000ULL, 0);
2329     vtd_define_quad(s, DMAR_CCMD_REG, 0, 0xe0000003ffffffffULL, 0);
2330     vtd_define_quad_wo(s, DMAR_CCMD_REG, 0x3ffff0000ULL);
2331 
2332     /* Advanced Fault Logging not supported */
2333     vtd_define_long(s, DMAR_FSTS_REG, 0, 0, 0x11UL);
2334     vtd_define_long(s, DMAR_FECTL_REG, 0x80000000UL, 0x80000000UL, 0);
2335     vtd_define_long(s, DMAR_FEDATA_REG, 0, 0x0000ffffUL, 0);
2336     vtd_define_long(s, DMAR_FEADDR_REG, 0, 0xfffffffcUL, 0);
2337 
2338     /* Treated as RsvdZ when EIM in ECAP_REG is not supported
2339      * vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0xffffffffUL, 0);
2340      */
2341     vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0, 0);
2342 
2343     /* Treated as RO for implementations that PLMR and PHMR fields reported
2344      * as Clear in the CAP_REG.
2345      * vtd_define_long(s, DMAR_PMEN_REG, 0, 0x80000000UL, 0);
2346      */
2347     vtd_define_long(s, DMAR_PMEN_REG, 0, 0, 0);
2348 
2349     vtd_define_quad(s, DMAR_IQH_REG, 0, 0, 0);
2350     vtd_define_quad(s, DMAR_IQT_REG, 0, 0x7fff0ULL, 0);
2351     vtd_define_quad(s, DMAR_IQA_REG, 0, 0xfffffffffffff007ULL, 0);
2352     vtd_define_long(s, DMAR_ICS_REG, 0, 0, 0x1UL);
2353     vtd_define_long(s, DMAR_IECTL_REG, 0x80000000UL, 0x80000000UL, 0);
2354     vtd_define_long(s, DMAR_IEDATA_REG, 0, 0xffffffffUL, 0);
2355     vtd_define_long(s, DMAR_IEADDR_REG, 0, 0xfffffffcUL, 0);
2356     /* Treadted as RsvdZ when EIM in ECAP_REG is not supported */
2357     vtd_define_long(s, DMAR_IEUADDR_REG, 0, 0, 0);
2358 
2359     /* IOTLB registers */
2360     vtd_define_quad(s, DMAR_IOTLB_REG, 0, 0Xb003ffff00000000ULL, 0);
2361     vtd_define_quad(s, DMAR_IVA_REG, 0, 0xfffffffffffff07fULL, 0);
2362     vtd_define_quad_wo(s, DMAR_IVA_REG, 0xfffffffffffff07fULL);
2363 
2364     /* Fault Recording Registers, 128-bit */
2365     vtd_define_quad(s, DMAR_FRCD_REG_0_0, 0, 0, 0);
2366     vtd_define_quad(s, DMAR_FRCD_REG_0_2, 0, 0, 0x8000000000000000ULL);
2367 
2368     /*
2369      * Interrupt remapping registers, not support extended interrupt
2370      * mode for now.
2371      */
2372     vtd_define_quad(s, DMAR_IRTA_REG, 0, 0xfffffffffffff00fULL, 0);
2373 }
2374 
2375 /* Should not reset address_spaces when reset because devices will still use
2376  * the address space they got at first (won't ask the bus again).
2377  */
2378 static void vtd_reset(DeviceState *dev)
2379 {
2380     IntelIOMMUState *s = INTEL_IOMMU_DEVICE(dev);
2381 
2382     VTD_DPRINTF(GENERAL, "");
2383     vtd_init(s);
2384 }
2385 
2386 static AddressSpace *vtd_host_dma_iommu(PCIBus *bus, void *opaque, int devfn)
2387 {
2388     IntelIOMMUState *s = opaque;
2389     VTDAddressSpace *vtd_as;
2390 
2391     assert(0 <= devfn && devfn <= X86_IOMMU_PCI_DEVFN_MAX);
2392 
2393     vtd_as = vtd_find_add_as(s, bus, devfn);
2394     return &vtd_as->as;
2395 }
2396 
2397 static void vtd_realize(DeviceState *dev, Error **errp)
2398 {
2399     PCMachineState *pcms = PC_MACHINE(qdev_get_machine());
2400     PCIBus *bus = pcms->bus;
2401     IntelIOMMUState *s = INTEL_IOMMU_DEVICE(dev);
2402 
2403     VTD_DPRINTF(GENERAL, "");
2404     memset(s->vtd_as_by_bus_num, 0, sizeof(s->vtd_as_by_bus_num));
2405     memory_region_init_io(&s->csrmem, OBJECT(s), &vtd_mem_ops, s,
2406                           "intel_iommu", DMAR_REG_SIZE);
2407     sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->csrmem);
2408     /* No corresponding destroy */
2409     s->iotlb = g_hash_table_new_full(vtd_uint64_hash, vtd_uint64_equal,
2410                                      g_free, g_free);
2411     s->vtd_as_by_busptr = g_hash_table_new_full(vtd_uint64_hash, vtd_uint64_equal,
2412                                               g_free, g_free);
2413     vtd_init(s);
2414     sysbus_mmio_map(SYS_BUS_DEVICE(s), 0, Q35_HOST_BRIDGE_IOMMU_ADDR);
2415     pci_setup_iommu(bus, vtd_host_dma_iommu, dev);
2416     /* Pseudo address space under root PCI bus. */
2417     pcms->ioapic_as = vtd_host_dma_iommu(bus, s, Q35_PSEUDO_DEVFN_IOAPIC);
2418 }
2419 
2420 static void vtd_class_init(ObjectClass *klass, void *data)
2421 {
2422     DeviceClass *dc = DEVICE_CLASS(klass);
2423     X86IOMMUClass *x86_class = X86_IOMMU_CLASS(klass);
2424 
2425     dc->reset = vtd_reset;
2426     dc->vmsd = &vtd_vmstate;
2427     dc->props = vtd_properties;
2428     dc->hotpluggable = false;
2429     x86_class->realize = vtd_realize;
2430     x86_class->int_remap = vtd_int_remap;
2431 }
2432 
2433 static const TypeInfo vtd_info = {
2434     .name          = TYPE_INTEL_IOMMU_DEVICE,
2435     .parent        = TYPE_X86_IOMMU_DEVICE,
2436     .instance_size = sizeof(IntelIOMMUState),
2437     .class_init    = vtd_class_init,
2438 };
2439 
2440 static void vtd_register_types(void)
2441 {
2442     VTD_DPRINTF(GENERAL, "");
2443     type_register_static(&vtd_info);
2444 }
2445 
2446 type_init(vtd_register_types)
2447