2 * QEMU emulation of an Intel IOMMU (VT-d)
3 * (DMA Remapping device)
5 * Copyright (C) 2013 Knut Omang, Oracle <knut.omang@oracle.com>
6 * Copyright (C) 2014 Le Tan, <tamlokveer@gmail.com>
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.
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.
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/>.
22 #include "qemu/osdep.h"
23 #include "qemu/error-report.h"
24 #include "qemu/main-loop.h"
25 #include "qapi/error.h"
26 #include "hw/sysbus.h"
27 #include "intel_iommu_internal.h"
28 #include "hw/pci/pci.h"
29 #include "hw/pci/pci_bus.h"
30 #include "hw/qdev-properties.h"
31 #include "hw/i386/pc.h"
32 #include "hw/i386/apic-msidef.h"
33 #include "hw/i386/x86-iommu.h"
34 #include "hw/pci-host/q35.h"
35 #include "sysemu/kvm.h"
36 #include "sysemu/dma.h"
37 #include "sysemu/sysemu.h"
38 #include "hw/i386/apic_internal.h"
39 #include "kvm/kvm_i386.h"
40 #include "migration/vmstate.h"
43 /* context entry operations */
44 #define VTD_CE_GET_RID2PASID(ce) \
45 ((ce)->val[1] & VTD_SM_CONTEXT_ENTRY_RID2PASID_MASK)
46 #define VTD_CE_GET_PASID_DIR_TABLE(ce) \
47 ((ce)->val[0] & VTD_PASID_DIR_BASE_ADDR_MASK)
50 #define VTD_PE_GET_TYPE(pe) ((pe)->val[0] & VTD_SM_PASID_ENTRY_PGTT)
51 #define VTD_PE_GET_LEVEL(pe) (2 + (((pe)->val[0] >> 2) & VTD_SM_PASID_ENTRY_AW))
52 #define VTD_PE_GET_FPD_ERR(ret_fr, is_fpd_set, s, source_id, addr, is_write) {\
55 if (is_fpd_set && vtd_is_qualified_fault(ret_fr)) { \
56 trace_vtd_fault_disabled(); \
58 vtd_report_dmar_fault(s, source_id, addr, ret_fr, is_write); \
64 static void vtd_address_space_refresh_all(IntelIOMMUState *s);
65 static void vtd_address_space_unmap(VTDAddressSpace *as, IOMMUNotifier *n);
67 static void vtd_panic_require_caching_mode(void)
69 error_report("We need to set caching-mode=on for intel-iommu to enable "
70 "device assignment with IOMMU protection.");
74 static void vtd_define_quad(IntelIOMMUState *s, hwaddr addr, uint64_t val,
75 uint64_t wmask, uint64_t w1cmask)
77 stq_le_p(&s->csr[addr], val);
78 stq_le_p(&s->wmask[addr], wmask);
79 stq_le_p(&s->w1cmask[addr], w1cmask);
82 static void vtd_define_quad_wo(IntelIOMMUState *s, hwaddr addr, uint64_t mask)
84 stq_le_p(&s->womask[addr], mask);
87 static void vtd_define_long(IntelIOMMUState *s, hwaddr addr, uint32_t val,
88 uint32_t wmask, uint32_t w1cmask)
90 stl_le_p(&s->csr[addr], val);
91 stl_le_p(&s->wmask[addr], wmask);
92 stl_le_p(&s->w1cmask[addr], w1cmask);
95 static void vtd_define_long_wo(IntelIOMMUState *s, hwaddr addr, uint32_t mask)
97 stl_le_p(&s->womask[addr], mask);
100 /* "External" get/set operations */
101 static void vtd_set_quad(IntelIOMMUState *s, hwaddr addr, uint64_t val)
103 uint64_t oldval = ldq_le_p(&s->csr[addr]);
104 uint64_t wmask = ldq_le_p(&s->wmask[addr]);
105 uint64_t w1cmask = ldq_le_p(&s->w1cmask[addr]);
106 stq_le_p(&s->csr[addr],
107 ((oldval & ~wmask) | (val & wmask)) & ~(w1cmask & val));
110 static void vtd_set_long(IntelIOMMUState *s, hwaddr addr, uint32_t val)
112 uint32_t oldval = ldl_le_p(&s->csr[addr]);
113 uint32_t wmask = ldl_le_p(&s->wmask[addr]);
114 uint32_t w1cmask = ldl_le_p(&s->w1cmask[addr]);
115 stl_le_p(&s->csr[addr],
116 ((oldval & ~wmask) | (val & wmask)) & ~(w1cmask & val));
119 static uint64_t vtd_get_quad(IntelIOMMUState *s, hwaddr addr)
121 uint64_t val = ldq_le_p(&s->csr[addr]);
122 uint64_t womask = ldq_le_p(&s->womask[addr]);
123 return val & ~womask;
126 static uint32_t vtd_get_long(IntelIOMMUState *s, hwaddr addr)
128 uint32_t val = ldl_le_p(&s->csr[addr]);
129 uint32_t womask = ldl_le_p(&s->womask[addr]);
130 return val & ~womask;
133 /* "Internal" get/set operations */
134 static uint64_t vtd_get_quad_raw(IntelIOMMUState *s, hwaddr addr)
136 return ldq_le_p(&s->csr[addr]);
139 static uint32_t vtd_get_long_raw(IntelIOMMUState *s, hwaddr addr)
141 return ldl_le_p(&s->csr[addr]);
144 static void vtd_set_quad_raw(IntelIOMMUState *s, hwaddr addr, uint64_t val)
146 stq_le_p(&s->csr[addr], val);
149 static uint32_t vtd_set_clear_mask_long(IntelIOMMUState *s, hwaddr addr,
150 uint32_t clear, uint32_t mask)
152 uint32_t new_val = (ldl_le_p(&s->csr[addr]) & ~clear) | mask;
153 stl_le_p(&s->csr[addr], new_val);
157 static uint64_t vtd_set_clear_mask_quad(IntelIOMMUState *s, hwaddr addr,
158 uint64_t clear, uint64_t mask)
160 uint64_t new_val = (ldq_le_p(&s->csr[addr]) & ~clear) | mask;
161 stq_le_p(&s->csr[addr], new_val);
165 static inline void vtd_iommu_lock(IntelIOMMUState *s)
167 qemu_mutex_lock(&s->iommu_lock);
170 static inline void vtd_iommu_unlock(IntelIOMMUState *s)
172 qemu_mutex_unlock(&s->iommu_lock);
175 static void vtd_update_scalable_state(IntelIOMMUState *s)
177 uint64_t val = vtd_get_quad_raw(s, DMAR_RTADDR_REG);
179 if (s->scalable_mode) {
180 s->root_scalable = val & VTD_RTADDR_SMT;
184 /* Whether the address space needs to notify new mappings */
185 static inline gboolean vtd_as_has_map_notifier(VTDAddressSpace *as)
187 return as->notifier_flags & IOMMU_NOTIFIER_MAP;
190 /* GHashTable functions */
191 static gboolean vtd_uint64_equal(gconstpointer v1, gconstpointer v2)
193 return *((const uint64_t *)v1) == *((const uint64_t *)v2);
196 static guint vtd_uint64_hash(gconstpointer v)
198 return (guint)*(const uint64_t *)v;
201 static gboolean vtd_hash_remove_by_domain(gpointer key, gpointer value,
204 VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value;
205 uint16_t domain_id = *(uint16_t *)user_data;
206 return entry->domain_id == domain_id;
209 /* The shift of an addr for a certain level of paging structure */
210 static inline uint32_t vtd_slpt_level_shift(uint32_t level)
213 return VTD_PAGE_SHIFT_4K + (level - 1) * VTD_SL_LEVEL_BITS;
216 static inline uint64_t vtd_slpt_level_page_mask(uint32_t level)
218 return ~((1ULL << vtd_slpt_level_shift(level)) - 1);
221 static gboolean vtd_hash_remove_by_page(gpointer key, gpointer value,
224 VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value;
225 VTDIOTLBPageInvInfo *info = (VTDIOTLBPageInvInfo *)user_data;
226 uint64_t gfn = (info->addr >> VTD_PAGE_SHIFT_4K) & info->mask;
227 uint64_t gfn_tlb = (info->addr & entry->mask) >> VTD_PAGE_SHIFT_4K;
228 return (entry->domain_id == info->domain_id) &&
229 (((entry->gfn & info->mask) == gfn) ||
230 (entry->gfn == gfn_tlb));
233 /* Reset all the gen of VTDAddressSpace to zero and set the gen of
234 * IntelIOMMUState to 1. Must be called with IOMMU lock held.
236 static void vtd_reset_context_cache_locked(IntelIOMMUState *s)
238 VTDAddressSpace *vtd_as;
240 GHashTableIter bus_it;
243 trace_vtd_context_cache_reset();
245 g_hash_table_iter_init(&bus_it, s->vtd_as_by_busptr);
247 while (g_hash_table_iter_next (&bus_it, NULL, (void**)&vtd_bus)) {
248 for (devfn_it = 0; devfn_it < PCI_DEVFN_MAX; ++devfn_it) {
249 vtd_as = vtd_bus->dev_as[devfn_it];
253 vtd_as->context_cache_entry.context_cache_gen = 0;
256 s->context_cache_gen = 1;
259 /* Must be called with IOMMU lock held. */
260 static void vtd_reset_iotlb_locked(IntelIOMMUState *s)
263 g_hash_table_remove_all(s->iotlb);
266 static void vtd_reset_iotlb(IntelIOMMUState *s)
269 vtd_reset_iotlb_locked(s);
273 static void vtd_reset_caches(IntelIOMMUState *s)
276 vtd_reset_iotlb_locked(s);
277 vtd_reset_context_cache_locked(s);
281 static uint64_t vtd_get_iotlb_key(uint64_t gfn, uint16_t source_id,
284 return gfn | ((uint64_t)(source_id) << VTD_IOTLB_SID_SHIFT) |
285 ((uint64_t)(level) << VTD_IOTLB_LVL_SHIFT);
288 static uint64_t vtd_get_iotlb_gfn(hwaddr addr, uint32_t level)
290 return (addr & vtd_slpt_level_page_mask(level)) >> VTD_PAGE_SHIFT_4K;
293 /* Must be called with IOMMU lock held */
294 static VTDIOTLBEntry *vtd_lookup_iotlb(IntelIOMMUState *s, uint16_t source_id,
297 VTDIOTLBEntry *entry;
301 for (level = VTD_SL_PT_LEVEL; level < VTD_SL_PML4_LEVEL; level++) {
302 key = vtd_get_iotlb_key(vtd_get_iotlb_gfn(addr, level),
304 entry = g_hash_table_lookup(s->iotlb, &key);
314 /* Must be with IOMMU lock held */
315 static void vtd_update_iotlb(IntelIOMMUState *s, uint16_t source_id,
316 uint16_t domain_id, hwaddr addr, uint64_t slpte,
317 uint8_t access_flags, uint32_t level)
319 VTDIOTLBEntry *entry = g_malloc(sizeof(*entry));
320 uint64_t *key = g_malloc(sizeof(*key));
321 uint64_t gfn = vtd_get_iotlb_gfn(addr, level);
323 trace_vtd_iotlb_page_update(source_id, addr, slpte, domain_id);
324 if (g_hash_table_size(s->iotlb) >= VTD_IOTLB_MAX_SIZE) {
325 trace_vtd_iotlb_reset("iotlb exceeds size limit");
326 vtd_reset_iotlb_locked(s);
330 entry->domain_id = domain_id;
331 entry->slpte = slpte;
332 entry->access_flags = access_flags;
333 entry->mask = vtd_slpt_level_page_mask(level);
334 *key = vtd_get_iotlb_key(gfn, source_id, level);
335 g_hash_table_replace(s->iotlb, key, entry);
338 /* Given the reg addr of both the message data and address, generate an
341 static void vtd_generate_interrupt(IntelIOMMUState *s, hwaddr mesg_addr_reg,
342 hwaddr mesg_data_reg)
346 assert(mesg_data_reg < DMAR_REG_SIZE);
347 assert(mesg_addr_reg < DMAR_REG_SIZE);
349 msi.address = vtd_get_long_raw(s, mesg_addr_reg);
350 msi.data = vtd_get_long_raw(s, mesg_data_reg);
352 trace_vtd_irq_generate(msi.address, msi.data);
354 apic_get_class()->send_msi(&msi);
357 /* Generate a fault event to software via MSI if conditions are met.
358 * Notice that the value of FSTS_REG being passed to it should be the one
361 static void vtd_generate_fault_event(IntelIOMMUState *s, uint32_t pre_fsts)
363 if (pre_fsts & VTD_FSTS_PPF || pre_fsts & VTD_FSTS_PFO ||
364 pre_fsts & VTD_FSTS_IQE) {
365 error_report_once("There are previous interrupt conditions "
366 "to be serviced by software, fault event "
370 vtd_set_clear_mask_long(s, DMAR_FECTL_REG, 0, VTD_FECTL_IP);
371 if (vtd_get_long_raw(s, DMAR_FECTL_REG) & VTD_FECTL_IM) {
372 error_report_once("Interrupt Mask set, irq is not generated");
374 vtd_generate_interrupt(s, DMAR_FEADDR_REG, DMAR_FEDATA_REG);
375 vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
379 /* Check if the Fault (F) field of the Fault Recording Register referenced by
382 static bool vtd_is_frcd_set(IntelIOMMUState *s, uint16_t index)
384 /* Each reg is 128-bit */
385 hwaddr addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
386 addr += 8; /* Access the high 64-bit half */
388 assert(index < DMAR_FRCD_REG_NR);
390 return vtd_get_quad_raw(s, addr) & VTD_FRCD_F;
393 /* Update the PPF field of Fault Status Register.
394 * Should be called whenever change the F field of any fault recording
397 static void vtd_update_fsts_ppf(IntelIOMMUState *s)
400 uint32_t ppf_mask = 0;
402 for (i = 0; i < DMAR_FRCD_REG_NR; i++) {
403 if (vtd_is_frcd_set(s, i)) {
404 ppf_mask = VTD_FSTS_PPF;
408 vtd_set_clear_mask_long(s, DMAR_FSTS_REG, VTD_FSTS_PPF, ppf_mask);
409 trace_vtd_fsts_ppf(!!ppf_mask);
412 static void vtd_set_frcd_and_update_ppf(IntelIOMMUState *s, uint16_t index)
414 /* Each reg is 128-bit */
415 hwaddr addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
416 addr += 8; /* Access the high 64-bit half */
418 assert(index < DMAR_FRCD_REG_NR);
420 vtd_set_clear_mask_quad(s, addr, 0, VTD_FRCD_F);
421 vtd_update_fsts_ppf(s);
424 /* Must not update F field now, should be done later */
425 static void vtd_record_frcd(IntelIOMMUState *s, uint16_t index,
426 uint16_t source_id, hwaddr addr,
427 VTDFaultReason fault, bool is_write)
430 hwaddr frcd_reg_addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
432 assert(index < DMAR_FRCD_REG_NR);
434 lo = VTD_FRCD_FI(addr);
435 hi = VTD_FRCD_SID(source_id) | VTD_FRCD_FR(fault);
439 vtd_set_quad_raw(s, frcd_reg_addr, lo);
440 vtd_set_quad_raw(s, frcd_reg_addr + 8, hi);
442 trace_vtd_frr_new(index, hi, lo);
445 /* Try to collapse multiple pending faults from the same requester */
446 static bool vtd_try_collapse_fault(IntelIOMMUState *s, uint16_t source_id)
450 hwaddr addr = DMAR_FRCD_REG_OFFSET + 8; /* The high 64-bit half */
452 for (i = 0; i < DMAR_FRCD_REG_NR; i++) {
453 frcd_reg = vtd_get_quad_raw(s, addr);
454 if ((frcd_reg & VTD_FRCD_F) &&
455 ((frcd_reg & VTD_FRCD_SID_MASK) == source_id)) {
458 addr += 16; /* 128-bit for each */
463 /* Log and report an DMAR (address translation) fault to software */
464 static void vtd_report_dmar_fault(IntelIOMMUState *s, uint16_t source_id,
465 hwaddr addr, VTDFaultReason fault,
468 uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
470 assert(fault < VTD_FR_MAX);
472 trace_vtd_dmar_fault(source_id, fault, addr, is_write);
474 if (fsts_reg & VTD_FSTS_PFO) {
475 error_report_once("New fault is not recorded due to "
476 "Primary Fault Overflow");
480 if (vtd_try_collapse_fault(s, source_id)) {
481 error_report_once("New fault is not recorded due to "
482 "compression of faults");
486 if (vtd_is_frcd_set(s, s->next_frcd_reg)) {
487 error_report_once("Next Fault Recording Reg is used, "
488 "new fault is not recorded, set PFO field");
489 vtd_set_clear_mask_long(s, DMAR_FSTS_REG, 0, VTD_FSTS_PFO);
493 vtd_record_frcd(s, s->next_frcd_reg, source_id, addr, fault, is_write);
495 if (fsts_reg & VTD_FSTS_PPF) {
496 error_report_once("There are pending faults already, "
497 "fault event is not generated");
498 vtd_set_frcd_and_update_ppf(s, s->next_frcd_reg);
500 if (s->next_frcd_reg == DMAR_FRCD_REG_NR) {
501 s->next_frcd_reg = 0;
504 vtd_set_clear_mask_long(s, DMAR_FSTS_REG, VTD_FSTS_FRI_MASK,
505 VTD_FSTS_FRI(s->next_frcd_reg));
506 vtd_set_frcd_and_update_ppf(s, s->next_frcd_reg); /* Will set PPF */
508 if (s->next_frcd_reg == DMAR_FRCD_REG_NR) {
509 s->next_frcd_reg = 0;
511 /* This case actually cause the PPF to be Set.
512 * So generate fault event (interrupt).
514 vtd_generate_fault_event(s, fsts_reg);
518 /* Handle Invalidation Queue Errors of queued invalidation interface error
521 static void vtd_handle_inv_queue_error(IntelIOMMUState *s)
523 uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
525 vtd_set_clear_mask_long(s, DMAR_FSTS_REG, 0, VTD_FSTS_IQE);
526 vtd_generate_fault_event(s, fsts_reg);
529 /* Set the IWC field and try to generate an invalidation completion interrupt */
530 static void vtd_generate_completion_event(IntelIOMMUState *s)
532 if (vtd_get_long_raw(s, DMAR_ICS_REG) & VTD_ICS_IWC) {
533 trace_vtd_inv_desc_wait_irq("One pending, skip current");
536 vtd_set_clear_mask_long(s, DMAR_ICS_REG, 0, VTD_ICS_IWC);
537 vtd_set_clear_mask_long(s, DMAR_IECTL_REG, 0, VTD_IECTL_IP);
538 if (vtd_get_long_raw(s, DMAR_IECTL_REG) & VTD_IECTL_IM) {
539 trace_vtd_inv_desc_wait_irq("IM in IECTL_REG is set, "
540 "new event not generated");
543 /* Generate the interrupt event */
544 trace_vtd_inv_desc_wait_irq("Generating complete event");
545 vtd_generate_interrupt(s, DMAR_IEADDR_REG, DMAR_IEDATA_REG);
546 vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
550 static inline bool vtd_root_entry_present(IntelIOMMUState *s,
554 if (s->root_scalable && devfn > UINT8_MAX / 2) {
555 return re->hi & VTD_ROOT_ENTRY_P;
558 return re->lo & VTD_ROOT_ENTRY_P;
561 static int vtd_get_root_entry(IntelIOMMUState *s, uint8_t index,
566 addr = s->root + index * sizeof(*re);
567 if (dma_memory_read(&address_space_memory, addr,
568 re, sizeof(*re), MEMTXATTRS_UNSPECIFIED)) {
570 return -VTD_FR_ROOT_TABLE_INV;
572 re->lo = le64_to_cpu(re->lo);
573 re->hi = le64_to_cpu(re->hi);
577 static inline bool vtd_ce_present(VTDContextEntry *context)
579 return context->lo & VTD_CONTEXT_ENTRY_P;
582 static int vtd_get_context_entry_from_root(IntelIOMMUState *s,
587 dma_addr_t addr, ce_size;
589 /* we have checked that root entry is present */
590 ce_size = s->root_scalable ? VTD_CTX_ENTRY_SCALABLE_SIZE :
591 VTD_CTX_ENTRY_LEGACY_SIZE;
593 if (s->root_scalable && index > UINT8_MAX / 2) {
594 index = index & (~VTD_DEVFN_CHECK_MASK);
595 addr = re->hi & VTD_ROOT_ENTRY_CTP;
597 addr = re->lo & VTD_ROOT_ENTRY_CTP;
600 addr = addr + index * ce_size;
601 if (dma_memory_read(&address_space_memory, addr,
602 ce, ce_size, MEMTXATTRS_UNSPECIFIED)) {
603 return -VTD_FR_CONTEXT_TABLE_INV;
606 ce->lo = le64_to_cpu(ce->lo);
607 ce->hi = le64_to_cpu(ce->hi);
608 if (ce_size == VTD_CTX_ENTRY_SCALABLE_SIZE) {
609 ce->val[2] = le64_to_cpu(ce->val[2]);
610 ce->val[3] = le64_to_cpu(ce->val[3]);
615 static inline dma_addr_t vtd_ce_get_slpt_base(VTDContextEntry *ce)
617 return ce->lo & VTD_CONTEXT_ENTRY_SLPTPTR;
620 static inline uint64_t vtd_get_slpte_addr(uint64_t slpte, uint8_t aw)
622 return slpte & VTD_SL_PT_BASE_ADDR_MASK(aw);
625 /* Whether the pte indicates the address of the page frame */
626 static inline bool vtd_is_last_slpte(uint64_t slpte, uint32_t level)
628 return level == VTD_SL_PT_LEVEL || (slpte & VTD_SL_PT_PAGE_SIZE_MASK);
631 /* Get the content of a spte located in @base_addr[@index] */
632 static uint64_t vtd_get_slpte(dma_addr_t base_addr, uint32_t index)
636 assert(index < VTD_SL_PT_ENTRY_NR);
638 if (dma_memory_read(&address_space_memory,
639 base_addr + index * sizeof(slpte),
640 &slpte, sizeof(slpte), MEMTXATTRS_UNSPECIFIED)) {
641 slpte = (uint64_t)-1;
644 slpte = le64_to_cpu(slpte);
648 /* Given an iova and the level of paging structure, return the offset
651 static inline uint32_t vtd_iova_level_offset(uint64_t iova, uint32_t level)
653 return (iova >> vtd_slpt_level_shift(level)) &
654 ((1ULL << VTD_SL_LEVEL_BITS) - 1);
657 /* Check Capability Register to see if the @level of page-table is supported */
658 static inline bool vtd_is_level_supported(IntelIOMMUState *s, uint32_t level)
660 return VTD_CAP_SAGAW_MASK & s->cap &
661 (1ULL << (level - 2 + VTD_CAP_SAGAW_SHIFT));
664 /* Return true if check passed, otherwise false */
665 static inline bool vtd_pe_type_check(X86IOMMUState *x86_iommu,
668 switch (VTD_PE_GET_TYPE(pe)) {
669 case VTD_SM_PASID_ENTRY_FLT:
670 case VTD_SM_PASID_ENTRY_SLT:
671 case VTD_SM_PASID_ENTRY_NESTED:
673 case VTD_SM_PASID_ENTRY_PT:
674 if (!x86_iommu->pt_supported) {
685 static inline bool vtd_pdire_present(VTDPASIDDirEntry *pdire)
687 return pdire->val & 1;
691 * Caller of this function should check present bit if wants
692 * to use pdir entry for further usage except for fpd bit check.
694 static int vtd_get_pdire_from_pdir_table(dma_addr_t pasid_dir_base,
696 VTDPASIDDirEntry *pdire)
699 dma_addr_t addr, entry_size;
701 index = VTD_PASID_DIR_INDEX(pasid);
702 entry_size = VTD_PASID_DIR_ENTRY_SIZE;
703 addr = pasid_dir_base + index * entry_size;
704 if (dma_memory_read(&address_space_memory, addr,
705 pdire, entry_size, MEMTXATTRS_UNSPECIFIED)) {
706 return -VTD_FR_PASID_TABLE_INV;
712 static inline bool vtd_pe_present(VTDPASIDEntry *pe)
714 return pe->val[0] & VTD_PASID_ENTRY_P;
717 static int vtd_get_pe_in_pasid_leaf_table(IntelIOMMUState *s,
723 dma_addr_t entry_size;
724 X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
726 index = VTD_PASID_TABLE_INDEX(pasid);
727 entry_size = VTD_PASID_ENTRY_SIZE;
728 addr = addr + index * entry_size;
729 if (dma_memory_read(&address_space_memory, addr,
730 pe, entry_size, MEMTXATTRS_UNSPECIFIED)) {
731 return -VTD_FR_PASID_TABLE_INV;
734 /* Do translation type check */
735 if (!vtd_pe_type_check(x86_iommu, pe)) {
736 return -VTD_FR_PASID_TABLE_INV;
739 if (!vtd_is_level_supported(s, VTD_PE_GET_LEVEL(pe))) {
740 return -VTD_FR_PASID_TABLE_INV;
747 * Caller of this function should check present bit if wants
748 * to use pasid entry for further usage except for fpd bit check.
750 static int vtd_get_pe_from_pdire(IntelIOMMUState *s,
752 VTDPASIDDirEntry *pdire,
755 dma_addr_t addr = pdire->val & VTD_PASID_TABLE_BASE_ADDR_MASK;
757 return vtd_get_pe_in_pasid_leaf_table(s, pasid, addr, pe);
761 * This function gets a pasid entry from a specified pasid
762 * table (includes dir and leaf table) with a specified pasid.
763 * Sanity check should be done to ensure return a present
764 * pasid entry to caller.
766 static int vtd_get_pe_from_pasid_table(IntelIOMMUState *s,
767 dma_addr_t pasid_dir_base,
772 VTDPASIDDirEntry pdire;
774 ret = vtd_get_pdire_from_pdir_table(pasid_dir_base,
780 if (!vtd_pdire_present(&pdire)) {
781 return -VTD_FR_PASID_TABLE_INV;
784 ret = vtd_get_pe_from_pdire(s, pasid, &pdire, pe);
789 if (!vtd_pe_present(pe)) {
790 return -VTD_FR_PASID_TABLE_INV;
796 static int vtd_ce_get_rid2pasid_entry(IntelIOMMUState *s,
801 dma_addr_t pasid_dir_base;
804 pasid = VTD_CE_GET_RID2PASID(ce);
805 pasid_dir_base = VTD_CE_GET_PASID_DIR_TABLE(ce);
806 ret = vtd_get_pe_from_pasid_table(s, pasid_dir_base, pasid, pe);
811 static int vtd_ce_get_pasid_fpd(IntelIOMMUState *s,
817 dma_addr_t pasid_dir_base;
818 VTDPASIDDirEntry pdire;
821 pasid = VTD_CE_GET_RID2PASID(ce);
822 pasid_dir_base = VTD_CE_GET_PASID_DIR_TABLE(ce);
825 * No present bit check since fpd is meaningful even
826 * if the present bit is clear.
828 ret = vtd_get_pdire_from_pdir_table(pasid_dir_base, pasid, &pdire);
833 if (pdire.val & VTD_PASID_DIR_FPD) {
838 if (!vtd_pdire_present(&pdire)) {
839 return -VTD_FR_PASID_TABLE_INV;
843 * No present bit check since fpd is meaningful even
844 * if the present bit is clear.
846 ret = vtd_get_pe_from_pdire(s, pasid, &pdire, &pe);
851 if (pe.val[0] & VTD_PASID_ENTRY_FPD) {
858 /* Get the page-table level that hardware should use for the second-level
859 * page-table walk from the Address Width field of context-entry.
861 static inline uint32_t vtd_ce_get_level(VTDContextEntry *ce)
863 return 2 + (ce->hi & VTD_CONTEXT_ENTRY_AW);
866 static uint32_t vtd_get_iova_level(IntelIOMMUState *s,
871 if (s->root_scalable) {
872 vtd_ce_get_rid2pasid_entry(s, ce, &pe);
873 return VTD_PE_GET_LEVEL(&pe);
876 return vtd_ce_get_level(ce);
879 static inline uint32_t vtd_ce_get_agaw(VTDContextEntry *ce)
881 return 30 + (ce->hi & VTD_CONTEXT_ENTRY_AW) * 9;
884 static uint32_t vtd_get_iova_agaw(IntelIOMMUState *s,
889 if (s->root_scalable) {
890 vtd_ce_get_rid2pasid_entry(s, ce, &pe);
891 return 30 + ((pe.val[0] >> 2) & VTD_SM_PASID_ENTRY_AW) * 9;
894 return vtd_ce_get_agaw(ce);
897 static inline uint32_t vtd_ce_get_type(VTDContextEntry *ce)
899 return ce->lo & VTD_CONTEXT_ENTRY_TT;
902 /* Only for Legacy Mode. Return true if check passed, otherwise false */
903 static inline bool vtd_ce_type_check(X86IOMMUState *x86_iommu,
906 switch (vtd_ce_get_type(ce)) {
907 case VTD_CONTEXT_TT_MULTI_LEVEL:
908 /* Always supported */
910 case VTD_CONTEXT_TT_DEV_IOTLB:
911 if (!x86_iommu->dt_supported) {
912 error_report_once("%s: DT specified but not supported", __func__);
916 case VTD_CONTEXT_TT_PASS_THROUGH:
917 if (!x86_iommu->pt_supported) {
918 error_report_once("%s: PT specified but not supported", __func__);
924 error_report_once("%s: unknown ce type: %"PRIu32, __func__,
925 vtd_ce_get_type(ce));
931 static inline uint64_t vtd_iova_limit(IntelIOMMUState *s,
932 VTDContextEntry *ce, uint8_t aw)
934 uint32_t ce_agaw = vtd_get_iova_agaw(s, ce);
935 return 1ULL << MIN(ce_agaw, aw);
938 /* Return true if IOVA passes range check, otherwise false. */
939 static inline bool vtd_iova_range_check(IntelIOMMUState *s,
940 uint64_t iova, VTDContextEntry *ce,
944 * Check if @iova is above 2^X-1, where X is the minimum of MGAW
945 * in CAP_REG and AW in context-entry.
947 return !(iova & ~(vtd_iova_limit(s, ce, aw) - 1));
950 static dma_addr_t vtd_get_iova_pgtbl_base(IntelIOMMUState *s,
955 if (s->root_scalable) {
956 vtd_ce_get_rid2pasid_entry(s, ce, &pe);
957 return pe.val[0] & VTD_SM_PASID_ENTRY_SLPTPTR;
960 return vtd_ce_get_slpt_base(ce);
964 * Rsvd field masks for spte:
965 * vtd_spte_rsvd 4k pages
966 * vtd_spte_rsvd_large large pages
968 static uint64_t vtd_spte_rsvd[5];
969 static uint64_t vtd_spte_rsvd_large[5];
971 static bool vtd_slpte_nonzero_rsvd(uint64_t slpte, uint32_t level)
973 uint64_t rsvd_mask = vtd_spte_rsvd[level];
975 if ((level == VTD_SL_PD_LEVEL || level == VTD_SL_PDP_LEVEL) &&
976 (slpte & VTD_SL_PT_PAGE_SIZE_MASK)) {
978 rsvd_mask = vtd_spte_rsvd_large[level];
981 return slpte & rsvd_mask;
984 /* Find the VTD address space associated with a given bus number */
985 static VTDBus *vtd_find_as_from_bus_num(IntelIOMMUState *s, uint8_t bus_num)
987 VTDBus *vtd_bus = s->vtd_as_by_bus_num[bus_num];
995 * Iterate over the registered buses to find the one which
996 * currently holds this bus number and update the bus_num
999 g_hash_table_iter_init(&iter, s->vtd_as_by_busptr);
1000 while (g_hash_table_iter_next(&iter, NULL, (void **)&vtd_bus)) {
1001 if (pci_bus_num(vtd_bus->bus) == bus_num) {
1002 s->vtd_as_by_bus_num[bus_num] = vtd_bus;
1010 /* Given the @iova, get relevant @slptep. @slpte_level will be the last level
1011 * of the translation, can be used for deciding the size of large page.
1013 static int vtd_iova_to_slpte(IntelIOMMUState *s, VTDContextEntry *ce,
1014 uint64_t iova, bool is_write,
1015 uint64_t *slptep, uint32_t *slpte_level,
1016 bool *reads, bool *writes, uint8_t aw_bits)
1018 dma_addr_t addr = vtd_get_iova_pgtbl_base(s, ce);
1019 uint32_t level = vtd_get_iova_level(s, ce);
1022 uint64_t access_right_check;
1023 uint64_t xlat, size;
1025 if (!vtd_iova_range_check(s, iova, ce, aw_bits)) {
1026 error_report_once("%s: detected IOVA overflow (iova=0x%" PRIx64 ")",
1028 return -VTD_FR_ADDR_BEYOND_MGAW;
1031 /* FIXME: what is the Atomics request here? */
1032 access_right_check = is_write ? VTD_SL_W : VTD_SL_R;
1035 offset = vtd_iova_level_offset(iova, level);
1036 slpte = vtd_get_slpte(addr, offset);
1038 if (slpte == (uint64_t)-1) {
1039 error_report_once("%s: detected read error on DMAR slpte "
1040 "(iova=0x%" PRIx64 ")", __func__, iova);
1041 if (level == vtd_get_iova_level(s, ce)) {
1042 /* Invalid programming of context-entry */
1043 return -VTD_FR_CONTEXT_ENTRY_INV;
1045 return -VTD_FR_PAGING_ENTRY_INV;
1048 *reads = (*reads) && (slpte & VTD_SL_R);
1049 *writes = (*writes) && (slpte & VTD_SL_W);
1050 if (!(slpte & access_right_check)) {
1051 error_report_once("%s: detected slpte permission error "
1052 "(iova=0x%" PRIx64 ", level=0x%" PRIx32 ", "
1053 "slpte=0x%" PRIx64 ", write=%d)", __func__,
1054 iova, level, slpte, is_write);
1055 return is_write ? -VTD_FR_WRITE : -VTD_FR_READ;
1057 if (vtd_slpte_nonzero_rsvd(slpte, level)) {
1058 error_report_once("%s: detected splte reserve non-zero "
1059 "iova=0x%" PRIx64 ", level=0x%" PRIx32
1060 "slpte=0x%" PRIx64 ")", __func__, iova,
1062 return -VTD_FR_PAGING_ENTRY_RSVD;
1065 if (vtd_is_last_slpte(slpte, level)) {
1067 *slpte_level = level;
1070 addr = vtd_get_slpte_addr(slpte, aw_bits);
1074 xlat = vtd_get_slpte_addr(*slptep, aw_bits);
1075 size = ~vtd_slpt_level_page_mask(level) + 1;
1078 * From VT-d spec 3.14: Untranslated requests and translation
1079 * requests that result in an address in the interrupt range will be
1080 * blocked with condition code LGN.4 or SGN.8.
1082 if ((xlat > VTD_INTERRUPT_ADDR_LAST ||
1083 xlat + size - 1 < VTD_INTERRUPT_ADDR_FIRST)) {
1086 error_report_once("%s: xlat address is in interrupt range "
1087 "(iova=0x%" PRIx64 ", level=0x%" PRIx32 ", "
1088 "slpte=0x%" PRIx64 ", write=%d, "
1089 "xlat=0x%" PRIx64 ", size=0x%" PRIx64 ")",
1090 __func__, iova, level, slpte, is_write,
1092 return s->scalable_mode ? -VTD_FR_SM_INTERRUPT_ADDR :
1093 -VTD_FR_INTERRUPT_ADDR;
1097 typedef int (*vtd_page_walk_hook)(IOMMUTLBEvent *event, void *private);
1100 * Constant information used during page walking
1102 * @hook_fn: hook func to be called when detected page
1103 * @private: private data to be passed into hook func
1104 * @notify_unmap: whether we should notify invalid entries
1105 * @as: VT-d address space of the device
1106 * @aw: maximum address width
1107 * @domain: domain ID of the page walk
1110 VTDAddressSpace *as;
1111 vtd_page_walk_hook hook_fn;
1116 } vtd_page_walk_info;
1118 static int vtd_page_walk_one(IOMMUTLBEvent *event, vtd_page_walk_info *info)
1120 VTDAddressSpace *as = info->as;
1121 vtd_page_walk_hook hook_fn = info->hook_fn;
1122 void *private = info->private;
1123 IOMMUTLBEntry *entry = &event->entry;
1125 .iova = entry->iova,
1126 .size = entry->addr_mask,
1127 .translated_addr = entry->translated_addr,
1128 .perm = entry->perm,
1130 const DMAMap *mapped = iova_tree_find(as->iova_tree, &target);
1132 if (event->type == IOMMU_NOTIFIER_UNMAP && !info->notify_unmap) {
1133 trace_vtd_page_walk_one_skip_unmap(entry->iova, entry->addr_mask);
1139 /* Update local IOVA mapped ranges */
1140 if (event->type == IOMMU_NOTIFIER_MAP) {
1142 /* If it's exactly the same translation, skip */
1143 if (!memcmp(mapped, &target, sizeof(target))) {
1144 trace_vtd_page_walk_one_skip_map(entry->iova, entry->addr_mask,
1145 entry->translated_addr);
1149 * Translation changed. Normally this should not
1150 * happen, but it can happen when with buggy guest
1151 * OSes. Note that there will be a small window that
1152 * we don't have map at all. But that's the best
1153 * effort we can do. The ideal way to emulate this is
1154 * atomically modify the PTE to follow what has
1155 * changed, but we can't. One example is that vfio
1156 * driver only has VFIO_IOMMU_[UN]MAP_DMA but no
1157 * interface to modify a mapping (meanwhile it seems
1158 * meaningless to even provide one). Anyway, let's
1159 * mark this as a TODO in case one day we'll have
1160 * a better solution.
1162 IOMMUAccessFlags cache_perm = entry->perm;
1165 /* Emulate an UNMAP */
1166 event->type = IOMMU_NOTIFIER_UNMAP;
1167 entry->perm = IOMMU_NONE;
1168 trace_vtd_page_walk_one(info->domain_id,
1170 entry->translated_addr,
1173 ret = hook_fn(event, private);
1177 /* Drop any existing mapping */
1178 iova_tree_remove(as->iova_tree, &target);
1179 /* Recover the correct type */
1180 event->type = IOMMU_NOTIFIER_MAP;
1181 entry->perm = cache_perm;
1184 iova_tree_insert(as->iova_tree, &target);
1187 /* Skip since we didn't map this range at all */
1188 trace_vtd_page_walk_one_skip_unmap(entry->iova, entry->addr_mask);
1191 iova_tree_remove(as->iova_tree, &target);
1194 trace_vtd_page_walk_one(info->domain_id, entry->iova,
1195 entry->translated_addr, entry->addr_mask,
1197 return hook_fn(event, private);
1201 * vtd_page_walk_level - walk over specific level for IOVA range
1203 * @addr: base GPA addr to start the walk
1204 * @start: IOVA range start address
1205 * @end: IOVA range end address (start <= addr < end)
1206 * @read: whether parent level has read permission
1207 * @write: whether parent level has write permission
1208 * @info: constant information for the page walk
1210 static int vtd_page_walk_level(dma_addr_t addr, uint64_t start,
1211 uint64_t end, uint32_t level, bool read,
1212 bool write, vtd_page_walk_info *info)
1214 bool read_cur, write_cur, entry_valid;
1217 uint64_t subpage_size, subpage_mask;
1218 IOMMUTLBEvent event;
1219 uint64_t iova = start;
1223 trace_vtd_page_walk_level(addr, level, start, end);
1225 subpage_size = 1ULL << vtd_slpt_level_shift(level);
1226 subpage_mask = vtd_slpt_level_page_mask(level);
1228 while (iova < end) {
1229 iova_next = (iova & subpage_mask) + subpage_size;
1231 offset = vtd_iova_level_offset(iova, level);
1232 slpte = vtd_get_slpte(addr, offset);
1234 if (slpte == (uint64_t)-1) {
1235 trace_vtd_page_walk_skip_read(iova, iova_next);
1239 if (vtd_slpte_nonzero_rsvd(slpte, level)) {
1240 trace_vtd_page_walk_skip_reserve(iova, iova_next);
1244 /* Permissions are stacked with parents' */
1245 read_cur = read && (slpte & VTD_SL_R);
1246 write_cur = write && (slpte & VTD_SL_W);
1249 * As long as we have either read/write permission, this is a
1250 * valid entry. The rule works for both page entries and page
1253 entry_valid = read_cur | write_cur;
1255 if (!vtd_is_last_slpte(slpte, level) && entry_valid) {
1257 * This is a valid PDE (or even bigger than PDE). We need
1258 * to walk one further level.
1260 ret = vtd_page_walk_level(vtd_get_slpte_addr(slpte, info->aw),
1261 iova, MIN(iova_next, end), level - 1,
1262 read_cur, write_cur, info);
1265 * This means we are either:
1267 * (1) the real page entry (either 4K page, or huge page)
1268 * (2) the whole range is invalid
1270 * In either case, we send an IOTLB notification down.
1272 event.entry.target_as = &address_space_memory;
1273 event.entry.iova = iova & subpage_mask;
1274 event.entry.perm = IOMMU_ACCESS_FLAG(read_cur, write_cur);
1275 event.entry.addr_mask = ~subpage_mask;
1276 /* NOTE: this is only meaningful if entry_valid == true */
1277 event.entry.translated_addr = vtd_get_slpte_addr(slpte, info->aw);
1278 event.type = event.entry.perm ? IOMMU_NOTIFIER_MAP :
1279 IOMMU_NOTIFIER_UNMAP;
1280 ret = vtd_page_walk_one(&event, info);
1295 * vtd_page_walk - walk specific IOVA range, and call the hook
1297 * @s: intel iommu state
1298 * @ce: context entry to walk upon
1299 * @start: IOVA address to start the walk
1300 * @end: IOVA range end address (start <= addr < end)
1301 * @info: page walking information struct
1303 static int vtd_page_walk(IntelIOMMUState *s, VTDContextEntry *ce,
1304 uint64_t start, uint64_t end,
1305 vtd_page_walk_info *info)
1307 dma_addr_t addr = vtd_get_iova_pgtbl_base(s, ce);
1308 uint32_t level = vtd_get_iova_level(s, ce);
1310 if (!vtd_iova_range_check(s, start, ce, info->aw)) {
1311 return -VTD_FR_ADDR_BEYOND_MGAW;
1314 if (!vtd_iova_range_check(s, end, ce, info->aw)) {
1315 /* Fix end so that it reaches the maximum */
1316 end = vtd_iova_limit(s, ce, info->aw);
1319 return vtd_page_walk_level(addr, start, end, level, true, true, info);
1322 static int vtd_root_entry_rsvd_bits_check(IntelIOMMUState *s,
1325 /* Legacy Mode reserved bits check */
1326 if (!s->root_scalable &&
1327 (re->hi || (re->lo & VTD_ROOT_ENTRY_RSVD(s->aw_bits))))
1330 /* Scalable Mode reserved bits check */
1331 if (s->root_scalable &&
1332 ((re->lo & VTD_ROOT_ENTRY_RSVD(s->aw_bits)) ||
1333 (re->hi & VTD_ROOT_ENTRY_RSVD(s->aw_bits))))
1339 error_report_once("%s: invalid root entry: hi=0x%"PRIx64
1341 __func__, re->hi, re->lo);
1342 return -VTD_FR_ROOT_ENTRY_RSVD;
1345 static inline int vtd_context_entry_rsvd_bits_check(IntelIOMMUState *s,
1346 VTDContextEntry *ce)
1348 if (!s->root_scalable &&
1349 (ce->hi & VTD_CONTEXT_ENTRY_RSVD_HI ||
1350 ce->lo & VTD_CONTEXT_ENTRY_RSVD_LO(s->aw_bits))) {
1351 error_report_once("%s: invalid context entry: hi=%"PRIx64
1352 ", lo=%"PRIx64" (reserved nonzero)",
1353 __func__, ce->hi, ce->lo);
1354 return -VTD_FR_CONTEXT_ENTRY_RSVD;
1357 if (s->root_scalable &&
1358 (ce->val[0] & VTD_SM_CONTEXT_ENTRY_RSVD_VAL0(s->aw_bits) ||
1359 ce->val[1] & VTD_SM_CONTEXT_ENTRY_RSVD_VAL1 ||
1362 error_report_once("%s: invalid context entry: val[3]=%"PRIx64
1365 ", val[0]=%"PRIx64" (reserved nonzero)",
1366 __func__, ce->val[3], ce->val[2],
1367 ce->val[1], ce->val[0]);
1368 return -VTD_FR_CONTEXT_ENTRY_RSVD;
1374 static int vtd_ce_rid2pasid_check(IntelIOMMUState *s,
1375 VTDContextEntry *ce)
1380 * Make sure in Scalable Mode, a present context entry
1381 * has valid rid2pasid setting, which includes valid
1382 * rid2pasid field and corresponding pasid entry setting
1384 return vtd_ce_get_rid2pasid_entry(s, ce, &pe);
1387 /* Map a device to its corresponding domain (context-entry) */
1388 static int vtd_dev_to_context_entry(IntelIOMMUState *s, uint8_t bus_num,
1389 uint8_t devfn, VTDContextEntry *ce)
1393 X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
1395 ret_fr = vtd_get_root_entry(s, bus_num, &re);
1400 if (!vtd_root_entry_present(s, &re, devfn)) {
1401 /* Not error - it's okay we don't have root entry. */
1402 trace_vtd_re_not_present(bus_num);
1403 return -VTD_FR_ROOT_ENTRY_P;
1406 ret_fr = vtd_root_entry_rsvd_bits_check(s, &re);
1411 ret_fr = vtd_get_context_entry_from_root(s, &re, devfn, ce);
1416 if (!vtd_ce_present(ce)) {
1417 /* Not error - it's okay we don't have context entry. */
1418 trace_vtd_ce_not_present(bus_num, devfn);
1419 return -VTD_FR_CONTEXT_ENTRY_P;
1422 ret_fr = vtd_context_entry_rsvd_bits_check(s, ce);
1427 /* Check if the programming of context-entry is valid */
1428 if (!s->root_scalable &&
1429 !vtd_is_level_supported(s, vtd_ce_get_level(ce))) {
1430 error_report_once("%s: invalid context entry: hi=%"PRIx64
1431 ", lo=%"PRIx64" (level %d not supported)",
1432 __func__, ce->hi, ce->lo,
1433 vtd_ce_get_level(ce));
1434 return -VTD_FR_CONTEXT_ENTRY_INV;
1437 if (!s->root_scalable) {
1438 /* Do translation type check */
1439 if (!vtd_ce_type_check(x86_iommu, ce)) {
1440 /* Errors dumped in vtd_ce_type_check() */
1441 return -VTD_FR_CONTEXT_ENTRY_INV;
1445 * Check if the programming of context-entry.rid2pasid
1446 * and corresponding pasid setting is valid, and thus
1447 * avoids to check pasid entry fetching result in future
1448 * helper function calling.
1450 ret_fr = vtd_ce_rid2pasid_check(s, ce);
1459 static int vtd_sync_shadow_page_hook(IOMMUTLBEvent *event,
1462 memory_region_notify_iommu(private, 0, *event);
1466 static uint16_t vtd_get_domain_id(IntelIOMMUState *s,
1467 VTDContextEntry *ce)
1471 if (s->root_scalable) {
1472 vtd_ce_get_rid2pasid_entry(s, ce, &pe);
1473 return VTD_SM_PASID_ENTRY_DID(pe.val[1]);
1476 return VTD_CONTEXT_ENTRY_DID(ce->hi);
1479 static int vtd_sync_shadow_page_table_range(VTDAddressSpace *vtd_as,
1480 VTDContextEntry *ce,
1481 hwaddr addr, hwaddr size)
1483 IntelIOMMUState *s = vtd_as->iommu_state;
1484 vtd_page_walk_info info = {
1485 .hook_fn = vtd_sync_shadow_page_hook,
1486 .private = (void *)&vtd_as->iommu,
1487 .notify_unmap = true,
1490 .domain_id = vtd_get_domain_id(s, ce),
1493 return vtd_page_walk(s, ce, addr, addr + size, &info);
1496 static int vtd_sync_shadow_page_table(VTDAddressSpace *vtd_as)
1502 if (!(vtd_as->iommu.iommu_notify_flags & IOMMU_NOTIFIER_IOTLB_EVENTS)) {
1506 ret = vtd_dev_to_context_entry(vtd_as->iommu_state,
1507 pci_bus_num(vtd_as->bus),
1508 vtd_as->devfn, &ce);
1510 if (ret == -VTD_FR_CONTEXT_ENTRY_P) {
1512 * It's a valid scenario to have a context entry that is
1513 * not present. For example, when a device is removed
1514 * from an existing domain then the context entry will be
1515 * zeroed by the guest before it was put into another
1516 * domain. When this happens, instead of synchronizing
1517 * the shadow pages we should invalidate all existing
1518 * mappings and notify the backends.
1520 IOMMU_NOTIFIER_FOREACH(n, &vtd_as->iommu) {
1521 vtd_address_space_unmap(vtd_as, n);
1528 return vtd_sync_shadow_page_table_range(vtd_as, &ce, 0, UINT64_MAX);
1532 * Check if specific device is configured to bypass address
1533 * translation for DMA requests. In Scalable Mode, bypass
1534 * 1st-level translation or 2nd-level translation, it depends
1537 static bool vtd_dev_pt_enabled(IntelIOMMUState *s, VTDContextEntry *ce)
1542 if (s->root_scalable) {
1543 ret = vtd_ce_get_rid2pasid_entry(s, ce, &pe);
1545 error_report_once("%s: vtd_ce_get_rid2pasid_entry error: %"PRId32,
1549 return (VTD_PE_GET_TYPE(&pe) == VTD_SM_PASID_ENTRY_PT);
1552 return (vtd_ce_get_type(ce) == VTD_CONTEXT_TT_PASS_THROUGH);
1556 static bool vtd_as_pt_enabled(VTDAddressSpace *as)
1564 s = as->iommu_state;
1565 ret = vtd_dev_to_context_entry(s, pci_bus_num(as->bus),
1569 * Possibly failed to parse the context entry for some reason
1570 * (e.g., during init, or any guest configuration errors on
1571 * context entries). We should assume PT not enabled for
1577 return vtd_dev_pt_enabled(s, &ce);
1580 /* Return whether the device is using IOMMU translation. */
1581 static bool vtd_switch_address_space(VTDAddressSpace *as)
1584 /* Whether we need to take the BQL on our own */
1585 bool take_bql = !qemu_mutex_iothread_locked();
1589 use_iommu = as->iommu_state->dmar_enabled && !vtd_as_pt_enabled(as);
1591 trace_vtd_switch_address_space(pci_bus_num(as->bus),
1592 VTD_PCI_SLOT(as->devfn),
1593 VTD_PCI_FUNC(as->devfn),
1597 * It's possible that we reach here without BQL, e.g., when called
1598 * from vtd_pt_enable_fast_path(). However the memory APIs need
1599 * it. We'd better make sure we have had it already, or, take it.
1602 qemu_mutex_lock_iothread();
1605 /* Turn off first then on the other */
1607 memory_region_set_enabled(&as->nodmar, false);
1608 memory_region_set_enabled(MEMORY_REGION(&as->iommu), true);
1610 memory_region_set_enabled(MEMORY_REGION(&as->iommu), false);
1611 memory_region_set_enabled(&as->nodmar, true);
1615 qemu_mutex_unlock_iothread();
1621 static void vtd_switch_address_space_all(IntelIOMMUState *s)
1623 GHashTableIter iter;
1627 g_hash_table_iter_init(&iter, s->vtd_as_by_busptr);
1628 while (g_hash_table_iter_next(&iter, NULL, (void **)&vtd_bus)) {
1629 for (i = 0; i < PCI_DEVFN_MAX; i++) {
1630 if (!vtd_bus->dev_as[i]) {
1633 vtd_switch_address_space(vtd_bus->dev_as[i]);
1638 static inline uint16_t vtd_make_source_id(uint8_t bus_num, uint8_t devfn)
1640 return ((bus_num & 0xffUL) << 8) | (devfn & 0xffUL);
1643 static const bool vtd_qualified_faults[] = {
1644 [VTD_FR_RESERVED] = false,
1645 [VTD_FR_ROOT_ENTRY_P] = false,
1646 [VTD_FR_CONTEXT_ENTRY_P] = true,
1647 [VTD_FR_CONTEXT_ENTRY_INV] = true,
1648 [VTD_FR_ADDR_BEYOND_MGAW] = true,
1649 [VTD_FR_WRITE] = true,
1650 [VTD_FR_READ] = true,
1651 [VTD_FR_PAGING_ENTRY_INV] = true,
1652 [VTD_FR_ROOT_TABLE_INV] = false,
1653 [VTD_FR_CONTEXT_TABLE_INV] = false,
1654 [VTD_FR_INTERRUPT_ADDR] = true,
1655 [VTD_FR_ROOT_ENTRY_RSVD] = false,
1656 [VTD_FR_PAGING_ENTRY_RSVD] = true,
1657 [VTD_FR_CONTEXT_ENTRY_TT] = true,
1658 [VTD_FR_PASID_TABLE_INV] = false,
1659 [VTD_FR_SM_INTERRUPT_ADDR] = true,
1660 [VTD_FR_MAX] = false,
1663 /* To see if a fault condition is "qualified", which is reported to software
1664 * only if the FPD field in the context-entry used to process the faulting
1667 static inline bool vtd_is_qualified_fault(VTDFaultReason fault)
1669 return vtd_qualified_faults[fault];
1672 static inline bool vtd_is_interrupt_addr(hwaddr addr)
1674 return VTD_INTERRUPT_ADDR_FIRST <= addr && addr <= VTD_INTERRUPT_ADDR_LAST;
1677 static void vtd_pt_enable_fast_path(IntelIOMMUState *s, uint16_t source_id)
1680 VTDAddressSpace *vtd_as;
1681 bool success = false;
1683 vtd_bus = vtd_find_as_from_bus_num(s, VTD_SID_TO_BUS(source_id));
1688 vtd_as = vtd_bus->dev_as[VTD_SID_TO_DEVFN(source_id)];
1693 if (vtd_switch_address_space(vtd_as) == false) {
1694 /* We switched off IOMMU region successfully. */
1699 trace_vtd_pt_enable_fast_path(source_id, success);
1702 /* Map dev to context-entry then do a paging-structures walk to do a iommu
1705 * Called from RCU critical section.
1707 * @bus_num: The bus number
1708 * @devfn: The devfn, which is the combined of device and function number
1709 * @is_write: The access is a write operation
1710 * @entry: IOMMUTLBEntry that contain the addr to be translated and result
1712 * Returns true if translation is successful, otherwise false.
1714 static bool vtd_do_iommu_translate(VTDAddressSpace *vtd_as, PCIBus *bus,
1715 uint8_t devfn, hwaddr addr, bool is_write,
1716 IOMMUTLBEntry *entry)
1718 IntelIOMMUState *s = vtd_as->iommu_state;
1720 uint8_t bus_num = pci_bus_num(bus);
1721 VTDContextCacheEntry *cc_entry;
1722 uint64_t slpte, page_mask;
1724 uint16_t source_id = vtd_make_source_id(bus_num, devfn);
1726 bool is_fpd_set = false;
1729 uint8_t access_flags;
1730 VTDIOTLBEntry *iotlb_entry;
1733 * We have standalone memory region for interrupt addresses, we
1734 * should never receive translation requests in this region.
1736 assert(!vtd_is_interrupt_addr(addr));
1740 cc_entry = &vtd_as->context_cache_entry;
1742 /* Try to fetch slpte form IOTLB */
1743 iotlb_entry = vtd_lookup_iotlb(s, source_id, addr);
1745 trace_vtd_iotlb_page_hit(source_id, addr, iotlb_entry->slpte,
1746 iotlb_entry->domain_id);
1747 slpte = iotlb_entry->slpte;
1748 access_flags = iotlb_entry->access_flags;
1749 page_mask = iotlb_entry->mask;
1753 /* Try to fetch context-entry from cache first */
1754 if (cc_entry->context_cache_gen == s->context_cache_gen) {
1755 trace_vtd_iotlb_cc_hit(bus_num, devfn, cc_entry->context_entry.hi,
1756 cc_entry->context_entry.lo,
1757 cc_entry->context_cache_gen);
1758 ce = cc_entry->context_entry;
1759 is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;
1760 if (!is_fpd_set && s->root_scalable) {
1761 ret_fr = vtd_ce_get_pasid_fpd(s, &ce, &is_fpd_set);
1762 VTD_PE_GET_FPD_ERR(ret_fr, is_fpd_set, s, source_id, addr, is_write);
1765 ret_fr = vtd_dev_to_context_entry(s, bus_num, devfn, &ce);
1766 is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;
1767 if (!ret_fr && !is_fpd_set && s->root_scalable) {
1768 ret_fr = vtd_ce_get_pasid_fpd(s, &ce, &is_fpd_set);
1770 VTD_PE_GET_FPD_ERR(ret_fr, is_fpd_set, s, source_id, addr, is_write);
1771 /* Update context-cache */
1772 trace_vtd_iotlb_cc_update(bus_num, devfn, ce.hi, ce.lo,
1773 cc_entry->context_cache_gen,
1774 s->context_cache_gen);
1775 cc_entry->context_entry = ce;
1776 cc_entry->context_cache_gen = s->context_cache_gen;
1780 * We don't need to translate for pass-through context entries.
1781 * Also, let's ignore IOTLB caching as well for PT devices.
1783 if (vtd_dev_pt_enabled(s, &ce)) {
1784 entry->iova = addr & VTD_PAGE_MASK_4K;
1785 entry->translated_addr = entry->iova;
1786 entry->addr_mask = ~VTD_PAGE_MASK_4K;
1787 entry->perm = IOMMU_RW;
1788 trace_vtd_translate_pt(source_id, entry->iova);
1791 * When this happens, it means firstly caching-mode is not
1792 * enabled, and this is the first passthrough translation for
1793 * the device. Let's enable the fast path for passthrough.
1795 * When passthrough is disabled again for the device, we can
1796 * capture it via the context entry invalidation, then the
1797 * IOMMU region can be swapped back.
1799 vtd_pt_enable_fast_path(s, source_id);
1800 vtd_iommu_unlock(s);
1804 ret_fr = vtd_iova_to_slpte(s, &ce, addr, is_write, &slpte, &level,
1805 &reads, &writes, s->aw_bits);
1806 VTD_PE_GET_FPD_ERR(ret_fr, is_fpd_set, s, source_id, addr, is_write);
1808 page_mask = vtd_slpt_level_page_mask(level);
1809 access_flags = IOMMU_ACCESS_FLAG(reads, writes);
1810 vtd_update_iotlb(s, source_id, vtd_get_domain_id(s, &ce), addr, slpte,
1811 access_flags, level);
1813 vtd_iommu_unlock(s);
1814 entry->iova = addr & page_mask;
1815 entry->translated_addr = vtd_get_slpte_addr(slpte, s->aw_bits) & page_mask;
1816 entry->addr_mask = ~page_mask;
1817 entry->perm = access_flags;
1821 vtd_iommu_unlock(s);
1823 entry->translated_addr = 0;
1824 entry->addr_mask = 0;
1825 entry->perm = IOMMU_NONE;
1829 static void vtd_root_table_setup(IntelIOMMUState *s)
1831 s->root = vtd_get_quad_raw(s, DMAR_RTADDR_REG);
1832 s->root &= VTD_RTADDR_ADDR_MASK(s->aw_bits);
1834 vtd_update_scalable_state(s);
1836 trace_vtd_reg_dmar_root(s->root, s->root_scalable);
1839 static void vtd_iec_notify_all(IntelIOMMUState *s, bool global,
1840 uint32_t index, uint32_t mask)
1842 x86_iommu_iec_notify_all(X86_IOMMU_DEVICE(s), global, index, mask);
1845 static void vtd_interrupt_remap_table_setup(IntelIOMMUState *s)
1848 value = vtd_get_quad_raw(s, DMAR_IRTA_REG);
1849 s->intr_size = 1UL << ((value & VTD_IRTA_SIZE_MASK) + 1);
1850 s->intr_root = value & VTD_IRTA_ADDR_MASK(s->aw_bits);
1851 s->intr_eime = value & VTD_IRTA_EIME;
1853 /* Notify global invalidation */
1854 vtd_iec_notify_all(s, true, 0, 0);
1856 trace_vtd_reg_ir_root(s->intr_root, s->intr_size);
1859 static void vtd_iommu_replay_all(IntelIOMMUState *s)
1861 VTDAddressSpace *vtd_as;
1863 QLIST_FOREACH(vtd_as, &s->vtd_as_with_notifiers, next) {
1864 vtd_sync_shadow_page_table(vtd_as);
1868 static void vtd_context_global_invalidate(IntelIOMMUState *s)
1870 trace_vtd_inv_desc_cc_global();
1871 /* Protects context cache */
1873 s->context_cache_gen++;
1874 if (s->context_cache_gen == VTD_CONTEXT_CACHE_GEN_MAX) {
1875 vtd_reset_context_cache_locked(s);
1877 vtd_iommu_unlock(s);
1878 vtd_address_space_refresh_all(s);
1880 * From VT-d spec 6.5.2.1, a global context entry invalidation
1881 * should be followed by a IOTLB global invalidation, so we should
1882 * be safe even without this. Hoewever, let's replay the region as
1883 * well to be safer, and go back here when we need finer tunes for
1884 * VT-d emulation codes.
1886 vtd_iommu_replay_all(s);
1889 /* Do a context-cache device-selective invalidation.
1890 * @func_mask: FM field after shifting
1892 static void vtd_context_device_invalidate(IntelIOMMUState *s,
1898 VTDAddressSpace *vtd_as;
1899 uint8_t bus_n, devfn;
1902 trace_vtd_inv_desc_cc_devices(source_id, func_mask);
1904 switch (func_mask & 3) {
1906 mask = 0; /* No bits in the SID field masked */
1909 mask = 4; /* Mask bit 2 in the SID field */
1912 mask = 6; /* Mask bit 2:1 in the SID field */
1915 mask = 7; /* Mask bit 2:0 in the SID field */
1918 g_assert_not_reached();
1922 bus_n = VTD_SID_TO_BUS(source_id);
1923 vtd_bus = vtd_find_as_from_bus_num(s, bus_n);
1925 devfn = VTD_SID_TO_DEVFN(source_id);
1926 for (devfn_it = 0; devfn_it < PCI_DEVFN_MAX; ++devfn_it) {
1927 vtd_as = vtd_bus->dev_as[devfn_it];
1928 if (vtd_as && ((devfn_it & mask) == (devfn & mask))) {
1929 trace_vtd_inv_desc_cc_device(bus_n, VTD_PCI_SLOT(devfn_it),
1930 VTD_PCI_FUNC(devfn_it));
1932 vtd_as->context_cache_entry.context_cache_gen = 0;
1933 vtd_iommu_unlock(s);
1935 * Do switch address space when needed, in case if the
1936 * device passthrough bit is switched.
1938 vtd_switch_address_space(vtd_as);
1940 * So a device is moving out of (or moving into) a
1941 * domain, resync the shadow page table.
1942 * This won't bring bad even if we have no such
1943 * notifier registered - the IOMMU notification
1944 * framework will skip MAP notifications if that
1947 vtd_sync_shadow_page_table(vtd_as);
1953 /* Context-cache invalidation
1954 * Returns the Context Actual Invalidation Granularity.
1955 * @val: the content of the CCMD_REG
1957 static uint64_t vtd_context_cache_invalidate(IntelIOMMUState *s, uint64_t val)
1960 uint64_t type = val & VTD_CCMD_CIRG_MASK;
1963 case VTD_CCMD_DOMAIN_INVL:
1965 case VTD_CCMD_GLOBAL_INVL:
1966 caig = VTD_CCMD_GLOBAL_INVL_A;
1967 vtd_context_global_invalidate(s);
1970 case VTD_CCMD_DEVICE_INVL:
1971 caig = VTD_CCMD_DEVICE_INVL_A;
1972 vtd_context_device_invalidate(s, VTD_CCMD_SID(val), VTD_CCMD_FM(val));
1976 error_report_once("%s: invalid context: 0x%" PRIx64,
1983 static void vtd_iotlb_global_invalidate(IntelIOMMUState *s)
1985 trace_vtd_inv_desc_iotlb_global();
1987 vtd_iommu_replay_all(s);
1990 static void vtd_iotlb_domain_invalidate(IntelIOMMUState *s, uint16_t domain_id)
1993 VTDAddressSpace *vtd_as;
1995 trace_vtd_inv_desc_iotlb_domain(domain_id);
1998 g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_domain,
2000 vtd_iommu_unlock(s);
2002 QLIST_FOREACH(vtd_as, &s->vtd_as_with_notifiers, next) {
2003 if (!vtd_dev_to_context_entry(s, pci_bus_num(vtd_as->bus),
2004 vtd_as->devfn, &ce) &&
2005 domain_id == vtd_get_domain_id(s, &ce)) {
2006 vtd_sync_shadow_page_table(vtd_as);
2011 static void vtd_iotlb_page_invalidate_notify(IntelIOMMUState *s,
2012 uint16_t domain_id, hwaddr addr,
2015 VTDAddressSpace *vtd_as;
2018 hwaddr size = (1 << am) * VTD_PAGE_SIZE;
2020 QLIST_FOREACH(vtd_as, &(s->vtd_as_with_notifiers), next) {
2021 ret = vtd_dev_to_context_entry(s, pci_bus_num(vtd_as->bus),
2022 vtd_as->devfn, &ce);
2023 if (!ret && domain_id == vtd_get_domain_id(s, &ce)) {
2024 if (vtd_as_has_map_notifier(vtd_as)) {
2026 * As long as we have MAP notifications registered in
2027 * any of our IOMMU notifiers, we need to sync the
2028 * shadow page table.
2030 vtd_sync_shadow_page_table_range(vtd_as, &ce, addr, size);
2033 * For UNMAP-only notifiers, we don't need to walk the
2034 * page tables. We just deliver the PSI down to
2035 * invalidate caches.
2037 IOMMUTLBEvent event = {
2038 .type = IOMMU_NOTIFIER_UNMAP,
2040 .target_as = &address_space_memory,
2042 .translated_addr = 0,
2043 .addr_mask = size - 1,
2047 memory_region_notify_iommu(&vtd_as->iommu, 0, event);
2053 static void vtd_iotlb_page_invalidate(IntelIOMMUState *s, uint16_t domain_id,
2054 hwaddr addr, uint8_t am)
2056 VTDIOTLBPageInvInfo info;
2058 trace_vtd_inv_desc_iotlb_pages(domain_id, addr, am);
2060 assert(am <= VTD_MAMV);
2061 info.domain_id = domain_id;
2063 info.mask = ~((1 << am) - 1);
2065 g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_page, &info);
2066 vtd_iommu_unlock(s);
2067 vtd_iotlb_page_invalidate_notify(s, domain_id, addr, am);
2071 * Returns the IOTLB Actual Invalidation Granularity.
2072 * @val: the content of the IOTLB_REG
2074 static uint64_t vtd_iotlb_flush(IntelIOMMUState *s, uint64_t val)
2077 uint64_t type = val & VTD_TLB_FLUSH_GRANU_MASK;
2083 case VTD_TLB_GLOBAL_FLUSH:
2084 iaig = VTD_TLB_GLOBAL_FLUSH_A;
2085 vtd_iotlb_global_invalidate(s);
2088 case VTD_TLB_DSI_FLUSH:
2089 domain_id = VTD_TLB_DID(val);
2090 iaig = VTD_TLB_DSI_FLUSH_A;
2091 vtd_iotlb_domain_invalidate(s, domain_id);
2094 case VTD_TLB_PSI_FLUSH:
2095 domain_id = VTD_TLB_DID(val);
2096 addr = vtd_get_quad_raw(s, DMAR_IVA_REG);
2097 am = VTD_IVA_AM(addr);
2098 addr = VTD_IVA_ADDR(addr);
2099 if (am > VTD_MAMV) {
2100 error_report_once("%s: address mask overflow: 0x%" PRIx64,
2101 __func__, vtd_get_quad_raw(s, DMAR_IVA_REG));
2105 iaig = VTD_TLB_PSI_FLUSH_A;
2106 vtd_iotlb_page_invalidate(s, domain_id, addr, am);
2110 error_report_once("%s: invalid granularity: 0x%" PRIx64,
2117 static void vtd_fetch_inv_desc(IntelIOMMUState *s);
2119 static inline bool vtd_queued_inv_disable_check(IntelIOMMUState *s)
2121 return s->qi_enabled && (s->iq_tail == s->iq_head) &&
2122 (s->iq_last_desc_type == VTD_INV_DESC_WAIT);
2125 static void vtd_handle_gcmd_qie(IntelIOMMUState *s, bool en)
2127 uint64_t iqa_val = vtd_get_quad_raw(s, DMAR_IQA_REG);
2129 trace_vtd_inv_qi_enable(en);
2132 s->iq = iqa_val & VTD_IQA_IQA_MASK(s->aw_bits);
2133 /* 2^(x+8) entries */
2134 s->iq_size = 1UL << ((iqa_val & VTD_IQA_QS) + 8 - (s->iq_dw ? 1 : 0));
2135 s->qi_enabled = true;
2136 trace_vtd_inv_qi_setup(s->iq, s->iq_size);
2137 /* Ok - report back to driver */
2138 vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_QIES);
2140 if (s->iq_tail != 0) {
2142 * This is a spec violation but Windows guests are known to set up
2143 * Queued Invalidation this way so we allow the write and process
2144 * Invalidation Descriptors right away.
2146 trace_vtd_warn_invalid_qi_tail(s->iq_tail);
2147 if (!(vtd_get_long_raw(s, DMAR_FSTS_REG) & VTD_FSTS_IQE)) {
2148 vtd_fetch_inv_desc(s);
2152 if (vtd_queued_inv_disable_check(s)) {
2153 /* disable Queued Invalidation */
2154 vtd_set_quad_raw(s, DMAR_IQH_REG, 0);
2156 s->qi_enabled = false;
2157 /* Ok - report back to driver */
2158 vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_QIES, 0);
2160 error_report_once("%s: detected improper state when disable QI "
2161 "(head=0x%x, tail=0x%x, last_type=%d)",
2163 s->iq_head, s->iq_tail, s->iq_last_desc_type);
2168 /* Set Root Table Pointer */
2169 static void vtd_handle_gcmd_srtp(IntelIOMMUState *s)
2171 vtd_root_table_setup(s);
2172 /* Ok - report back to driver */
2173 vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_RTPS);
2174 vtd_reset_caches(s);
2175 vtd_address_space_refresh_all(s);
2178 /* Set Interrupt Remap Table Pointer */
2179 static void vtd_handle_gcmd_sirtp(IntelIOMMUState *s)
2181 vtd_interrupt_remap_table_setup(s);
2182 /* Ok - report back to driver */
2183 vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_IRTPS);
2186 /* Handle Translation Enable/Disable */
2187 static void vtd_handle_gcmd_te(IntelIOMMUState *s, bool en)
2189 if (s->dmar_enabled == en) {
2193 trace_vtd_dmar_enable(en);
2196 s->dmar_enabled = true;
2197 /* Ok - report back to driver */
2198 vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_TES);
2200 s->dmar_enabled = false;
2202 /* Clear the index of Fault Recording Register */
2203 s->next_frcd_reg = 0;
2204 /* Ok - report back to driver */
2205 vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_TES, 0);
2208 vtd_reset_caches(s);
2209 vtd_address_space_refresh_all(s);
2212 /* Handle Interrupt Remap Enable/Disable */
2213 static void vtd_handle_gcmd_ire(IntelIOMMUState *s, bool en)
2215 trace_vtd_ir_enable(en);
2218 s->intr_enabled = true;
2219 /* Ok - report back to driver */
2220 vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_IRES);
2222 s->intr_enabled = false;
2223 /* Ok - report back to driver */
2224 vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_IRES, 0);
2228 /* Handle write to Global Command Register */
2229 static void vtd_handle_gcmd_write(IntelIOMMUState *s)
2231 X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
2232 uint32_t status = vtd_get_long_raw(s, DMAR_GSTS_REG);
2233 uint32_t val = vtd_get_long_raw(s, DMAR_GCMD_REG);
2234 uint32_t changed = status ^ val;
2236 trace_vtd_reg_write_gcmd(status, val);
2237 if ((changed & VTD_GCMD_TE) && s->dma_translation) {
2238 /* Translation enable/disable */
2239 vtd_handle_gcmd_te(s, val & VTD_GCMD_TE);
2241 if (val & VTD_GCMD_SRTP) {
2242 /* Set/update the root-table pointer */
2243 vtd_handle_gcmd_srtp(s);
2245 if (changed & VTD_GCMD_QIE) {
2246 /* Queued Invalidation Enable */
2247 vtd_handle_gcmd_qie(s, val & VTD_GCMD_QIE);
2249 if (val & VTD_GCMD_SIRTP) {
2250 /* Set/update the interrupt remapping root-table pointer */
2251 vtd_handle_gcmd_sirtp(s);
2253 if ((changed & VTD_GCMD_IRE) &&
2254 x86_iommu_ir_supported(x86_iommu)) {
2255 /* Interrupt remap enable/disable */
2256 vtd_handle_gcmd_ire(s, val & VTD_GCMD_IRE);
2260 /* Handle write to Context Command Register */
2261 static void vtd_handle_ccmd_write(IntelIOMMUState *s)
2264 uint64_t val = vtd_get_quad_raw(s, DMAR_CCMD_REG);
2266 /* Context-cache invalidation request */
2267 if (val & VTD_CCMD_ICC) {
2268 if (s->qi_enabled) {
2269 error_report_once("Queued Invalidation enabled, "
2270 "should not use register-based invalidation");
2273 ret = vtd_context_cache_invalidate(s, val);
2274 /* Invalidation completed. Change something to show */
2275 vtd_set_clear_mask_quad(s, DMAR_CCMD_REG, VTD_CCMD_ICC, 0ULL);
2276 ret = vtd_set_clear_mask_quad(s, DMAR_CCMD_REG, VTD_CCMD_CAIG_MASK,
2281 /* Handle write to IOTLB Invalidation Register */
2282 static void vtd_handle_iotlb_write(IntelIOMMUState *s)
2285 uint64_t val = vtd_get_quad_raw(s, DMAR_IOTLB_REG);
2287 /* IOTLB invalidation request */
2288 if (val & VTD_TLB_IVT) {
2289 if (s->qi_enabled) {
2290 error_report_once("Queued Invalidation enabled, "
2291 "should not use register-based invalidation");
2294 ret = vtd_iotlb_flush(s, val);
2295 /* Invalidation completed. Change something to show */
2296 vtd_set_clear_mask_quad(s, DMAR_IOTLB_REG, VTD_TLB_IVT, 0ULL);
2297 ret = vtd_set_clear_mask_quad(s, DMAR_IOTLB_REG,
2298 VTD_TLB_FLUSH_GRANU_MASK_A, ret);
2302 /* Fetch an Invalidation Descriptor from the Invalidation Queue */
2303 static bool vtd_get_inv_desc(IntelIOMMUState *s,
2304 VTDInvDesc *inv_desc)
2306 dma_addr_t base_addr = s->iq;
2307 uint32_t offset = s->iq_head;
2308 uint32_t dw = s->iq_dw ? 32 : 16;
2309 dma_addr_t addr = base_addr + offset * dw;
2311 if (dma_memory_read(&address_space_memory, addr,
2312 inv_desc, dw, MEMTXATTRS_UNSPECIFIED)) {
2313 error_report_once("Read INV DESC failed.");
2316 inv_desc->lo = le64_to_cpu(inv_desc->lo);
2317 inv_desc->hi = le64_to_cpu(inv_desc->hi);
2319 inv_desc->val[2] = le64_to_cpu(inv_desc->val[2]);
2320 inv_desc->val[3] = le64_to_cpu(inv_desc->val[3]);
2325 static bool vtd_process_wait_desc(IntelIOMMUState *s, VTDInvDesc *inv_desc)
2327 if ((inv_desc->hi & VTD_INV_DESC_WAIT_RSVD_HI) ||
2328 (inv_desc->lo & VTD_INV_DESC_WAIT_RSVD_LO)) {
2329 error_report_once("%s: invalid wait desc: hi=%"PRIx64", lo=%"PRIx64
2330 " (reserved nonzero)", __func__, inv_desc->hi,
2334 if (inv_desc->lo & VTD_INV_DESC_WAIT_SW) {
2336 uint32_t status_data = (uint32_t)(inv_desc->lo >>
2337 VTD_INV_DESC_WAIT_DATA_SHIFT);
2339 assert(!(inv_desc->lo & VTD_INV_DESC_WAIT_IF));
2341 /* FIXME: need to be masked with HAW? */
2342 dma_addr_t status_addr = inv_desc->hi;
2343 trace_vtd_inv_desc_wait_sw(status_addr, status_data);
2344 status_data = cpu_to_le32(status_data);
2345 if (dma_memory_write(&address_space_memory, status_addr,
2346 &status_data, sizeof(status_data),
2347 MEMTXATTRS_UNSPECIFIED)) {
2348 trace_vtd_inv_desc_wait_write_fail(inv_desc->hi, inv_desc->lo);
2351 } else if (inv_desc->lo & VTD_INV_DESC_WAIT_IF) {
2352 /* Interrupt flag */
2353 vtd_generate_completion_event(s);
2355 error_report_once("%s: invalid wait desc: hi=%"PRIx64", lo=%"PRIx64
2356 " (unknown type)", __func__, inv_desc->hi,
2363 static bool vtd_process_context_cache_desc(IntelIOMMUState *s,
2364 VTDInvDesc *inv_desc)
2366 uint16_t sid, fmask;
2368 if ((inv_desc->lo & VTD_INV_DESC_CC_RSVD) || inv_desc->hi) {
2369 error_report_once("%s: invalid cc inv desc: hi=%"PRIx64", lo=%"PRIx64
2370 " (reserved nonzero)", __func__, inv_desc->hi,
2374 switch (inv_desc->lo & VTD_INV_DESC_CC_G) {
2375 case VTD_INV_DESC_CC_DOMAIN:
2376 trace_vtd_inv_desc_cc_domain(
2377 (uint16_t)VTD_INV_DESC_CC_DID(inv_desc->lo));
2379 case VTD_INV_DESC_CC_GLOBAL:
2380 vtd_context_global_invalidate(s);
2383 case VTD_INV_DESC_CC_DEVICE:
2384 sid = VTD_INV_DESC_CC_SID(inv_desc->lo);
2385 fmask = VTD_INV_DESC_CC_FM(inv_desc->lo);
2386 vtd_context_device_invalidate(s, sid, fmask);
2390 error_report_once("%s: invalid cc inv desc: hi=%"PRIx64", lo=%"PRIx64
2391 " (invalid type)", __func__, inv_desc->hi,
2398 static bool vtd_process_iotlb_desc(IntelIOMMUState *s, VTDInvDesc *inv_desc)
2404 if ((inv_desc->lo & VTD_INV_DESC_IOTLB_RSVD_LO) ||
2405 (inv_desc->hi & VTD_INV_DESC_IOTLB_RSVD_HI)) {
2406 error_report_once("%s: invalid iotlb inv desc: hi=0x%"PRIx64
2407 ", lo=0x%"PRIx64" (reserved bits unzero)",
2408 __func__, inv_desc->hi, inv_desc->lo);
2412 switch (inv_desc->lo & VTD_INV_DESC_IOTLB_G) {
2413 case VTD_INV_DESC_IOTLB_GLOBAL:
2414 vtd_iotlb_global_invalidate(s);
2417 case VTD_INV_DESC_IOTLB_DOMAIN:
2418 domain_id = VTD_INV_DESC_IOTLB_DID(inv_desc->lo);
2419 vtd_iotlb_domain_invalidate(s, domain_id);
2422 case VTD_INV_DESC_IOTLB_PAGE:
2423 domain_id = VTD_INV_DESC_IOTLB_DID(inv_desc->lo);
2424 addr = VTD_INV_DESC_IOTLB_ADDR(inv_desc->hi);
2425 am = VTD_INV_DESC_IOTLB_AM(inv_desc->hi);
2426 if (am > VTD_MAMV) {
2427 error_report_once("%s: invalid iotlb inv desc: hi=0x%"PRIx64
2428 ", lo=0x%"PRIx64" (am=%u > VTD_MAMV=%u)",
2429 __func__, inv_desc->hi, inv_desc->lo,
2430 am, (unsigned)VTD_MAMV);
2433 vtd_iotlb_page_invalidate(s, domain_id, addr, am);
2437 error_report_once("%s: invalid iotlb inv desc: hi=0x%"PRIx64
2438 ", lo=0x%"PRIx64" (type mismatch: 0x%llx)",
2439 __func__, inv_desc->hi, inv_desc->lo,
2440 inv_desc->lo & VTD_INV_DESC_IOTLB_G);
2446 static bool vtd_process_inv_iec_desc(IntelIOMMUState *s,
2447 VTDInvDesc *inv_desc)
2449 trace_vtd_inv_desc_iec(inv_desc->iec.granularity,
2450 inv_desc->iec.index,
2451 inv_desc->iec.index_mask);
2453 vtd_iec_notify_all(s, !inv_desc->iec.granularity,
2454 inv_desc->iec.index,
2455 inv_desc->iec.index_mask);
2459 static bool vtd_process_device_iotlb_desc(IntelIOMMUState *s,
2460 VTDInvDesc *inv_desc)
2462 VTDAddressSpace *vtd_dev_as;
2463 IOMMUTLBEvent event;
2464 struct VTDBus *vtd_bus;
2472 addr = VTD_INV_DESC_DEVICE_IOTLB_ADDR(inv_desc->hi);
2473 sid = VTD_INV_DESC_DEVICE_IOTLB_SID(inv_desc->lo);
2476 size = VTD_INV_DESC_DEVICE_IOTLB_SIZE(inv_desc->hi);
2478 if ((inv_desc->lo & VTD_INV_DESC_DEVICE_IOTLB_RSVD_LO) ||
2479 (inv_desc->hi & VTD_INV_DESC_DEVICE_IOTLB_RSVD_HI)) {
2480 error_report_once("%s: invalid dev-iotlb inv desc: hi=%"PRIx64
2481 ", lo=%"PRIx64" (reserved nonzero)", __func__,
2482 inv_desc->hi, inv_desc->lo);
2486 vtd_bus = vtd_find_as_from_bus_num(s, bus_num);
2491 vtd_dev_as = vtd_bus->dev_as[devfn];
2496 /* According to ATS spec table 2.4:
2497 * S = 0, bits 15:12 = xxxx range size: 4K
2498 * S = 1, bits 15:12 = xxx0 range size: 8K
2499 * S = 1, bits 15:12 = xx01 range size: 16K
2500 * S = 1, bits 15:12 = x011 range size: 32K
2501 * S = 1, bits 15:12 = 0111 range size: 64K
2505 sz = (VTD_PAGE_SIZE * 2) << cto64(addr >> VTD_PAGE_SHIFT);
2511 event.type = IOMMU_NOTIFIER_DEVIOTLB_UNMAP;
2512 event.entry.target_as = &vtd_dev_as->as;
2513 event.entry.addr_mask = sz - 1;
2514 event.entry.iova = addr;
2515 event.entry.perm = IOMMU_NONE;
2516 event.entry.translated_addr = 0;
2517 memory_region_notify_iommu(&vtd_dev_as->iommu, 0, event);
2523 static bool vtd_process_inv_desc(IntelIOMMUState *s)
2525 VTDInvDesc inv_desc;
2528 trace_vtd_inv_qi_head(s->iq_head);
2529 if (!vtd_get_inv_desc(s, &inv_desc)) {
2530 s->iq_last_desc_type = VTD_INV_DESC_NONE;
2534 desc_type = inv_desc.lo & VTD_INV_DESC_TYPE;
2535 /* FIXME: should update at first or at last? */
2536 s->iq_last_desc_type = desc_type;
2538 switch (desc_type) {
2539 case VTD_INV_DESC_CC:
2540 trace_vtd_inv_desc("context-cache", inv_desc.hi, inv_desc.lo);
2541 if (!vtd_process_context_cache_desc(s, &inv_desc)) {
2546 case VTD_INV_DESC_IOTLB:
2547 trace_vtd_inv_desc("iotlb", inv_desc.hi, inv_desc.lo);
2548 if (!vtd_process_iotlb_desc(s, &inv_desc)) {
2554 * TODO: the entity of below two cases will be implemented in future series.
2555 * To make guest (which integrates scalable mode support patch set in
2556 * iommu driver) work, just return true is enough so far.
2558 case VTD_INV_DESC_PC:
2561 case VTD_INV_DESC_PIOTLB:
2564 case VTD_INV_DESC_WAIT:
2565 trace_vtd_inv_desc("wait", inv_desc.hi, inv_desc.lo);
2566 if (!vtd_process_wait_desc(s, &inv_desc)) {
2571 case VTD_INV_DESC_IEC:
2572 trace_vtd_inv_desc("iec", inv_desc.hi, inv_desc.lo);
2573 if (!vtd_process_inv_iec_desc(s, &inv_desc)) {
2578 case VTD_INV_DESC_DEVICE:
2579 trace_vtd_inv_desc("device", inv_desc.hi, inv_desc.lo);
2580 if (!vtd_process_device_iotlb_desc(s, &inv_desc)) {
2586 error_report_once("%s: invalid inv desc: hi=%"PRIx64", lo=%"PRIx64
2587 " (unknown type)", __func__, inv_desc.hi,
2592 if (s->iq_head == s->iq_size) {
2598 /* Try to fetch and process more Invalidation Descriptors */
2599 static void vtd_fetch_inv_desc(IntelIOMMUState *s)
2603 /* Refer to 10.4.23 of VT-d spec 3.0 */
2604 qi_shift = s->iq_dw ? VTD_IQH_QH_SHIFT_5 : VTD_IQH_QH_SHIFT_4;
2606 trace_vtd_inv_qi_fetch();
2608 if (s->iq_tail >= s->iq_size) {
2609 /* Detects an invalid Tail pointer */
2610 error_report_once("%s: detected invalid QI tail "
2611 "(tail=0x%x, size=0x%x)",
2612 __func__, s->iq_tail, s->iq_size);
2613 vtd_handle_inv_queue_error(s);
2616 while (s->iq_head != s->iq_tail) {
2617 if (!vtd_process_inv_desc(s)) {
2618 /* Invalidation Queue Errors */
2619 vtd_handle_inv_queue_error(s);
2622 /* Must update the IQH_REG in time */
2623 vtd_set_quad_raw(s, DMAR_IQH_REG,
2624 (((uint64_t)(s->iq_head)) << qi_shift) &
2629 /* Handle write to Invalidation Queue Tail Register */
2630 static void vtd_handle_iqt_write(IntelIOMMUState *s)
2632 uint64_t val = vtd_get_quad_raw(s, DMAR_IQT_REG);
2634 if (s->iq_dw && (val & VTD_IQT_QT_256_RSV_BIT)) {
2635 error_report_once("%s: RSV bit is set: val=0x%"PRIx64,
2639 s->iq_tail = VTD_IQT_QT(s->iq_dw, val);
2640 trace_vtd_inv_qi_tail(s->iq_tail);
2642 if (s->qi_enabled && !(vtd_get_long_raw(s, DMAR_FSTS_REG) & VTD_FSTS_IQE)) {
2643 /* Process Invalidation Queue here */
2644 vtd_fetch_inv_desc(s);
2648 static void vtd_handle_fsts_write(IntelIOMMUState *s)
2650 uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
2651 uint32_t fectl_reg = vtd_get_long_raw(s, DMAR_FECTL_REG);
2652 uint32_t status_fields = VTD_FSTS_PFO | VTD_FSTS_PPF | VTD_FSTS_IQE;
2654 if ((fectl_reg & VTD_FECTL_IP) && !(fsts_reg & status_fields)) {
2655 vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
2656 trace_vtd_fsts_clear_ip();
2658 /* FIXME: when IQE is Clear, should we try to fetch some Invalidation
2659 * Descriptors if there are any when Queued Invalidation is enabled?
2663 static void vtd_handle_fectl_write(IntelIOMMUState *s)
2666 /* FIXME: when software clears the IM field, check the IP field. But do we
2667 * need to compare the old value and the new value to conclude that
2668 * software clears the IM field? Or just check if the IM field is zero?
2670 fectl_reg = vtd_get_long_raw(s, DMAR_FECTL_REG);
2672 trace_vtd_reg_write_fectl(fectl_reg);
2674 if ((fectl_reg & VTD_FECTL_IP) && !(fectl_reg & VTD_FECTL_IM)) {
2675 vtd_generate_interrupt(s, DMAR_FEADDR_REG, DMAR_FEDATA_REG);
2676 vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
2680 static void vtd_handle_ics_write(IntelIOMMUState *s)
2682 uint32_t ics_reg = vtd_get_long_raw(s, DMAR_ICS_REG);
2683 uint32_t iectl_reg = vtd_get_long_raw(s, DMAR_IECTL_REG);
2685 if ((iectl_reg & VTD_IECTL_IP) && !(ics_reg & VTD_ICS_IWC)) {
2686 trace_vtd_reg_ics_clear_ip();
2687 vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
2691 static void vtd_handle_iectl_write(IntelIOMMUState *s)
2694 /* FIXME: when software clears the IM field, check the IP field. But do we
2695 * need to compare the old value and the new value to conclude that
2696 * software clears the IM field? Or just check if the IM field is zero?
2698 iectl_reg = vtd_get_long_raw(s, DMAR_IECTL_REG);
2700 trace_vtd_reg_write_iectl(iectl_reg);
2702 if ((iectl_reg & VTD_IECTL_IP) && !(iectl_reg & VTD_IECTL_IM)) {
2703 vtd_generate_interrupt(s, DMAR_IEADDR_REG, DMAR_IEDATA_REG);
2704 vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
2708 static uint64_t vtd_mem_read(void *opaque, hwaddr addr, unsigned size)
2710 IntelIOMMUState *s = opaque;
2713 trace_vtd_reg_read(addr, size);
2715 if (addr + size > DMAR_REG_SIZE) {
2716 error_report_once("%s: MMIO over range: addr=0x%" PRIx64
2717 " size=0x%x", __func__, addr, size);
2718 return (uint64_t)-1;
2722 /* Root Table Address Register, 64-bit */
2723 case DMAR_RTADDR_REG:
2724 val = vtd_get_quad_raw(s, DMAR_RTADDR_REG);
2726 val = val & ((1ULL << 32) - 1);
2730 case DMAR_RTADDR_REG_HI:
2732 val = vtd_get_quad_raw(s, DMAR_RTADDR_REG) >> 32;
2735 /* Invalidation Queue Address Register, 64-bit */
2737 val = s->iq | (vtd_get_quad(s, DMAR_IQA_REG) & VTD_IQA_QS);
2739 val = val & ((1ULL << 32) - 1);
2743 case DMAR_IQA_REG_HI:
2750 val = vtd_get_long(s, addr);
2752 val = vtd_get_quad(s, addr);
2759 static void vtd_mem_write(void *opaque, hwaddr addr,
2760 uint64_t val, unsigned size)
2762 IntelIOMMUState *s = opaque;
2764 trace_vtd_reg_write(addr, size, val);
2766 if (addr + size > DMAR_REG_SIZE) {
2767 error_report_once("%s: MMIO over range: addr=0x%" PRIx64
2768 " size=0x%x", __func__, addr, size);
2773 /* Global Command Register, 32-bit */
2775 vtd_set_long(s, addr, val);
2776 vtd_handle_gcmd_write(s);
2779 /* Context Command Register, 64-bit */
2782 vtd_set_long(s, addr, val);
2784 vtd_set_quad(s, addr, val);
2785 vtd_handle_ccmd_write(s);
2789 case DMAR_CCMD_REG_HI:
2791 vtd_set_long(s, addr, val);
2792 vtd_handle_ccmd_write(s);
2795 /* IOTLB Invalidation Register, 64-bit */
2796 case DMAR_IOTLB_REG:
2798 vtd_set_long(s, addr, val);
2800 vtd_set_quad(s, addr, val);
2801 vtd_handle_iotlb_write(s);
2805 case DMAR_IOTLB_REG_HI:
2807 vtd_set_long(s, addr, val);
2808 vtd_handle_iotlb_write(s);
2811 /* Invalidate Address Register, 64-bit */
2814 vtd_set_long(s, addr, val);
2816 vtd_set_quad(s, addr, val);
2820 case DMAR_IVA_REG_HI:
2822 vtd_set_long(s, addr, val);
2825 /* Fault Status Register, 32-bit */
2828 vtd_set_long(s, addr, val);
2829 vtd_handle_fsts_write(s);
2832 /* Fault Event Control Register, 32-bit */
2833 case DMAR_FECTL_REG:
2835 vtd_set_long(s, addr, val);
2836 vtd_handle_fectl_write(s);
2839 /* Fault Event Data Register, 32-bit */
2840 case DMAR_FEDATA_REG:
2842 vtd_set_long(s, addr, val);
2845 /* Fault Event Address Register, 32-bit */
2846 case DMAR_FEADDR_REG:
2848 vtd_set_long(s, addr, val);
2851 * While the register is 32-bit only, some guests (Xen...) write to
2854 vtd_set_quad(s, addr, val);
2858 /* Fault Event Upper Address Register, 32-bit */
2859 case DMAR_FEUADDR_REG:
2861 vtd_set_long(s, addr, val);
2864 /* Protected Memory Enable Register, 32-bit */
2867 vtd_set_long(s, addr, val);
2870 /* Root Table Address Register, 64-bit */
2871 case DMAR_RTADDR_REG:
2873 vtd_set_long(s, addr, val);
2875 vtd_set_quad(s, addr, val);
2879 case DMAR_RTADDR_REG_HI:
2881 vtd_set_long(s, addr, val);
2884 /* Invalidation Queue Tail Register, 64-bit */
2887 vtd_set_long(s, addr, val);
2889 vtd_set_quad(s, addr, val);
2891 vtd_handle_iqt_write(s);
2894 case DMAR_IQT_REG_HI:
2896 vtd_set_long(s, addr, val);
2897 /* 19:63 of IQT_REG is RsvdZ, do nothing here */
2900 /* Invalidation Queue Address Register, 64-bit */
2903 vtd_set_long(s, addr, val);
2905 vtd_set_quad(s, addr, val);
2907 if (s->ecap & VTD_ECAP_SMTS &&
2908 val & VTD_IQA_DW_MASK) {
2915 case DMAR_IQA_REG_HI:
2917 vtd_set_long(s, addr, val);
2920 /* Invalidation Completion Status Register, 32-bit */
2923 vtd_set_long(s, addr, val);
2924 vtd_handle_ics_write(s);
2927 /* Invalidation Event Control Register, 32-bit */
2928 case DMAR_IECTL_REG:
2930 vtd_set_long(s, addr, val);
2931 vtd_handle_iectl_write(s);
2934 /* Invalidation Event Data Register, 32-bit */
2935 case DMAR_IEDATA_REG:
2937 vtd_set_long(s, addr, val);
2940 /* Invalidation Event Address Register, 32-bit */
2941 case DMAR_IEADDR_REG:
2943 vtd_set_long(s, addr, val);
2946 /* Invalidation Event Upper Address Register, 32-bit */
2947 case DMAR_IEUADDR_REG:
2949 vtd_set_long(s, addr, val);
2952 /* Fault Recording Registers, 128-bit */
2953 case DMAR_FRCD_REG_0_0:
2955 vtd_set_long(s, addr, val);
2957 vtd_set_quad(s, addr, val);
2961 case DMAR_FRCD_REG_0_1:
2963 vtd_set_long(s, addr, val);
2966 case DMAR_FRCD_REG_0_2:
2968 vtd_set_long(s, addr, val);
2970 vtd_set_quad(s, addr, val);
2971 /* May clear bit 127 (Fault), update PPF */
2972 vtd_update_fsts_ppf(s);
2976 case DMAR_FRCD_REG_0_3:
2978 vtd_set_long(s, addr, val);
2979 /* May clear bit 127 (Fault), update PPF */
2980 vtd_update_fsts_ppf(s);
2985 vtd_set_long(s, addr, val);
2987 vtd_set_quad(s, addr, val);
2991 case DMAR_IRTA_REG_HI:
2993 vtd_set_long(s, addr, val);
2998 vtd_set_long(s, addr, val);
3000 vtd_set_quad(s, addr, val);
3005 static IOMMUTLBEntry vtd_iommu_translate(IOMMUMemoryRegion *iommu, hwaddr addr,
3006 IOMMUAccessFlags flag, int iommu_idx)
3008 VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu);
3009 IntelIOMMUState *s = vtd_as->iommu_state;
3010 IOMMUTLBEntry iotlb = {
3011 /* We'll fill in the rest later. */
3012 .target_as = &address_space_memory,
3016 if (likely(s->dmar_enabled)) {
3017 success = vtd_do_iommu_translate(vtd_as, vtd_as->bus, vtd_as->devfn,
3018 addr, flag & IOMMU_WO, &iotlb);
3020 /* DMAR disabled, passthrough, use 4k-page*/
3021 iotlb.iova = addr & VTD_PAGE_MASK_4K;
3022 iotlb.translated_addr = addr & VTD_PAGE_MASK_4K;
3023 iotlb.addr_mask = ~VTD_PAGE_MASK_4K;
3024 iotlb.perm = IOMMU_RW;
3028 if (likely(success)) {
3029 trace_vtd_dmar_translate(pci_bus_num(vtd_as->bus),
3030 VTD_PCI_SLOT(vtd_as->devfn),
3031 VTD_PCI_FUNC(vtd_as->devfn),
3032 iotlb.iova, iotlb.translated_addr,
3035 error_report_once("%s: detected translation failure "
3036 "(dev=%02x:%02x:%02x, iova=0x%" PRIx64 ")",
3037 __func__, pci_bus_num(vtd_as->bus),
3038 VTD_PCI_SLOT(vtd_as->devfn),
3039 VTD_PCI_FUNC(vtd_as->devfn),
3046 static int vtd_iommu_notify_flag_changed(IOMMUMemoryRegion *iommu,
3047 IOMMUNotifierFlag old,
3048 IOMMUNotifierFlag new,
3051 VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu);
3052 IntelIOMMUState *s = vtd_as->iommu_state;
3054 /* TODO: add support for VFIO and vhost users */
3055 if (s->snoop_control) {
3056 error_setg_errno(errp, ENOTSUP,
3057 "Snoop Control with vhost or VFIO is not supported");
3061 /* Update per-address-space notifier flags */
3062 vtd_as->notifier_flags = new;
3064 if (old == IOMMU_NOTIFIER_NONE) {
3065 QLIST_INSERT_HEAD(&s->vtd_as_with_notifiers, vtd_as, next);
3066 } else if (new == IOMMU_NOTIFIER_NONE) {
3067 QLIST_REMOVE(vtd_as, next);
3072 static int vtd_post_load(void *opaque, int version_id)
3074 IntelIOMMUState *iommu = opaque;
3077 * We don't need to migrate the root_scalable because we can
3078 * simply do the calculation after the loading is complete. We
3079 * can actually do similar things with root, dmar_enabled, etc.
3080 * however since we've had them already so we'd better keep them
3081 * for compatibility of migration.
3083 vtd_update_scalable_state(iommu);
3086 * Memory regions are dynamically turned on/off depending on
3087 * context entry configurations from the guest. After migration,
3088 * we need to make sure the memory regions are still correct.
3090 vtd_switch_address_space_all(iommu);
3095 static const VMStateDescription vtd_vmstate = {
3096 .name = "iommu-intel",
3098 .minimum_version_id = 1,
3099 .priority = MIG_PRI_IOMMU,
3100 .post_load = vtd_post_load,
3101 .fields = (VMStateField[]) {
3102 VMSTATE_UINT64(root, IntelIOMMUState),
3103 VMSTATE_UINT64(intr_root, IntelIOMMUState),
3104 VMSTATE_UINT64(iq, IntelIOMMUState),
3105 VMSTATE_UINT32(intr_size, IntelIOMMUState),
3106 VMSTATE_UINT16(iq_head, IntelIOMMUState),
3107 VMSTATE_UINT16(iq_tail, IntelIOMMUState),
3108 VMSTATE_UINT16(iq_size, IntelIOMMUState),
3109 VMSTATE_UINT16(next_frcd_reg, IntelIOMMUState),
3110 VMSTATE_UINT8_ARRAY(csr, IntelIOMMUState, DMAR_REG_SIZE),
3111 VMSTATE_UINT8(iq_last_desc_type, IntelIOMMUState),
3112 VMSTATE_UNUSED(1), /* bool root_extended is obsolete by VT-d */
3113 VMSTATE_BOOL(dmar_enabled, IntelIOMMUState),
3114 VMSTATE_BOOL(qi_enabled, IntelIOMMUState),
3115 VMSTATE_BOOL(intr_enabled, IntelIOMMUState),
3116 VMSTATE_BOOL(intr_eime, IntelIOMMUState),
3117 VMSTATE_END_OF_LIST()
3121 static const MemoryRegionOps vtd_mem_ops = {
3122 .read = vtd_mem_read,
3123 .write = vtd_mem_write,
3124 .endianness = DEVICE_LITTLE_ENDIAN,
3126 .min_access_size = 4,
3127 .max_access_size = 8,
3130 .min_access_size = 4,
3131 .max_access_size = 8,
3135 static Property vtd_properties[] = {
3136 DEFINE_PROP_UINT32("version", IntelIOMMUState, version, 0),
3137 DEFINE_PROP_ON_OFF_AUTO("eim", IntelIOMMUState, intr_eim,
3139 DEFINE_PROP_BOOL("x-buggy-eim", IntelIOMMUState, buggy_eim, false),
3140 DEFINE_PROP_UINT8("aw-bits", IntelIOMMUState, aw_bits,
3141 VTD_HOST_ADDRESS_WIDTH),
3142 DEFINE_PROP_BOOL("caching-mode", IntelIOMMUState, caching_mode, FALSE),
3143 DEFINE_PROP_BOOL("x-scalable-mode", IntelIOMMUState, scalable_mode, FALSE),
3144 DEFINE_PROP_BOOL("snoop-control", IntelIOMMUState, snoop_control, false),
3145 DEFINE_PROP_BOOL("dma-drain", IntelIOMMUState, dma_drain, true),
3146 DEFINE_PROP_BOOL("dma-translation", IntelIOMMUState, dma_translation, true),
3147 DEFINE_PROP_END_OF_LIST(),
3150 /* Read IRTE entry with specific index */
3151 static int vtd_irte_get(IntelIOMMUState *iommu, uint16_t index,
3152 VTD_IR_TableEntry *entry, uint16_t sid)
3154 static const uint16_t vtd_svt_mask[VTD_SQ_MAX] = \
3155 {0xffff, 0xfffb, 0xfff9, 0xfff8};
3156 dma_addr_t addr = 0x00;
3157 uint16_t mask, source_id;
3158 uint8_t bus, bus_max, bus_min;
3160 if (index >= iommu->intr_size) {
3161 error_report_once("%s: index too large: ind=0x%x",
3163 return -VTD_FR_IR_INDEX_OVER;
3166 addr = iommu->intr_root + index * sizeof(*entry);
3167 if (dma_memory_read(&address_space_memory, addr,
3168 entry, sizeof(*entry), MEMTXATTRS_UNSPECIFIED)) {
3169 error_report_once("%s: read failed: ind=0x%x addr=0x%" PRIx64,
3170 __func__, index, addr);
3171 return -VTD_FR_IR_ROOT_INVAL;
3174 trace_vtd_ir_irte_get(index, le64_to_cpu(entry->data[1]),
3175 le64_to_cpu(entry->data[0]));
3177 if (!entry->irte.present) {
3178 error_report_once("%s: detected non-present IRTE "
3179 "(index=%u, high=0x%" PRIx64 ", low=0x%" PRIx64 ")",
3180 __func__, index, le64_to_cpu(entry->data[1]),
3181 le64_to_cpu(entry->data[0]));
3182 return -VTD_FR_IR_ENTRY_P;
3185 if (entry->irte.__reserved_0 || entry->irte.__reserved_1 ||
3186 entry->irte.__reserved_2) {
3187 error_report_once("%s: detected non-zero reserved IRTE "
3188 "(index=%u, high=0x%" PRIx64 ", low=0x%" PRIx64 ")",
3189 __func__, index, le64_to_cpu(entry->data[1]),
3190 le64_to_cpu(entry->data[0]));
3191 return -VTD_FR_IR_IRTE_RSVD;
3194 if (sid != X86_IOMMU_SID_INVALID) {
3195 /* Validate IRTE SID */
3196 source_id = le32_to_cpu(entry->irte.source_id);
3197 switch (entry->irte.sid_vtype) {
3202 mask = vtd_svt_mask[entry->irte.sid_q];
3203 if ((source_id & mask) != (sid & mask)) {
3204 error_report_once("%s: invalid IRTE SID "
3205 "(index=%u, sid=%u, source_id=%u)",
3206 __func__, index, sid, source_id);
3207 return -VTD_FR_IR_SID_ERR;
3212 bus_max = source_id >> 8;
3213 bus_min = source_id & 0xff;
3215 if (bus > bus_max || bus < bus_min) {
3216 error_report_once("%s: invalid SVT_BUS "
3217 "(index=%u, bus=%u, min=%u, max=%u)",
3218 __func__, index, bus, bus_min, bus_max);
3219 return -VTD_FR_IR_SID_ERR;
3224 error_report_once("%s: detected invalid IRTE SVT "
3225 "(index=%u, type=%d)", __func__,
3226 index, entry->irte.sid_vtype);
3227 /* Take this as verification failure. */
3228 return -VTD_FR_IR_SID_ERR;
3235 /* Fetch IRQ information of specific IR index */
3236 static int vtd_remap_irq_get(IntelIOMMUState *iommu, uint16_t index,
3237 X86IOMMUIrq *irq, uint16_t sid)
3239 VTD_IR_TableEntry irte = {};
3242 ret = vtd_irte_get(iommu, index, &irte, sid);
3247 irq->trigger_mode = irte.irte.trigger_mode;
3248 irq->vector = irte.irte.vector;
3249 irq->delivery_mode = irte.irte.delivery_mode;
3250 irq->dest = le32_to_cpu(irte.irte.dest_id);
3251 if (!iommu->intr_eime) {
3252 #define VTD_IR_APIC_DEST_MASK (0xff00ULL)
3253 #define VTD_IR_APIC_DEST_SHIFT (8)
3254 irq->dest = (irq->dest & VTD_IR_APIC_DEST_MASK) >>
3255 VTD_IR_APIC_DEST_SHIFT;
3257 irq->dest_mode = irte.irte.dest_mode;
3258 irq->redir_hint = irte.irte.redir_hint;
3260 trace_vtd_ir_remap(index, irq->trigger_mode, irq->vector,
3261 irq->delivery_mode, irq->dest, irq->dest_mode);
3266 /* Interrupt remapping for MSI/MSI-X entry */
3267 static int vtd_interrupt_remap_msi(IntelIOMMUState *iommu,
3269 MSIMessage *translated,
3273 VTD_IR_MSIAddress addr;
3275 X86IOMMUIrq irq = {};
3277 assert(origin && translated);
3279 trace_vtd_ir_remap_msi_req(origin->address, origin->data);
3281 if (!iommu || !iommu->intr_enabled) {
3282 memcpy(translated, origin, sizeof(*origin));
3286 if (origin->address & VTD_MSI_ADDR_HI_MASK) {
3287 error_report_once("%s: MSI address high 32 bits non-zero detected: "
3288 "address=0x%" PRIx64, __func__, origin->address);
3289 return -VTD_FR_IR_REQ_RSVD;
3292 addr.data = origin->address & VTD_MSI_ADDR_LO_MASK;
3293 if (addr.addr.__head != 0xfee) {
3294 error_report_once("%s: MSI address low 32 bit invalid: 0x%" PRIx32,
3295 __func__, addr.data);
3296 return -VTD_FR_IR_REQ_RSVD;
3299 /* This is compatible mode. */
3300 if (addr.addr.int_mode != VTD_IR_INT_FORMAT_REMAP) {
3301 memcpy(translated, origin, sizeof(*origin));
3305 index = addr.addr.index_h << 15 | le16_to_cpu(addr.addr.index_l);
3307 #define VTD_IR_MSI_DATA_SUBHANDLE (0x0000ffff)
3308 #define VTD_IR_MSI_DATA_RESERVED (0xffff0000)
3310 if (addr.addr.sub_valid) {
3311 /* See VT-d spec 5.1.2.2 and 5.1.3 on subhandle */
3312 index += origin->data & VTD_IR_MSI_DATA_SUBHANDLE;
3315 ret = vtd_remap_irq_get(iommu, index, &irq, sid);
3320 if (addr.addr.sub_valid) {
3321 trace_vtd_ir_remap_type("MSI");
3322 if (origin->data & VTD_IR_MSI_DATA_RESERVED) {
3323 error_report_once("%s: invalid IR MSI "
3324 "(sid=%u, address=0x%" PRIx64
3325 ", data=0x%" PRIx32 ")",
3326 __func__, sid, origin->address, origin->data);
3327 return -VTD_FR_IR_REQ_RSVD;
3330 uint8_t vector = origin->data & 0xff;
3331 uint8_t trigger_mode = (origin->data >> MSI_DATA_TRIGGER_SHIFT) & 0x1;
3333 trace_vtd_ir_remap_type("IOAPIC");
3334 /* IOAPIC entry vector should be aligned with IRTE vector
3335 * (see vt-d spec 5.1.5.1). */
3336 if (vector != irq.vector) {
3337 trace_vtd_warn_ir_vector(sid, index, vector, irq.vector);
3340 /* The Trigger Mode field must match the Trigger Mode in the IRTE.
3341 * (see vt-d spec 5.1.5.1). */
3342 if (trigger_mode != irq.trigger_mode) {
3343 trace_vtd_warn_ir_trigger(sid, index, trigger_mode,
3349 * We'd better keep the last two bits, assuming that guest OS
3350 * might modify it. Keep it does not hurt after all.
3352 irq.msi_addr_last_bits = addr.addr.__not_care;
3354 /* Translate X86IOMMUIrq to MSI message */
3355 x86_iommu_irq_to_msi_message(&irq, translated);
3358 trace_vtd_ir_remap_msi(origin->address, origin->data,
3359 translated->address, translated->data);
3363 static int vtd_int_remap(X86IOMMUState *iommu, MSIMessage *src,
3364 MSIMessage *dst, uint16_t sid)
3366 return vtd_interrupt_remap_msi(INTEL_IOMMU_DEVICE(iommu),
3370 static MemTxResult vtd_mem_ir_read(void *opaque, hwaddr addr,
3371 uint64_t *data, unsigned size,
3377 static MemTxResult vtd_mem_ir_write(void *opaque, hwaddr addr,
3378 uint64_t value, unsigned size,
3382 MSIMessage from = {}, to = {};
3383 uint16_t sid = X86_IOMMU_SID_INVALID;
3385 from.address = (uint64_t) addr + VTD_INTERRUPT_ADDR_FIRST;
3386 from.data = (uint32_t) value;
3388 if (!attrs.unspecified) {
3389 /* We have explicit Source ID */
3390 sid = attrs.requester_id;
3393 ret = vtd_interrupt_remap_msi(opaque, &from, &to, sid);
3395 /* TODO: report error */
3396 /* Drop this interrupt */
3400 apic_get_class()->send_msi(&to);
3405 static const MemoryRegionOps vtd_mem_ir_ops = {
3406 .read_with_attrs = vtd_mem_ir_read,
3407 .write_with_attrs = vtd_mem_ir_write,
3408 .endianness = DEVICE_LITTLE_ENDIAN,
3410 .min_access_size = 4,
3411 .max_access_size = 4,
3414 .min_access_size = 4,
3415 .max_access_size = 4,
3419 VTDAddressSpace *vtd_find_add_as(IntelIOMMUState *s, PCIBus *bus, int devfn)
3421 uintptr_t key = (uintptr_t)bus;
3422 VTDBus *vtd_bus = g_hash_table_lookup(s->vtd_as_by_busptr, &key);
3423 VTDAddressSpace *vtd_dev_as;
3427 uintptr_t *new_key = g_malloc(sizeof(*new_key));
3428 *new_key = (uintptr_t)bus;
3429 /* No corresponding free() */
3430 vtd_bus = g_malloc0(sizeof(VTDBus) + sizeof(VTDAddressSpace *) * \
3433 g_hash_table_insert(s->vtd_as_by_busptr, new_key, vtd_bus);
3436 vtd_dev_as = vtd_bus->dev_as[devfn];
3439 snprintf(name, sizeof(name), "vtd-%02x.%x", PCI_SLOT(devfn),
3441 vtd_bus->dev_as[devfn] = vtd_dev_as = g_new0(VTDAddressSpace, 1);
3443 vtd_dev_as->bus = bus;
3444 vtd_dev_as->devfn = (uint8_t)devfn;
3445 vtd_dev_as->iommu_state = s;
3446 vtd_dev_as->context_cache_entry.context_cache_gen = 0;
3447 vtd_dev_as->iova_tree = iova_tree_new();
3449 memory_region_init(&vtd_dev_as->root, OBJECT(s), name, UINT64_MAX);
3450 address_space_init(&vtd_dev_as->as, &vtd_dev_as->root, "vtd-root");
3453 * Build the DMAR-disabled container with aliases to the
3454 * shared MRs. Note that aliasing to a shared memory region
3455 * could help the memory API to detect same FlatViews so we
3456 * can have devices to share the same FlatView when DMAR is
3457 * disabled (either by not providing "intel_iommu=on" or with
3458 * "iommu=pt"). It will greatly reduce the total number of
3459 * FlatViews of the system hence VM runs faster.
3461 memory_region_init_alias(&vtd_dev_as->nodmar, OBJECT(s),
3462 "vtd-nodmar", &s->mr_nodmar, 0,
3463 memory_region_size(&s->mr_nodmar));
3466 * Build the per-device DMAR-enabled container.
3468 * TODO: currently we have per-device IOMMU memory region only
3469 * because we have per-device IOMMU notifiers for devices. If
3470 * one day we can abstract the IOMMU notifiers out of the
3471 * memory regions then we can also share the same memory
3472 * region here just like what we've done above with the nodmar
3475 strcat(name, "-dmar");
3476 memory_region_init_iommu(&vtd_dev_as->iommu, sizeof(vtd_dev_as->iommu),
3477 TYPE_INTEL_IOMMU_MEMORY_REGION, OBJECT(s),
3479 memory_region_init_alias(&vtd_dev_as->iommu_ir, OBJECT(s), "vtd-ir",
3480 &s->mr_ir, 0, memory_region_size(&s->mr_ir));
3481 memory_region_add_subregion_overlap(MEMORY_REGION(&vtd_dev_as->iommu),
3482 VTD_INTERRUPT_ADDR_FIRST,
3483 &vtd_dev_as->iommu_ir, 1);
3486 * Hook both the containers under the root container, we
3487 * switch between DMAR & noDMAR by enable/disable
3488 * corresponding sub-containers
3490 memory_region_add_subregion_overlap(&vtd_dev_as->root, 0,
3491 MEMORY_REGION(&vtd_dev_as->iommu),
3493 memory_region_add_subregion_overlap(&vtd_dev_as->root, 0,
3494 &vtd_dev_as->nodmar, 0);
3496 vtd_switch_address_space(vtd_dev_as);
3501 /* Unmap the whole range in the notifier's scope. */
3502 static void vtd_address_space_unmap(VTDAddressSpace *as, IOMMUNotifier *n)
3504 hwaddr size, remain;
3505 hwaddr start = n->start;
3506 hwaddr end = n->end;
3507 IntelIOMMUState *s = as->iommu_state;
3511 * Note: all the codes in this function has a assumption that IOVA
3512 * bits are no more than VTD_MGAW bits (which is restricted by
3513 * VT-d spec), otherwise we need to consider overflow of 64 bits.
3516 if (end > VTD_ADDRESS_SIZE(s->aw_bits) - 1) {
3518 * Don't need to unmap regions that is bigger than the whole
3519 * VT-d supported address space size
3521 end = VTD_ADDRESS_SIZE(s->aw_bits) - 1;
3524 assert(start <= end);
3525 size = remain = end - start + 1;
3527 while (remain >= VTD_PAGE_SIZE) {
3528 IOMMUTLBEvent event;
3529 uint64_t mask = dma_aligned_pow2_mask(start, end, s->aw_bits);
3530 uint64_t size = mask + 1;
3534 event.type = IOMMU_NOTIFIER_UNMAP;
3535 event.entry.iova = start;
3536 event.entry.addr_mask = mask;
3537 event.entry.target_as = &address_space_memory;
3538 event.entry.perm = IOMMU_NONE;
3539 /* This field is meaningless for unmap */
3540 event.entry.translated_addr = 0;
3542 memory_region_notify_iommu_one(n, &event);
3550 trace_vtd_as_unmap_whole(pci_bus_num(as->bus),
3551 VTD_PCI_SLOT(as->devfn),
3552 VTD_PCI_FUNC(as->devfn),
3555 map.iova = n->start;
3557 iova_tree_remove(as->iova_tree, &map);
3560 static void vtd_address_space_unmap_all(IntelIOMMUState *s)
3562 VTDAddressSpace *vtd_as;
3565 QLIST_FOREACH(vtd_as, &s->vtd_as_with_notifiers, next) {
3566 IOMMU_NOTIFIER_FOREACH(n, &vtd_as->iommu) {
3567 vtd_address_space_unmap(vtd_as, n);
3572 static void vtd_address_space_refresh_all(IntelIOMMUState *s)
3574 vtd_address_space_unmap_all(s);
3575 vtd_switch_address_space_all(s);
3578 static int vtd_replay_hook(IOMMUTLBEvent *event, void *private)
3580 memory_region_notify_iommu_one(private, event);
3584 static void vtd_iommu_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n)
3586 VTDAddressSpace *vtd_as = container_of(iommu_mr, VTDAddressSpace, iommu);
3587 IntelIOMMUState *s = vtd_as->iommu_state;
3588 uint8_t bus_n = pci_bus_num(vtd_as->bus);
3592 * The replay can be triggered by either a invalidation or a newly
3593 * created entry. No matter what, we release existing mappings
3594 * (it means flushing caches for UNMAP-only registers).
3596 vtd_address_space_unmap(vtd_as, n);
3598 if (vtd_dev_to_context_entry(s, bus_n, vtd_as->devfn, &ce) == 0) {
3599 trace_vtd_replay_ce_valid(s->root_scalable ? "scalable mode" :
3601 bus_n, PCI_SLOT(vtd_as->devfn),
3602 PCI_FUNC(vtd_as->devfn),
3603 vtd_get_domain_id(s, &ce),
3605 if (vtd_as_has_map_notifier(vtd_as)) {
3606 /* This is required only for MAP typed notifiers */
3607 vtd_page_walk_info info = {
3608 .hook_fn = vtd_replay_hook,
3609 .private = (void *)n,
3610 .notify_unmap = false,
3613 .domain_id = vtd_get_domain_id(s, &ce),
3616 vtd_page_walk(s, &ce, 0, ~0ULL, &info);
3619 trace_vtd_replay_ce_invalid(bus_n, PCI_SLOT(vtd_as->devfn),
3620 PCI_FUNC(vtd_as->devfn));
3626 /* Do the initialization. It will also be called when reset, so pay
3627 * attention when adding new initialization stuff.
3629 static void vtd_init(IntelIOMMUState *s)
3631 X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
3633 memset(s->csr, 0, DMAR_REG_SIZE);
3634 memset(s->wmask, 0, DMAR_REG_SIZE);
3635 memset(s->w1cmask, 0, DMAR_REG_SIZE);
3636 memset(s->womask, 0, DMAR_REG_SIZE);
3639 s->root_scalable = false;
3640 s->dmar_enabled = false;
3641 s->intr_enabled = false;
3646 s->qi_enabled = false;
3647 s->iq_last_desc_type = VTD_INV_DESC_NONE;
3649 s->next_frcd_reg = 0;
3650 s->cap = VTD_CAP_FRO | VTD_CAP_NFR | VTD_CAP_ND |
3651 VTD_CAP_MAMV | VTD_CAP_PSI | VTD_CAP_SLLPS |
3652 VTD_CAP_MGAW(s->aw_bits);
3654 s->cap |= VTD_CAP_DRAIN;
3656 if (s->dma_translation) {
3657 if (s->aw_bits >= VTD_HOST_AW_39BIT) {
3658 s->cap |= VTD_CAP_SAGAW_39bit;
3660 if (s->aw_bits >= VTD_HOST_AW_48BIT) {
3661 s->cap |= VTD_CAP_SAGAW_48bit;
3664 s->ecap = VTD_ECAP_QI | VTD_ECAP_IRO;
3667 * Rsvd field masks for spte
3669 vtd_spte_rsvd[0] = ~0ULL;
3670 vtd_spte_rsvd[1] = VTD_SPTE_PAGE_L1_RSVD_MASK(s->aw_bits,
3671 x86_iommu->dt_supported);
3672 vtd_spte_rsvd[2] = VTD_SPTE_PAGE_L2_RSVD_MASK(s->aw_bits);
3673 vtd_spte_rsvd[3] = VTD_SPTE_PAGE_L3_RSVD_MASK(s->aw_bits);
3674 vtd_spte_rsvd[4] = VTD_SPTE_PAGE_L4_RSVD_MASK(s->aw_bits);
3676 vtd_spte_rsvd_large[2] = VTD_SPTE_LPAGE_L2_RSVD_MASK(s->aw_bits,
3677 x86_iommu->dt_supported);
3678 vtd_spte_rsvd_large[3] = VTD_SPTE_LPAGE_L3_RSVD_MASK(s->aw_bits,
3679 x86_iommu->dt_supported);
3681 if (s->scalable_mode || s->snoop_control) {
3682 vtd_spte_rsvd[1] &= ~VTD_SPTE_SNP;
3683 vtd_spte_rsvd_large[2] &= ~VTD_SPTE_SNP;
3684 vtd_spte_rsvd_large[3] &= ~VTD_SPTE_SNP;
3687 if (x86_iommu_ir_supported(x86_iommu)) {
3688 s->ecap |= VTD_ECAP_IR | VTD_ECAP_MHMV;
3689 if (s->intr_eim == ON_OFF_AUTO_ON) {
3690 s->ecap |= VTD_ECAP_EIM;
3692 assert(s->intr_eim != ON_OFF_AUTO_AUTO);
3695 if (x86_iommu->dt_supported) {
3696 s->ecap |= VTD_ECAP_DT;
3699 if (x86_iommu->pt_supported) {
3700 s->ecap |= VTD_ECAP_PT;
3703 if (s->caching_mode) {
3704 s->cap |= VTD_CAP_CM;
3707 /* TODO: read cap/ecap from host to decide which cap to be exposed. */
3708 if (s->scalable_mode) {
3709 s->ecap |= VTD_ECAP_SMTS | VTD_ECAP_SRS | VTD_ECAP_SLTS;
3712 if (s->snoop_control) {
3713 s->ecap |= VTD_ECAP_SC;
3716 vtd_reset_caches(s);
3718 /* Define registers with default values and bit semantics */
3719 vtd_define_long(s, DMAR_VER_REG, 0x10UL, 0, 0);
3720 vtd_define_quad(s, DMAR_CAP_REG, s->cap, 0, 0);
3721 vtd_define_quad(s, DMAR_ECAP_REG, s->ecap, 0, 0);
3722 vtd_define_long(s, DMAR_GCMD_REG, 0, 0xff800000UL, 0);
3723 vtd_define_long_wo(s, DMAR_GCMD_REG, 0xff800000UL);
3724 vtd_define_long(s, DMAR_GSTS_REG, 0, 0, 0);
3725 vtd_define_quad(s, DMAR_RTADDR_REG, 0, 0xfffffffffffffc00ULL, 0);
3726 vtd_define_quad(s, DMAR_CCMD_REG, 0, 0xe0000003ffffffffULL, 0);
3727 vtd_define_quad_wo(s, DMAR_CCMD_REG, 0x3ffff0000ULL);
3729 /* Advanced Fault Logging not supported */
3730 vtd_define_long(s, DMAR_FSTS_REG, 0, 0, 0x11UL);
3731 vtd_define_long(s, DMAR_FECTL_REG, 0x80000000UL, 0x80000000UL, 0);
3732 vtd_define_long(s, DMAR_FEDATA_REG, 0, 0x0000ffffUL, 0);
3733 vtd_define_long(s, DMAR_FEADDR_REG, 0, 0xfffffffcUL, 0);
3735 /* Treated as RsvdZ when EIM in ECAP_REG is not supported
3736 * vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0xffffffffUL, 0);
3738 vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0, 0);
3740 /* Treated as RO for implementations that PLMR and PHMR fields reported
3741 * as Clear in the CAP_REG.
3742 * vtd_define_long(s, DMAR_PMEN_REG, 0, 0x80000000UL, 0);
3744 vtd_define_long(s, DMAR_PMEN_REG, 0, 0, 0);
3746 vtd_define_quad(s, DMAR_IQH_REG, 0, 0, 0);
3747 vtd_define_quad(s, DMAR_IQT_REG, 0, 0x7fff0ULL, 0);
3748 vtd_define_quad(s, DMAR_IQA_REG, 0, 0xfffffffffffff807ULL, 0);
3749 vtd_define_long(s, DMAR_ICS_REG, 0, 0, 0x1UL);
3750 vtd_define_long(s, DMAR_IECTL_REG, 0x80000000UL, 0x80000000UL, 0);
3751 vtd_define_long(s, DMAR_IEDATA_REG, 0, 0xffffffffUL, 0);
3752 vtd_define_long(s, DMAR_IEADDR_REG, 0, 0xfffffffcUL, 0);
3753 /* Treadted as RsvdZ when EIM in ECAP_REG is not supported */
3754 vtd_define_long(s, DMAR_IEUADDR_REG, 0, 0, 0);
3756 /* IOTLB registers */
3757 vtd_define_quad(s, DMAR_IOTLB_REG, 0, 0Xb003ffff00000000ULL, 0);
3758 vtd_define_quad(s, DMAR_IVA_REG, 0, 0xfffffffffffff07fULL, 0);
3759 vtd_define_quad_wo(s, DMAR_IVA_REG, 0xfffffffffffff07fULL);
3761 /* Fault Recording Registers, 128-bit */
3762 vtd_define_quad(s, DMAR_FRCD_REG_0_0, 0, 0, 0);
3763 vtd_define_quad(s, DMAR_FRCD_REG_0_2, 0, 0, 0x8000000000000000ULL);
3766 * Interrupt remapping registers.
3768 vtd_define_quad(s, DMAR_IRTA_REG, 0, 0xfffffffffffff80fULL, 0);
3771 /* Should not reset address_spaces when reset because devices will still use
3772 * the address space they got at first (won't ask the bus again).
3774 static void vtd_reset(DeviceState *dev)
3776 IntelIOMMUState *s = INTEL_IOMMU_DEVICE(dev);
3779 vtd_address_space_refresh_all(s);
3782 static AddressSpace *vtd_host_dma_iommu(PCIBus *bus, void *opaque, int devfn)
3784 IntelIOMMUState *s = opaque;
3785 VTDAddressSpace *vtd_as;
3787 assert(0 <= devfn && devfn < PCI_DEVFN_MAX);
3789 vtd_as = vtd_find_add_as(s, bus, devfn);
3793 static bool vtd_decide_config(IntelIOMMUState *s, Error **errp)
3795 X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
3797 if (s->intr_eim == ON_OFF_AUTO_ON && !x86_iommu_ir_supported(x86_iommu)) {
3798 error_setg(errp, "eim=on cannot be selected without intremap=on");
3802 if (s->intr_eim == ON_OFF_AUTO_AUTO) {
3803 s->intr_eim = (kvm_irqchip_in_kernel() || s->buggy_eim)
3804 && x86_iommu_ir_supported(x86_iommu) ?
3805 ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
3807 if (s->intr_eim == ON_OFF_AUTO_ON && !s->buggy_eim) {
3808 if (!kvm_irqchip_is_split()) {
3809 error_setg(errp, "eim=on requires accel=kvm,kernel-irqchip=split");
3814 /* Currently only address widths supported are 39 and 48 bits */
3815 if ((s->aw_bits != VTD_HOST_AW_39BIT) &&
3816 (s->aw_bits != VTD_HOST_AW_48BIT)) {
3817 error_setg(errp, "Supported values for aw-bits are: %d, %d",
3818 VTD_HOST_AW_39BIT, VTD_HOST_AW_48BIT);
3822 if (s->scalable_mode && !s->dma_drain) {
3823 error_setg(errp, "Need to set dma_drain for scalable mode");
3830 static int vtd_machine_done_notify_one(Object *child, void *unused)
3832 IntelIOMMUState *iommu = INTEL_IOMMU_DEVICE(x86_iommu_get_default());
3835 * We hard-coded here because vfio-pci is the only special case
3836 * here. Let's be more elegant in the future when we can, but so
3837 * far there seems to be no better way.
3839 if (object_dynamic_cast(child, "vfio-pci") && !iommu->caching_mode) {
3840 vtd_panic_require_caching_mode();
3846 static void vtd_machine_done_hook(Notifier *notifier, void *unused)
3848 object_child_foreach_recursive(object_get_root(),
3849 vtd_machine_done_notify_one, NULL);
3852 static Notifier vtd_machine_done_notify = {
3853 .notify = vtd_machine_done_hook,
3856 static void vtd_realize(DeviceState *dev, Error **errp)
3858 MachineState *ms = MACHINE(qdev_get_machine());
3859 PCMachineState *pcms = PC_MACHINE(ms);
3860 X86MachineState *x86ms = X86_MACHINE(ms);
3861 PCIBus *bus = pcms->bus;
3862 IntelIOMMUState *s = INTEL_IOMMU_DEVICE(dev);
3864 if (!vtd_decide_config(s, errp)) {
3868 QLIST_INIT(&s->vtd_as_with_notifiers);
3869 qemu_mutex_init(&s->iommu_lock);
3870 memset(s->vtd_as_by_bus_num, 0, sizeof(s->vtd_as_by_bus_num));
3871 memory_region_init_io(&s->csrmem, OBJECT(s), &vtd_mem_ops, s,
3872 "intel_iommu", DMAR_REG_SIZE);
3874 /* Create the shared memory regions by all devices */
3875 memory_region_init(&s->mr_nodmar, OBJECT(s), "vtd-nodmar",
3877 memory_region_init_io(&s->mr_ir, OBJECT(s), &vtd_mem_ir_ops,
3878 s, "vtd-ir", VTD_INTERRUPT_ADDR_SIZE);
3879 memory_region_init_alias(&s->mr_sys_alias, OBJECT(s),
3880 "vtd-sys-alias", get_system_memory(), 0,
3881 memory_region_size(get_system_memory()));
3882 memory_region_add_subregion_overlap(&s->mr_nodmar, 0,
3883 &s->mr_sys_alias, 0);
3884 memory_region_add_subregion_overlap(&s->mr_nodmar,
3885 VTD_INTERRUPT_ADDR_FIRST,
3888 sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->csrmem);
3889 /* No corresponding destroy */
3890 s->iotlb = g_hash_table_new_full(vtd_uint64_hash, vtd_uint64_equal,
3892 s->vtd_as_by_busptr = g_hash_table_new_full(vtd_uint64_hash, vtd_uint64_equal,
3895 sysbus_mmio_map(SYS_BUS_DEVICE(s), 0, Q35_HOST_BRIDGE_IOMMU_ADDR);
3896 pci_setup_iommu(bus, vtd_host_dma_iommu, dev);
3897 /* Pseudo address space under root PCI bus. */
3898 x86ms->ioapic_as = vtd_host_dma_iommu(bus, s, Q35_PSEUDO_DEVFN_IOAPIC);
3899 qemu_add_machine_init_done_notifier(&vtd_machine_done_notify);
3902 static void vtd_class_init(ObjectClass *klass, void *data)
3904 DeviceClass *dc = DEVICE_CLASS(klass);
3905 X86IOMMUClass *x86_class = X86_IOMMU_DEVICE_CLASS(klass);
3907 dc->reset = vtd_reset;
3908 dc->vmsd = &vtd_vmstate;
3909 device_class_set_props(dc, vtd_properties);
3910 dc->hotpluggable = false;
3911 x86_class->realize = vtd_realize;
3912 x86_class->int_remap = vtd_int_remap;
3913 /* Supported by the pc-q35-* machine types */
3914 dc->user_creatable = true;
3915 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
3916 dc->desc = "Intel IOMMU (VT-d) DMA Remapping device";
3919 static const TypeInfo vtd_info = {
3920 .name = TYPE_INTEL_IOMMU_DEVICE,
3921 .parent = TYPE_X86_IOMMU_DEVICE,
3922 .instance_size = sizeof(IntelIOMMUState),
3923 .class_init = vtd_class_init,
3926 static void vtd_iommu_memory_region_class_init(ObjectClass *klass,
3929 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_CLASS(klass);
3931 imrc->translate = vtd_iommu_translate;
3932 imrc->notify_flag_changed = vtd_iommu_notify_flag_changed;
3933 imrc->replay = vtd_iommu_replay;
3936 static const TypeInfo vtd_iommu_memory_region_info = {
3937 .parent = TYPE_IOMMU_MEMORY_REGION,
3938 .name = TYPE_INTEL_IOMMU_MEMORY_REGION,
3939 .class_init = vtd_iommu_memory_region_class_init,
3942 static void vtd_register_types(void)
3944 type_register_static(&vtd_info);
3945 type_register_static(&vtd_iommu_memory_region_info);
3948 type_init(vtd_register_types)