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