xref: /openbmc/qemu/hw/i386/intel_iommu.c (revision b54a9d46a0fe294a3ff6d169cd5292c73e2894e4)
11da12ec4SLe Tan /*
21da12ec4SLe Tan  * QEMU emulation of an Intel IOMMU (VT-d)
31da12ec4SLe Tan  *   (DMA Remapping device)
41da12ec4SLe Tan  *
51da12ec4SLe Tan  * Copyright (C) 2013 Knut Omang, Oracle <knut.omang@oracle.com>
61da12ec4SLe Tan  * Copyright (C) 2014 Le Tan, <tamlokveer@gmail.com>
71da12ec4SLe Tan  *
81da12ec4SLe Tan  * This program is free software; you can redistribute it and/or modify
91da12ec4SLe Tan  * it under the terms of the GNU General Public License as published by
101da12ec4SLe Tan  * the Free Software Foundation; either version 2 of the License, or
111da12ec4SLe Tan  * (at your option) any later version.
121da12ec4SLe Tan 
131da12ec4SLe Tan  * This program is distributed in the hope that it will be useful,
141da12ec4SLe Tan  * but WITHOUT ANY WARRANTY; without even the implied warranty of
151da12ec4SLe Tan  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
161da12ec4SLe Tan  * GNU General Public License for more details.
171da12ec4SLe Tan 
181da12ec4SLe Tan  * You should have received a copy of the GNU General Public License along
191da12ec4SLe Tan  * with this program; if not, see <http://www.gnu.org/licenses/>.
201da12ec4SLe Tan  */
211da12ec4SLe Tan 
22b6a0aa05SPeter Maydell #include "qemu/osdep.h"
234684a204SPeter Xu #include "qemu/error-report.h"
24db725815SMarkus Armbruster #include "qemu/main-loop.h"
256333e93cSRadim Krčmář #include "qapi/error.h"
261da12ec4SLe Tan #include "hw/sysbus.h"
271da12ec4SLe Tan #include "intel_iommu_internal.h"
287df953bdSKnut Omang #include "hw/pci/pci.h"
293cb3b154SAlex Williamson #include "hw/pci/pci_bus.h"
30a27bd6c7SMarkus Armbruster #include "hw/qdev-properties.h"
31621d983aSMarcel Apfelbaum #include "hw/i386/pc.h"
32dea651a9SFeng Wu #include "hw/i386/apic-msidef.h"
3304af0e18SPeter Xu #include "hw/i386/x86-iommu.h"
34cb135f59SPeter Xu #include "hw/pci-host/q35.h"
354684a204SPeter Xu #include "sysemu/kvm.h"
36f14fb6c2SEric Auger #include "sysemu/dma.h"
3728cf553aSPeter Xu #include "sysemu/sysemu.h"
3832946019SRadim Krčmář #include "hw/i386/apic_internal.h"
39a9dc68d9SClaudio Fontana #include "kvm/kvm_i386.h"
40d6454270SMarkus Armbruster #include "migration/vmstate.h"
41bc535e59SPeter Xu #include "trace.h"
421da12ec4SLe Tan 
43fb43cf73SLiu, Yi L /* context entry operations */
44fb43cf73SLiu, Yi L #define VTD_CE_GET_RID2PASID(ce) \
45fb43cf73SLiu, Yi L     ((ce)->val[1] & VTD_SM_CONTEXT_ENTRY_RID2PASID_MASK)
46fb43cf73SLiu, Yi L #define VTD_CE_GET_PASID_DIR_TABLE(ce) \
47fb43cf73SLiu, Yi L     ((ce)->val[0] & VTD_PASID_DIR_BASE_ADDR_MASK)
48fb43cf73SLiu, Yi L 
49fb43cf73SLiu, Yi L /* pe operations */
50fb43cf73SLiu, Yi L #define VTD_PE_GET_TYPE(pe) ((pe)->val[0] & VTD_SM_PASID_ENTRY_PGTT)
51fb43cf73SLiu, Yi L #define VTD_PE_GET_LEVEL(pe) (2 + (((pe)->val[0] >> 2) & VTD_SM_PASID_ENTRY_AW))
52fb43cf73SLiu, Yi L 
53da8d439cSJason Wang /*
54da8d439cSJason Wang  * PCI bus number (or SID) is not reliable since the device is usaully
55bad5cfcdSMichael Tokarev  * initialized before guest can configure the PCI bridge
56da8d439cSJason Wang  * (SECONDARY_BUS_NUMBER).
57da8d439cSJason Wang  */
58da8d439cSJason Wang struct vtd_as_key {
59da8d439cSJason Wang     PCIBus *bus;
60da8d439cSJason Wang     uint8_t devfn;
611b2b1237SJason Wang     uint32_t pasid;
621b2b1237SJason Wang };
631b2b1237SJason Wang 
641b2b1237SJason Wang struct vtd_iotlb_key {
651b2b1237SJason Wang     uint64_t gfn;
661b2b1237SJason Wang     uint32_t pasid;
671b2b1237SJason Wang     uint16_t sid;
68ec1a78ceSJason Wang     uint8_t level;
69da8d439cSJason Wang };
70da8d439cSJason Wang 
712cc9ddccSPeter Xu static void vtd_address_space_refresh_all(IntelIOMMUState *s);
72c28b535dSPeter Xu static void vtd_address_space_unmap(VTDAddressSpace *as, IOMMUNotifier *n);
732cc9ddccSPeter Xu 
7428cf553aSPeter Xu static void vtd_panic_require_caching_mode(void)
7528cf553aSPeter Xu {
7628cf553aSPeter Xu     error_report("We need to set caching-mode=on for intel-iommu to enable "
7728cf553aSPeter Xu                  "device assignment with IOMMU protection.");
7828cf553aSPeter Xu     exit(1);
7928cf553aSPeter Xu }
8028cf553aSPeter Xu 
811da12ec4SLe Tan static void vtd_define_quad(IntelIOMMUState *s, hwaddr addr, uint64_t val,
821da12ec4SLe Tan                             uint64_t wmask, uint64_t w1cmask)
831da12ec4SLe Tan {
841da12ec4SLe Tan     stq_le_p(&s->csr[addr], val);
851da12ec4SLe Tan     stq_le_p(&s->wmask[addr], wmask);
861da12ec4SLe Tan     stq_le_p(&s->w1cmask[addr], w1cmask);
871da12ec4SLe Tan }
881da12ec4SLe Tan 
891da12ec4SLe Tan static void vtd_define_quad_wo(IntelIOMMUState *s, hwaddr addr, uint64_t mask)
901da12ec4SLe Tan {
911da12ec4SLe Tan     stq_le_p(&s->womask[addr], mask);
921da12ec4SLe Tan }
931da12ec4SLe Tan 
941da12ec4SLe Tan static void vtd_define_long(IntelIOMMUState *s, hwaddr addr, uint32_t val,
951da12ec4SLe Tan                             uint32_t wmask, uint32_t w1cmask)
961da12ec4SLe Tan {
971da12ec4SLe Tan     stl_le_p(&s->csr[addr], val);
981da12ec4SLe Tan     stl_le_p(&s->wmask[addr], wmask);
991da12ec4SLe Tan     stl_le_p(&s->w1cmask[addr], w1cmask);
1001da12ec4SLe Tan }
1011da12ec4SLe Tan 
1021da12ec4SLe Tan static void vtd_define_long_wo(IntelIOMMUState *s, hwaddr addr, uint32_t mask)
1031da12ec4SLe Tan {
1041da12ec4SLe Tan     stl_le_p(&s->womask[addr], mask);
1051da12ec4SLe Tan }
1061da12ec4SLe Tan 
1071da12ec4SLe Tan /* "External" get/set operations */
1081da12ec4SLe Tan static void vtd_set_quad(IntelIOMMUState *s, hwaddr addr, uint64_t val)
1091da12ec4SLe Tan {
1101da12ec4SLe Tan     uint64_t oldval = ldq_le_p(&s->csr[addr]);
1111da12ec4SLe Tan     uint64_t wmask = ldq_le_p(&s->wmask[addr]);
1121da12ec4SLe Tan     uint64_t w1cmask = ldq_le_p(&s->w1cmask[addr]);
1131da12ec4SLe Tan     stq_le_p(&s->csr[addr],
1141da12ec4SLe Tan              ((oldval & ~wmask) | (val & wmask)) & ~(w1cmask & val));
1151da12ec4SLe Tan }
1161da12ec4SLe Tan 
1171da12ec4SLe Tan static void vtd_set_long(IntelIOMMUState *s, hwaddr addr, uint32_t val)
1181da12ec4SLe Tan {
1191da12ec4SLe Tan     uint32_t oldval = ldl_le_p(&s->csr[addr]);
1201da12ec4SLe Tan     uint32_t wmask = ldl_le_p(&s->wmask[addr]);
1211da12ec4SLe Tan     uint32_t w1cmask = ldl_le_p(&s->w1cmask[addr]);
1221da12ec4SLe Tan     stl_le_p(&s->csr[addr],
1231da12ec4SLe Tan              ((oldval & ~wmask) | (val & wmask)) & ~(w1cmask & val));
1241da12ec4SLe Tan }
1251da12ec4SLe Tan 
1261da12ec4SLe Tan static uint64_t vtd_get_quad(IntelIOMMUState *s, hwaddr addr)
1271da12ec4SLe Tan {
1281da12ec4SLe Tan     uint64_t val = ldq_le_p(&s->csr[addr]);
1291da12ec4SLe Tan     uint64_t womask = ldq_le_p(&s->womask[addr]);
1301da12ec4SLe Tan     return val & ~womask;
1311da12ec4SLe Tan }
1321da12ec4SLe Tan 
1331da12ec4SLe Tan static uint32_t vtd_get_long(IntelIOMMUState *s, hwaddr addr)
1341da12ec4SLe Tan {
1351da12ec4SLe Tan     uint32_t val = ldl_le_p(&s->csr[addr]);
1361da12ec4SLe Tan     uint32_t womask = ldl_le_p(&s->womask[addr]);
1371da12ec4SLe Tan     return val & ~womask;
1381da12ec4SLe Tan }
1391da12ec4SLe Tan 
1401da12ec4SLe Tan /* "Internal" get/set operations */
1411da12ec4SLe Tan static uint64_t vtd_get_quad_raw(IntelIOMMUState *s, hwaddr addr)
1421da12ec4SLe Tan {
1431da12ec4SLe Tan     return ldq_le_p(&s->csr[addr]);
1441da12ec4SLe Tan }
1451da12ec4SLe Tan 
1461da12ec4SLe Tan static uint32_t vtd_get_long_raw(IntelIOMMUState *s, hwaddr addr)
1471da12ec4SLe Tan {
1481da12ec4SLe Tan     return ldl_le_p(&s->csr[addr]);
1491da12ec4SLe Tan }
1501da12ec4SLe Tan 
1511da12ec4SLe Tan static void vtd_set_quad_raw(IntelIOMMUState *s, hwaddr addr, uint64_t val)
1521da12ec4SLe Tan {
1531da12ec4SLe Tan     stq_le_p(&s->csr[addr], val);
1541da12ec4SLe Tan }
1551da12ec4SLe Tan 
1561da12ec4SLe Tan static uint32_t vtd_set_clear_mask_long(IntelIOMMUState *s, hwaddr addr,
1571da12ec4SLe Tan                                         uint32_t clear, uint32_t mask)
1581da12ec4SLe Tan {
1591da12ec4SLe Tan     uint32_t new_val = (ldl_le_p(&s->csr[addr]) & ~clear) | mask;
1601da12ec4SLe Tan     stl_le_p(&s->csr[addr], new_val);
1611da12ec4SLe Tan     return new_val;
1621da12ec4SLe Tan }
1631da12ec4SLe Tan 
1641da12ec4SLe Tan static uint64_t vtd_set_clear_mask_quad(IntelIOMMUState *s, hwaddr addr,
1651da12ec4SLe Tan                                         uint64_t clear, uint64_t mask)
1661da12ec4SLe Tan {
1671da12ec4SLe Tan     uint64_t new_val = (ldq_le_p(&s->csr[addr]) & ~clear) | mask;
1681da12ec4SLe Tan     stq_le_p(&s->csr[addr], new_val);
1691da12ec4SLe Tan     return new_val;
1701da12ec4SLe Tan }
1711da12ec4SLe Tan 
1721d9efa73SPeter Xu static inline void vtd_iommu_lock(IntelIOMMUState *s)
1731d9efa73SPeter Xu {
1741d9efa73SPeter Xu     qemu_mutex_lock(&s->iommu_lock);
1751d9efa73SPeter Xu }
1761d9efa73SPeter Xu 
1771d9efa73SPeter Xu static inline void vtd_iommu_unlock(IntelIOMMUState *s)
1781d9efa73SPeter Xu {
1791d9efa73SPeter Xu     qemu_mutex_unlock(&s->iommu_lock);
1801d9efa73SPeter Xu }
1811d9efa73SPeter Xu 
1822811af3bSPeter Xu static void vtd_update_scalable_state(IntelIOMMUState *s)
1832811af3bSPeter Xu {
1842811af3bSPeter Xu     uint64_t val = vtd_get_quad_raw(s, DMAR_RTADDR_REG);
1852811af3bSPeter Xu 
1862811af3bSPeter Xu     if (s->scalable_mode) {
1872811af3bSPeter Xu         s->root_scalable = val & VTD_RTADDR_SMT;
1882811af3bSPeter Xu     }
1892811af3bSPeter Xu }
1902811af3bSPeter Xu 
191147a372eSJason Wang static void vtd_update_iq_dw(IntelIOMMUState *s)
192147a372eSJason Wang {
193147a372eSJason Wang     uint64_t val = vtd_get_quad_raw(s, DMAR_IQA_REG);
194147a372eSJason Wang 
195147a372eSJason Wang     if (s->ecap & VTD_ECAP_SMTS &&
196147a372eSJason Wang         val & VTD_IQA_DW_MASK) {
197147a372eSJason Wang         s->iq_dw = true;
198147a372eSJason Wang     } else {
199147a372eSJason Wang         s->iq_dw = false;
200147a372eSJason Wang     }
201147a372eSJason Wang }
202147a372eSJason Wang 
2034f8a62a9SPeter Xu /* Whether the address space needs to notify new mappings */
2044f8a62a9SPeter Xu static inline gboolean vtd_as_has_map_notifier(VTDAddressSpace *as)
2054f8a62a9SPeter Xu {
2064f8a62a9SPeter Xu     return as->notifier_flags & IOMMU_NOTIFIER_MAP;
2074f8a62a9SPeter Xu }
2084f8a62a9SPeter Xu 
209b5a280c0SLe Tan /* GHashTable functions */
2101b2b1237SJason Wang static gboolean vtd_iotlb_equal(gconstpointer v1, gconstpointer v2)
211b5a280c0SLe Tan {
2121b2b1237SJason Wang     const struct vtd_iotlb_key *key1 = v1;
2131b2b1237SJason Wang     const struct vtd_iotlb_key *key2 = v2;
2141b2b1237SJason Wang 
2151b2b1237SJason Wang     return key1->sid == key2->sid &&
2161b2b1237SJason Wang            key1->pasid == key2->pasid &&
2171b2b1237SJason Wang            key1->level == key2->level &&
2181b2b1237SJason Wang            key1->gfn == key2->gfn;
219b5a280c0SLe Tan }
220b5a280c0SLe Tan 
2211b2b1237SJason Wang static guint vtd_iotlb_hash(gconstpointer v)
222b5a280c0SLe Tan {
2231b2b1237SJason Wang     const struct vtd_iotlb_key *key = v;
224ec1a78ceSJason Wang     uint64_t hash64 = key->gfn | ((uint64_t)(key->sid) << VTD_IOTLB_SID_SHIFT) |
225ec1a78ceSJason Wang         (uint64_t)(key->level - 1) << VTD_IOTLB_LVL_SHIFT |
226ec1a78ceSJason Wang         (uint64_t)(key->pasid) << VTD_IOTLB_PASID_SHIFT;
2271b2b1237SJason Wang 
228ec1a78ceSJason Wang     return (guint)((hash64 >> 32) ^ (hash64 & 0xffffffffU));
229b5a280c0SLe Tan }
230b5a280c0SLe Tan 
231da8d439cSJason Wang static gboolean vtd_as_equal(gconstpointer v1, gconstpointer v2)
232da8d439cSJason Wang {
233da8d439cSJason Wang     const struct vtd_as_key *key1 = v1;
234da8d439cSJason Wang     const struct vtd_as_key *key2 = v2;
235da8d439cSJason Wang 
2361b2b1237SJason Wang     return (key1->bus == key2->bus) && (key1->devfn == key2->devfn) &&
2371b2b1237SJason Wang            (key1->pasid == key2->pasid);
238da8d439cSJason Wang }
239da8d439cSJason Wang 
240da8d439cSJason Wang /*
241da8d439cSJason Wang  * Note that we use pointer to PCIBus as the key, so hashing/shifting
242da8d439cSJason Wang  * based on the pointer value is intended. Note that we deal with
243da8d439cSJason Wang  * collisions through vtd_as_equal().
244da8d439cSJason Wang  */
245da8d439cSJason Wang static guint vtd_as_hash(gconstpointer v)
246da8d439cSJason Wang {
247da8d439cSJason Wang     const struct vtd_as_key *key = v;
248da8d439cSJason Wang     guint value = (guint)(uintptr_t)key->bus;
249da8d439cSJason Wang 
250da8d439cSJason Wang     return (guint)(value << 8 | key->devfn);
251da8d439cSJason Wang }
252da8d439cSJason Wang 
253b5a280c0SLe Tan static gboolean vtd_hash_remove_by_domain(gpointer key, gpointer value,
254b5a280c0SLe Tan                                           gpointer user_data)
255b5a280c0SLe Tan {
256b5a280c0SLe Tan     VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value;
257b5a280c0SLe Tan     uint16_t domain_id = *(uint16_t *)user_data;
258b5a280c0SLe Tan     return entry->domain_id == domain_id;
259b5a280c0SLe Tan }
260b5a280c0SLe Tan 
261d66b969bSJason Wang /* The shift of an addr for a certain level of paging structure */
262d66b969bSJason Wang static inline uint32_t vtd_slpt_level_shift(uint32_t level)
263d66b969bSJason Wang {
2647e58326aSPeter Xu     assert(level != 0);
265d66b969bSJason Wang     return VTD_PAGE_SHIFT_4K + (level - 1) * VTD_SL_LEVEL_BITS;
266d66b969bSJason Wang }
267d66b969bSJason Wang 
268d66b969bSJason Wang static inline uint64_t vtd_slpt_level_page_mask(uint32_t level)
269d66b969bSJason Wang {
270d66b969bSJason Wang     return ~((1ULL << vtd_slpt_level_shift(level)) - 1);
271d66b969bSJason Wang }
272d66b969bSJason Wang 
273b5a280c0SLe Tan static gboolean vtd_hash_remove_by_page(gpointer key, gpointer value,
274b5a280c0SLe Tan                                         gpointer user_data)
275b5a280c0SLe Tan {
276b5a280c0SLe Tan     VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value;
277b5a280c0SLe Tan     VTDIOTLBPageInvInfo *info = (VTDIOTLBPageInvInfo *)user_data;
278d66b969bSJason Wang     uint64_t gfn = (info->addr >> VTD_PAGE_SHIFT_4K) & info->mask;
279d66b969bSJason Wang     uint64_t gfn_tlb = (info->addr & entry->mask) >> VTD_PAGE_SHIFT_4K;
280b5a280c0SLe Tan     return (entry->domain_id == info->domain_id) &&
281d66b969bSJason Wang             (((entry->gfn & info->mask) == gfn) ||
282d66b969bSJason Wang              (entry->gfn == gfn_tlb));
283b5a280c0SLe Tan }
284b5a280c0SLe Tan 
285d92fa2dcSLe Tan /* Reset all the gen of VTDAddressSpace to zero and set the gen of
2861d9efa73SPeter Xu  * IntelIOMMUState to 1.  Must be called with IOMMU lock held.
287d92fa2dcSLe Tan  */
2881d9efa73SPeter Xu static void vtd_reset_context_cache_locked(IntelIOMMUState *s)
289d92fa2dcSLe Tan {
290d92fa2dcSLe Tan     VTDAddressSpace *vtd_as;
291da8d439cSJason Wang     GHashTableIter as_it;
292d92fa2dcSLe Tan 
2937feb51b7SPeter Xu     trace_vtd_context_cache_reset();
2947feb51b7SPeter Xu 
295da8d439cSJason Wang     g_hash_table_iter_init(&as_it, s->vtd_address_spaces);
2967df953bdSKnut Omang 
297da8d439cSJason Wang     while (g_hash_table_iter_next(&as_it, NULL, (void **)&vtd_as)) {
298d92fa2dcSLe Tan         vtd_as->context_cache_entry.context_cache_gen = 0;
299d92fa2dcSLe Tan     }
300d92fa2dcSLe Tan     s->context_cache_gen = 1;
301d92fa2dcSLe Tan }
302d92fa2dcSLe Tan 
3031d9efa73SPeter Xu /* Must be called with IOMMU lock held. */
3041d9efa73SPeter Xu static void vtd_reset_iotlb_locked(IntelIOMMUState *s)
305b5a280c0SLe Tan {
306b5a280c0SLe Tan     assert(s->iotlb);
307b5a280c0SLe Tan     g_hash_table_remove_all(s->iotlb);
308b5a280c0SLe Tan }
309b5a280c0SLe Tan 
3101d9efa73SPeter Xu static void vtd_reset_iotlb(IntelIOMMUState *s)
3111d9efa73SPeter Xu {
3121d9efa73SPeter Xu     vtd_iommu_lock(s);
3131d9efa73SPeter Xu     vtd_reset_iotlb_locked(s);
3141d9efa73SPeter Xu     vtd_iommu_unlock(s);
3151d9efa73SPeter Xu }
3161d9efa73SPeter Xu 
31706aba4caSPeter Xu static void vtd_reset_caches(IntelIOMMUState *s)
31806aba4caSPeter Xu {
31906aba4caSPeter Xu     vtd_iommu_lock(s);
32006aba4caSPeter Xu     vtd_reset_iotlb_locked(s);
32106aba4caSPeter Xu     vtd_reset_context_cache_locked(s);
32206aba4caSPeter Xu     vtd_iommu_unlock(s);
32306aba4caSPeter Xu }
32406aba4caSPeter Xu 
325d66b969bSJason Wang static uint64_t vtd_get_iotlb_gfn(hwaddr addr, uint32_t level)
326d66b969bSJason Wang {
327d66b969bSJason Wang     return (addr & vtd_slpt_level_page_mask(level)) >> VTD_PAGE_SHIFT_4K;
328d66b969bSJason Wang }
329d66b969bSJason Wang 
3301d9efa73SPeter Xu /* Must be called with IOMMU lock held */
331b5a280c0SLe Tan static VTDIOTLBEntry *vtd_lookup_iotlb(IntelIOMMUState *s, uint16_t source_id,
3321b2b1237SJason Wang                                        uint32_t pasid, hwaddr addr)
333b5a280c0SLe Tan {
3341b2b1237SJason Wang     struct vtd_iotlb_key key;
335d66b969bSJason Wang     VTDIOTLBEntry *entry;
336d66b969bSJason Wang     int level;
337b5a280c0SLe Tan 
338d66b969bSJason Wang     for (level = VTD_SL_PT_LEVEL; level < VTD_SL_PML4_LEVEL; level++) {
3391b2b1237SJason Wang         key.gfn = vtd_get_iotlb_gfn(addr, level);
3401b2b1237SJason Wang         key.level = level;
3411b2b1237SJason Wang         key.sid = source_id;
3421b2b1237SJason Wang         key.pasid = pasid;
343d66b969bSJason Wang         entry = g_hash_table_lookup(s->iotlb, &key);
344d66b969bSJason Wang         if (entry) {
345d66b969bSJason Wang             goto out;
346d66b969bSJason Wang         }
347d66b969bSJason Wang     }
348b5a280c0SLe Tan 
349d66b969bSJason Wang out:
350d66b969bSJason Wang     return entry;
351b5a280c0SLe Tan }
352b5a280c0SLe Tan 
3531d9efa73SPeter Xu /* Must be with IOMMU lock held */
354b5a280c0SLe Tan static void vtd_update_iotlb(IntelIOMMUState *s, uint16_t source_id,
355b5a280c0SLe Tan                              uint16_t domain_id, hwaddr addr, uint64_t slpte,
3561b2b1237SJason Wang                              uint8_t access_flags, uint32_t level,
3571b2b1237SJason Wang                              uint32_t pasid)
358b5a280c0SLe Tan {
359b5a280c0SLe Tan     VTDIOTLBEntry *entry = g_malloc(sizeof(*entry));
3601b2b1237SJason Wang     struct vtd_iotlb_key *key = g_malloc(sizeof(*key));
361d66b969bSJason Wang     uint64_t gfn = vtd_get_iotlb_gfn(addr, level);
362b5a280c0SLe Tan 
3636c441e1dSPeter Xu     trace_vtd_iotlb_page_update(source_id, addr, slpte, domain_id);
364b5a280c0SLe Tan     if (g_hash_table_size(s->iotlb) >= VTD_IOTLB_MAX_SIZE) {
3656c441e1dSPeter Xu         trace_vtd_iotlb_reset("iotlb exceeds size limit");
3661d9efa73SPeter Xu         vtd_reset_iotlb_locked(s);
367b5a280c0SLe Tan     }
368b5a280c0SLe Tan 
369b5a280c0SLe Tan     entry->gfn = gfn;
370b5a280c0SLe Tan     entry->domain_id = domain_id;
371b5a280c0SLe Tan     entry->slpte = slpte;
37207f7b733SPeter Xu     entry->access_flags = access_flags;
373d66b969bSJason Wang     entry->mask = vtd_slpt_level_page_mask(level);
3741b2b1237SJason Wang     entry->pasid = pasid;
3751b2b1237SJason Wang 
3761b2b1237SJason Wang     key->gfn = gfn;
3771b2b1237SJason Wang     key->sid = source_id;
3781b2b1237SJason Wang     key->level = level;
3791b2b1237SJason Wang     key->pasid = pasid;
3801b2b1237SJason Wang 
381b5a280c0SLe Tan     g_hash_table_replace(s->iotlb, key, entry);
382b5a280c0SLe Tan }
383b5a280c0SLe Tan 
3841da12ec4SLe Tan /* Given the reg addr of both the message data and address, generate an
3851da12ec4SLe Tan  * interrupt via MSI.
3861da12ec4SLe Tan  */
3871da12ec4SLe Tan static void vtd_generate_interrupt(IntelIOMMUState *s, hwaddr mesg_addr_reg,
3881da12ec4SLe Tan                                    hwaddr mesg_data_reg)
3891da12ec4SLe Tan {
39032946019SRadim Krčmář     MSIMessage msi;
3911da12ec4SLe Tan 
3921da12ec4SLe Tan     assert(mesg_data_reg < DMAR_REG_SIZE);
3931da12ec4SLe Tan     assert(mesg_addr_reg < DMAR_REG_SIZE);
3941da12ec4SLe Tan 
39532946019SRadim Krčmář     msi.address = vtd_get_long_raw(s, mesg_addr_reg);
39632946019SRadim Krčmář     msi.data = vtd_get_long_raw(s, mesg_data_reg);
3971da12ec4SLe Tan 
3987feb51b7SPeter Xu     trace_vtd_irq_generate(msi.address, msi.data);
3997feb51b7SPeter Xu 
400eaaaf8abSPaolo Bonzini     apic_get_class(NULL)->send_msi(&msi);
4011da12ec4SLe Tan }
4021da12ec4SLe Tan 
4031da12ec4SLe Tan /* Generate a fault event to software via MSI if conditions are met.
4041da12ec4SLe Tan  * Notice that the value of FSTS_REG being passed to it should be the one
4051da12ec4SLe Tan  * before any update.
4061da12ec4SLe Tan  */
4071da12ec4SLe Tan static void vtd_generate_fault_event(IntelIOMMUState *s, uint32_t pre_fsts)
4081da12ec4SLe Tan {
4091da12ec4SLe Tan     if (pre_fsts & VTD_FSTS_PPF || pre_fsts & VTD_FSTS_PFO ||
4101da12ec4SLe Tan         pre_fsts & VTD_FSTS_IQE) {
4111376211fSPeter Xu         error_report_once("There are previous interrupt conditions "
4127feb51b7SPeter Xu                           "to be serviced by software, fault event "
4131376211fSPeter Xu                           "is not generated");
4141da12ec4SLe Tan         return;
4151da12ec4SLe Tan     }
4161da12ec4SLe Tan     vtd_set_clear_mask_long(s, DMAR_FECTL_REG, 0, VTD_FECTL_IP);
4171da12ec4SLe Tan     if (vtd_get_long_raw(s, DMAR_FECTL_REG) & VTD_FECTL_IM) {
4181376211fSPeter Xu         error_report_once("Interrupt Mask set, irq is not generated");
4191da12ec4SLe Tan     } else {
4201da12ec4SLe Tan         vtd_generate_interrupt(s, DMAR_FEADDR_REG, DMAR_FEDATA_REG);
4211da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
4221da12ec4SLe Tan     }
4231da12ec4SLe Tan }
4241da12ec4SLe Tan 
4251da12ec4SLe Tan /* Check if the Fault (F) field of the Fault Recording Register referenced by
4261da12ec4SLe Tan  * @index is Set.
4271da12ec4SLe Tan  */
4281da12ec4SLe Tan static bool vtd_is_frcd_set(IntelIOMMUState *s, uint16_t index)
4291da12ec4SLe Tan {
4301da12ec4SLe Tan     /* Each reg is 128-bit */
4311da12ec4SLe Tan     hwaddr addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
4321da12ec4SLe Tan     addr += 8; /* Access the high 64-bit half */
4331da12ec4SLe Tan 
4341da12ec4SLe Tan     assert(index < DMAR_FRCD_REG_NR);
4351da12ec4SLe Tan 
4361da12ec4SLe Tan     return vtd_get_quad_raw(s, addr) & VTD_FRCD_F;
4371da12ec4SLe Tan }
4381da12ec4SLe Tan 
4391da12ec4SLe Tan /* Update the PPF field of Fault Status Register.
4401da12ec4SLe Tan  * Should be called whenever change the F field of any fault recording
4411da12ec4SLe Tan  * registers.
4421da12ec4SLe Tan  */
4431da12ec4SLe Tan static void vtd_update_fsts_ppf(IntelIOMMUState *s)
4441da12ec4SLe Tan {
4451da12ec4SLe Tan     uint32_t i;
4461da12ec4SLe Tan     uint32_t ppf_mask = 0;
4471da12ec4SLe Tan 
4481da12ec4SLe Tan     for (i = 0; i < DMAR_FRCD_REG_NR; i++) {
4491da12ec4SLe Tan         if (vtd_is_frcd_set(s, i)) {
4501da12ec4SLe Tan             ppf_mask = VTD_FSTS_PPF;
4511da12ec4SLe Tan             break;
4521da12ec4SLe Tan         }
4531da12ec4SLe Tan     }
4541da12ec4SLe Tan     vtd_set_clear_mask_long(s, DMAR_FSTS_REG, VTD_FSTS_PPF, ppf_mask);
4557feb51b7SPeter Xu     trace_vtd_fsts_ppf(!!ppf_mask);
4561da12ec4SLe Tan }
4571da12ec4SLe Tan 
4581da12ec4SLe Tan static void vtd_set_frcd_and_update_ppf(IntelIOMMUState *s, uint16_t index)
4591da12ec4SLe Tan {
4601da12ec4SLe Tan     /* Each reg is 128-bit */
4611da12ec4SLe Tan     hwaddr addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
4621da12ec4SLe Tan     addr += 8; /* Access the high 64-bit half */
4631da12ec4SLe Tan 
4641da12ec4SLe Tan     assert(index < DMAR_FRCD_REG_NR);
4651da12ec4SLe Tan 
4661da12ec4SLe Tan     vtd_set_clear_mask_quad(s, addr, 0, VTD_FRCD_F);
4671da12ec4SLe Tan     vtd_update_fsts_ppf(s);
4681da12ec4SLe Tan }
4691da12ec4SLe Tan 
4701da12ec4SLe Tan /* Must not update F field now, should be done later */
4711da12ec4SLe Tan static void vtd_record_frcd(IntelIOMMUState *s, uint16_t index,
472c7016bf7SDavid Woodhouse                             uint64_t hi, uint64_t lo)
4731da12ec4SLe Tan {
4741da12ec4SLe Tan     hwaddr frcd_reg_addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
4751da12ec4SLe Tan 
4761da12ec4SLe Tan     assert(index < DMAR_FRCD_REG_NR);
4771da12ec4SLe Tan 
4781da12ec4SLe Tan     vtd_set_quad_raw(s, frcd_reg_addr, lo);
4791da12ec4SLe Tan     vtd_set_quad_raw(s, frcd_reg_addr + 8, hi);
4807feb51b7SPeter Xu 
4817feb51b7SPeter Xu     trace_vtd_frr_new(index, hi, lo);
4821da12ec4SLe Tan }
4831da12ec4SLe Tan 
4841da12ec4SLe Tan /* Try to collapse multiple pending faults from the same requester */
4851da12ec4SLe Tan static bool vtd_try_collapse_fault(IntelIOMMUState *s, uint16_t source_id)
4861da12ec4SLe Tan {
4871da12ec4SLe Tan     uint32_t i;
4881da12ec4SLe Tan     uint64_t frcd_reg;
4891da12ec4SLe Tan     hwaddr addr = DMAR_FRCD_REG_OFFSET + 8; /* The high 64-bit half */
4901da12ec4SLe Tan 
4911da12ec4SLe Tan     for (i = 0; i < DMAR_FRCD_REG_NR; i++) {
4921da12ec4SLe Tan         frcd_reg = vtd_get_quad_raw(s, addr);
4931da12ec4SLe Tan         if ((frcd_reg & VTD_FRCD_F) &&
4941da12ec4SLe Tan             ((frcd_reg & VTD_FRCD_SID_MASK) == source_id)) {
4951da12ec4SLe Tan             return true;
4961da12ec4SLe Tan         }
4971da12ec4SLe Tan         addr += 16; /* 128-bit for each */
4981da12ec4SLe Tan     }
4991da12ec4SLe Tan     return false;
5001da12ec4SLe Tan }
5011da12ec4SLe Tan 
5021da12ec4SLe Tan /* Log and report an DMAR (address translation) fault to software */
503c7016bf7SDavid Woodhouse static void vtd_report_frcd_fault(IntelIOMMUState *s, uint64_t source_id,
504c7016bf7SDavid Woodhouse                                   uint64_t hi, uint64_t lo)
5051da12ec4SLe Tan {
5061da12ec4SLe Tan     uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
5071da12ec4SLe Tan 
5081da12ec4SLe Tan     if (fsts_reg & VTD_FSTS_PFO) {
5091376211fSPeter Xu         error_report_once("New fault is not recorded due to "
5101376211fSPeter Xu                           "Primary Fault Overflow");
5111da12ec4SLe Tan         return;
5121da12ec4SLe Tan     }
5137feb51b7SPeter Xu 
5141da12ec4SLe Tan     if (vtd_try_collapse_fault(s, source_id)) {
5151376211fSPeter Xu         error_report_once("New fault is not recorded due to "
5161376211fSPeter Xu                           "compression of faults");
5171da12ec4SLe Tan         return;
5181da12ec4SLe Tan     }
5197feb51b7SPeter Xu 
5201da12ec4SLe Tan     if (vtd_is_frcd_set(s, s->next_frcd_reg)) {
5211376211fSPeter Xu         error_report_once("Next Fault Recording Reg is used, "
5221376211fSPeter Xu                           "new fault is not recorded, set PFO field");
5231da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_FSTS_REG, 0, VTD_FSTS_PFO);
5241da12ec4SLe Tan         return;
5251da12ec4SLe Tan     }
5261da12ec4SLe Tan 
527c7016bf7SDavid Woodhouse     vtd_record_frcd(s, s->next_frcd_reg, hi, lo);
5281da12ec4SLe Tan 
5291da12ec4SLe Tan     if (fsts_reg & VTD_FSTS_PPF) {
5301376211fSPeter Xu         error_report_once("There are pending faults already, "
5311376211fSPeter Xu                           "fault event is not generated");
5321da12ec4SLe Tan         vtd_set_frcd_and_update_ppf(s, s->next_frcd_reg);
5331da12ec4SLe Tan         s->next_frcd_reg++;
5341da12ec4SLe Tan         if (s->next_frcd_reg == DMAR_FRCD_REG_NR) {
5351da12ec4SLe Tan             s->next_frcd_reg = 0;
5361da12ec4SLe Tan         }
5371da12ec4SLe Tan     } else {
5381da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_FSTS_REG, VTD_FSTS_FRI_MASK,
5391da12ec4SLe Tan                                 VTD_FSTS_FRI(s->next_frcd_reg));
5401da12ec4SLe Tan         vtd_set_frcd_and_update_ppf(s, s->next_frcd_reg); /* Will set PPF */
5411da12ec4SLe Tan         s->next_frcd_reg++;
5421da12ec4SLe Tan         if (s->next_frcd_reg == DMAR_FRCD_REG_NR) {
5431da12ec4SLe Tan             s->next_frcd_reg = 0;
5441da12ec4SLe Tan         }
5451da12ec4SLe Tan         /* This case actually cause the PPF to be Set.
5461da12ec4SLe Tan          * So generate fault event (interrupt).
5471da12ec4SLe Tan          */
5481da12ec4SLe Tan          vtd_generate_fault_event(s, fsts_reg);
5491da12ec4SLe Tan     }
5501da12ec4SLe Tan }
5511da12ec4SLe Tan 
552c7016bf7SDavid Woodhouse /* Log and report an DMAR (address translation) fault to software */
553c7016bf7SDavid Woodhouse static void vtd_report_dmar_fault(IntelIOMMUState *s, uint16_t source_id,
554c7016bf7SDavid Woodhouse                                   hwaddr addr, VTDFaultReason fault,
555c7016bf7SDavid Woodhouse                                   bool is_write, bool is_pasid,
556c7016bf7SDavid Woodhouse                                   uint32_t pasid)
557c7016bf7SDavid Woodhouse {
558c7016bf7SDavid Woodhouse     uint64_t hi, lo;
559c7016bf7SDavid Woodhouse 
560c7016bf7SDavid Woodhouse     assert(fault < VTD_FR_MAX);
561c7016bf7SDavid Woodhouse 
562c7016bf7SDavid Woodhouse     trace_vtd_dmar_fault(source_id, fault, addr, is_write);
563c7016bf7SDavid Woodhouse 
564c7016bf7SDavid Woodhouse     lo = VTD_FRCD_FI(addr);
565c7016bf7SDavid Woodhouse     hi = VTD_FRCD_SID(source_id) | VTD_FRCD_FR(fault) |
566c7016bf7SDavid Woodhouse          VTD_FRCD_PV(pasid) | VTD_FRCD_PP(is_pasid);
567c7016bf7SDavid Woodhouse     if (!is_write) {
568c7016bf7SDavid Woodhouse         hi |= VTD_FRCD_T;
569c7016bf7SDavid Woodhouse     }
570c7016bf7SDavid Woodhouse 
571c7016bf7SDavid Woodhouse     vtd_report_frcd_fault(s, source_id, hi, lo);
572c7016bf7SDavid Woodhouse }
573c7016bf7SDavid Woodhouse 
574c7016bf7SDavid Woodhouse 
575c7016bf7SDavid Woodhouse static void vtd_report_ir_fault(IntelIOMMUState *s, uint64_t source_id,
576c7016bf7SDavid Woodhouse                                 VTDFaultReason fault, uint16_t index)
577c7016bf7SDavid Woodhouse {
578c7016bf7SDavid Woodhouse     uint64_t hi, lo;
579c7016bf7SDavid Woodhouse 
580c7016bf7SDavid Woodhouse     lo = VTD_FRCD_IR_IDX(index);
581c7016bf7SDavid Woodhouse     hi = VTD_FRCD_SID(source_id) | VTD_FRCD_FR(fault);
582c7016bf7SDavid Woodhouse 
583c7016bf7SDavid Woodhouse     vtd_report_frcd_fault(s, source_id, hi, lo);
584c7016bf7SDavid Woodhouse }
585c7016bf7SDavid Woodhouse 
586ed7b8fbcSLe Tan /* Handle Invalidation Queue Errors of queued invalidation interface error
587ed7b8fbcSLe Tan  * conditions.
588ed7b8fbcSLe Tan  */
589ed7b8fbcSLe Tan static void vtd_handle_inv_queue_error(IntelIOMMUState *s)
590ed7b8fbcSLe Tan {
591ed7b8fbcSLe Tan     uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
592ed7b8fbcSLe Tan 
593ed7b8fbcSLe Tan     vtd_set_clear_mask_long(s, DMAR_FSTS_REG, 0, VTD_FSTS_IQE);
594ed7b8fbcSLe Tan     vtd_generate_fault_event(s, fsts_reg);
595ed7b8fbcSLe Tan }
596ed7b8fbcSLe Tan 
597ed7b8fbcSLe Tan /* Set the IWC field and try to generate an invalidation completion interrupt */
598ed7b8fbcSLe Tan static void vtd_generate_completion_event(IntelIOMMUState *s)
599ed7b8fbcSLe Tan {
600ed7b8fbcSLe Tan     if (vtd_get_long_raw(s, DMAR_ICS_REG) & VTD_ICS_IWC) {
601bc535e59SPeter Xu         trace_vtd_inv_desc_wait_irq("One pending, skip current");
602ed7b8fbcSLe Tan         return;
603ed7b8fbcSLe Tan     }
604ed7b8fbcSLe Tan     vtd_set_clear_mask_long(s, DMAR_ICS_REG, 0, VTD_ICS_IWC);
605ed7b8fbcSLe Tan     vtd_set_clear_mask_long(s, DMAR_IECTL_REG, 0, VTD_IECTL_IP);
606ed7b8fbcSLe Tan     if (vtd_get_long_raw(s, DMAR_IECTL_REG) & VTD_IECTL_IM) {
607bc535e59SPeter Xu         trace_vtd_inv_desc_wait_irq("IM in IECTL_REG is set, "
608bc535e59SPeter Xu                                     "new event not generated");
609ed7b8fbcSLe Tan         return;
610ed7b8fbcSLe Tan     } else {
611ed7b8fbcSLe Tan         /* Generate the interrupt event */
612bc535e59SPeter Xu         trace_vtd_inv_desc_wait_irq("Generating complete event");
613ed7b8fbcSLe Tan         vtd_generate_interrupt(s, DMAR_IEADDR_REG, DMAR_IEDATA_REG);
614ed7b8fbcSLe Tan         vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
615ed7b8fbcSLe Tan     }
616ed7b8fbcSLe Tan }
617ed7b8fbcSLe Tan 
618fb43cf73SLiu, Yi L static inline bool vtd_root_entry_present(IntelIOMMUState *s,
619fb43cf73SLiu, Yi L                                           VTDRootEntry *re,
620fb43cf73SLiu, Yi L                                           uint8_t devfn)
6211da12ec4SLe Tan {
622fb43cf73SLiu, Yi L     if (s->root_scalable && devfn > UINT8_MAX / 2) {
623fb43cf73SLiu, Yi L         return re->hi & VTD_ROOT_ENTRY_P;
624fb43cf73SLiu, Yi L     }
625fb43cf73SLiu, Yi L 
626fb43cf73SLiu, Yi L     return re->lo & VTD_ROOT_ENTRY_P;
6271da12ec4SLe Tan }
6281da12ec4SLe Tan 
6291da12ec4SLe Tan static int vtd_get_root_entry(IntelIOMMUState *s, uint8_t index,
6301da12ec4SLe Tan                               VTDRootEntry *re)
6311da12ec4SLe Tan {
6321da12ec4SLe Tan     dma_addr_t addr;
6331da12ec4SLe Tan 
6341da12ec4SLe Tan     addr = s->root + index * sizeof(*re);
635ba06fe8aSPhilippe Mathieu-Daudé     if (dma_memory_read(&address_space_memory, addr,
636ba06fe8aSPhilippe Mathieu-Daudé                         re, sizeof(*re), MEMTXATTRS_UNSPECIFIED)) {
637fb43cf73SLiu, Yi L         re->lo = 0;
6381da12ec4SLe Tan         return -VTD_FR_ROOT_TABLE_INV;
6391da12ec4SLe Tan     }
640fb43cf73SLiu, Yi L     re->lo = le64_to_cpu(re->lo);
641fb43cf73SLiu, Yi L     re->hi = le64_to_cpu(re->hi);
6421da12ec4SLe Tan     return 0;
6431da12ec4SLe Tan }
6441da12ec4SLe Tan 
6458f7d7161SPeter Xu static inline bool vtd_ce_present(VTDContextEntry *context)
6461da12ec4SLe Tan {
6471da12ec4SLe Tan     return context->lo & VTD_CONTEXT_ENTRY_P;
6481da12ec4SLe Tan }
6491da12ec4SLe Tan 
650fb43cf73SLiu, Yi L static int vtd_get_context_entry_from_root(IntelIOMMUState *s,
651fb43cf73SLiu, Yi L                                            VTDRootEntry *re,
652fb43cf73SLiu, Yi L                                            uint8_t index,
6531da12ec4SLe Tan                                            VTDContextEntry *ce)
6541da12ec4SLe Tan {
655fb43cf73SLiu, Yi L     dma_addr_t addr, ce_size;
6561da12ec4SLe Tan 
6576c441e1dSPeter Xu     /* we have checked that root entry is present */
658fb43cf73SLiu, Yi L     ce_size = s->root_scalable ? VTD_CTX_ENTRY_SCALABLE_SIZE :
659fb43cf73SLiu, Yi L               VTD_CTX_ENTRY_LEGACY_SIZE;
660fb43cf73SLiu, Yi L 
661fb43cf73SLiu, Yi L     if (s->root_scalable && index > UINT8_MAX / 2) {
662fb43cf73SLiu, Yi L         index = index & (~VTD_DEVFN_CHECK_MASK);
663fb43cf73SLiu, Yi L         addr = re->hi & VTD_ROOT_ENTRY_CTP;
664fb43cf73SLiu, Yi L     } else {
665fb43cf73SLiu, Yi L         addr = re->lo & VTD_ROOT_ENTRY_CTP;
666fb43cf73SLiu, Yi L     }
667fb43cf73SLiu, Yi L 
668fb43cf73SLiu, Yi L     addr = addr + index * ce_size;
669ba06fe8aSPhilippe Mathieu-Daudé     if (dma_memory_read(&address_space_memory, addr,
670ba06fe8aSPhilippe Mathieu-Daudé                         ce, ce_size, MEMTXATTRS_UNSPECIFIED)) {
6711da12ec4SLe Tan         return -VTD_FR_CONTEXT_TABLE_INV;
6721da12ec4SLe Tan     }
673fb43cf73SLiu, Yi L 
6741da12ec4SLe Tan     ce->lo = le64_to_cpu(ce->lo);
6751da12ec4SLe Tan     ce->hi = le64_to_cpu(ce->hi);
676fb43cf73SLiu, Yi L     if (ce_size == VTD_CTX_ENTRY_SCALABLE_SIZE) {
677fb43cf73SLiu, Yi L         ce->val[2] = le64_to_cpu(ce->val[2]);
678fb43cf73SLiu, Yi L         ce->val[3] = le64_to_cpu(ce->val[3]);
679fb43cf73SLiu, Yi L     }
6801da12ec4SLe Tan     return 0;
6811da12ec4SLe Tan }
6821da12ec4SLe Tan 
6838f7d7161SPeter Xu static inline dma_addr_t vtd_ce_get_slpt_base(VTDContextEntry *ce)
6841da12ec4SLe Tan {
6851da12ec4SLe Tan     return ce->lo & VTD_CONTEXT_ENTRY_SLPTPTR;
6861da12ec4SLe Tan }
6871da12ec4SLe Tan 
68837f51384SPrasad Singamsetty static inline uint64_t vtd_get_slpte_addr(uint64_t slpte, uint8_t aw)
6891da12ec4SLe Tan {
69037f51384SPrasad Singamsetty     return slpte & VTD_SL_PT_BASE_ADDR_MASK(aw);
6911da12ec4SLe Tan }
6921da12ec4SLe Tan 
6931da12ec4SLe Tan /* Whether the pte indicates the address of the page frame */
6941da12ec4SLe Tan static inline bool vtd_is_last_slpte(uint64_t slpte, uint32_t level)
6951da12ec4SLe Tan {
6961da12ec4SLe Tan     return level == VTD_SL_PT_LEVEL || (slpte & VTD_SL_PT_PAGE_SIZE_MASK);
6971da12ec4SLe Tan }
6981da12ec4SLe Tan 
6991da12ec4SLe Tan /* Get the content of a spte located in @base_addr[@index] */
7001da12ec4SLe Tan static uint64_t vtd_get_slpte(dma_addr_t base_addr, uint32_t index)
7011da12ec4SLe Tan {
7021da12ec4SLe Tan     uint64_t slpte;
7031da12ec4SLe Tan 
7041da12ec4SLe Tan     assert(index < VTD_SL_PT_ENTRY_NR);
7051da12ec4SLe Tan 
7061da12ec4SLe Tan     if (dma_memory_read(&address_space_memory,
707ba06fe8aSPhilippe Mathieu-Daudé                         base_addr + index * sizeof(slpte),
708ba06fe8aSPhilippe Mathieu-Daudé                         &slpte, sizeof(slpte), MEMTXATTRS_UNSPECIFIED)) {
7091da12ec4SLe Tan         slpte = (uint64_t)-1;
7101da12ec4SLe Tan         return slpte;
7111da12ec4SLe Tan     }
7121da12ec4SLe Tan     slpte = le64_to_cpu(slpte);
7131da12ec4SLe Tan     return slpte;
7141da12ec4SLe Tan }
7151da12ec4SLe Tan 
7166e905564SPeter Xu /* Given an iova and the level of paging structure, return the offset
7176e905564SPeter Xu  * of current level.
7181da12ec4SLe Tan  */
7196e905564SPeter Xu static inline uint32_t vtd_iova_level_offset(uint64_t iova, uint32_t level)
7201da12ec4SLe Tan {
7216e905564SPeter Xu     return (iova >> vtd_slpt_level_shift(level)) &
7221da12ec4SLe Tan             ((1ULL << VTD_SL_LEVEL_BITS) - 1);
7231da12ec4SLe Tan }
7241da12ec4SLe Tan 
7251da12ec4SLe Tan /* Check Capability Register to see if the @level of page-table is supported */
7261da12ec4SLe Tan static inline bool vtd_is_level_supported(IntelIOMMUState *s, uint32_t level)
7271da12ec4SLe Tan {
7281da12ec4SLe Tan     return VTD_CAP_SAGAW_MASK & s->cap &
7291da12ec4SLe Tan            (1ULL << (level - 2 + VTD_CAP_SAGAW_SHIFT));
7301da12ec4SLe Tan }
7311da12ec4SLe Tan 
732fb43cf73SLiu, Yi L /* Return true if check passed, otherwise false */
733fb43cf73SLiu, Yi L static inline bool vtd_pe_type_check(X86IOMMUState *x86_iommu,
734fb43cf73SLiu, Yi L                                      VTDPASIDEntry *pe)
735fb43cf73SLiu, Yi L {
736fb43cf73SLiu, Yi L     switch (VTD_PE_GET_TYPE(pe)) {
737fb43cf73SLiu, Yi L     case VTD_SM_PASID_ENTRY_FLT:
738fb43cf73SLiu, Yi L     case VTD_SM_PASID_ENTRY_SLT:
739fb43cf73SLiu, Yi L     case VTD_SM_PASID_ENTRY_NESTED:
740fb43cf73SLiu, Yi L         break;
741fb43cf73SLiu, Yi L     case VTD_SM_PASID_ENTRY_PT:
742fb43cf73SLiu, Yi L         if (!x86_iommu->pt_supported) {
743fb43cf73SLiu, Yi L             return false;
744fb43cf73SLiu, Yi L         }
745fb43cf73SLiu, Yi L         break;
746fb43cf73SLiu, Yi L     default:
74737557b09SCai Huoqing         /* Unknown type */
748fb43cf73SLiu, Yi L         return false;
749fb43cf73SLiu, Yi L     }
750fb43cf73SLiu, Yi L     return true;
751fb43cf73SLiu, Yi L }
752fb43cf73SLiu, Yi L 
75356fc1e6aSLiu Yi L static inline bool vtd_pdire_present(VTDPASIDDirEntry *pdire)
75456fc1e6aSLiu Yi L {
75556fc1e6aSLiu Yi L     return pdire->val & 1;
75656fc1e6aSLiu Yi L }
75756fc1e6aSLiu Yi L 
75856fc1e6aSLiu Yi L /**
75956fc1e6aSLiu Yi L  * Caller of this function should check present bit if wants
76037557b09SCai Huoqing  * to use pdir entry for further usage except for fpd bit check.
76156fc1e6aSLiu Yi L  */
76256fc1e6aSLiu Yi L static int vtd_get_pdire_from_pdir_table(dma_addr_t pasid_dir_base,
763fb43cf73SLiu, Yi L                                          uint32_t pasid,
764fb43cf73SLiu, Yi L                                          VTDPASIDDirEntry *pdire)
765fb43cf73SLiu, Yi L {
766fb43cf73SLiu, Yi L     uint32_t index;
767fb43cf73SLiu, Yi L     dma_addr_t addr, entry_size;
768fb43cf73SLiu, Yi L 
769fb43cf73SLiu, Yi L     index = VTD_PASID_DIR_INDEX(pasid);
770fb43cf73SLiu, Yi L     entry_size = VTD_PASID_DIR_ENTRY_SIZE;
771fb43cf73SLiu, Yi L     addr = pasid_dir_base + index * entry_size;
772ba06fe8aSPhilippe Mathieu-Daudé     if (dma_memory_read(&address_space_memory, addr,
773ba06fe8aSPhilippe Mathieu-Daudé                         pdire, entry_size, MEMTXATTRS_UNSPECIFIED)) {
774fb43cf73SLiu, Yi L         return -VTD_FR_PASID_TABLE_INV;
775fb43cf73SLiu, Yi L     }
776fb43cf73SLiu, Yi L 
777cc2a0848SThomas Huth     pdire->val = le64_to_cpu(pdire->val);
778cc2a0848SThomas Huth 
779fb43cf73SLiu, Yi L     return 0;
780fb43cf73SLiu, Yi L }
781fb43cf73SLiu, Yi L 
78256fc1e6aSLiu Yi L static inline bool vtd_pe_present(VTDPASIDEntry *pe)
78356fc1e6aSLiu Yi L {
78456fc1e6aSLiu Yi L     return pe->val[0] & VTD_PASID_ENTRY_P;
78556fc1e6aSLiu Yi L }
78656fc1e6aSLiu Yi L 
78756fc1e6aSLiu Yi L static int vtd_get_pe_in_pasid_leaf_table(IntelIOMMUState *s,
788fb43cf73SLiu, Yi L                                           uint32_t pasid,
78956fc1e6aSLiu Yi L                                           dma_addr_t addr,
790fb43cf73SLiu, Yi L                                           VTDPASIDEntry *pe)
791fb43cf73SLiu, Yi L {
792fb43cf73SLiu, Yi L     uint32_t index;
79356fc1e6aSLiu Yi L     dma_addr_t entry_size;
794fb43cf73SLiu, Yi L     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
795fb43cf73SLiu, Yi L 
796fb43cf73SLiu, Yi L     index = VTD_PASID_TABLE_INDEX(pasid);
797fb43cf73SLiu, Yi L     entry_size = VTD_PASID_ENTRY_SIZE;
798fb43cf73SLiu, Yi L     addr = addr + index * entry_size;
799ba06fe8aSPhilippe Mathieu-Daudé     if (dma_memory_read(&address_space_memory, addr,
800ba06fe8aSPhilippe Mathieu-Daudé                         pe, entry_size, MEMTXATTRS_UNSPECIFIED)) {
801fb43cf73SLiu, Yi L         return -VTD_FR_PASID_TABLE_INV;
802fb43cf73SLiu, Yi L     }
803cc2a0848SThomas Huth     for (size_t i = 0; i < ARRAY_SIZE(pe->val); i++) {
804cc2a0848SThomas Huth         pe->val[i] = le64_to_cpu(pe->val[i]);
805cc2a0848SThomas Huth     }
806fb43cf73SLiu, Yi L 
807fb43cf73SLiu, Yi L     /* Do translation type check */
808fb43cf73SLiu, Yi L     if (!vtd_pe_type_check(x86_iommu, pe)) {
809fb43cf73SLiu, Yi L         return -VTD_FR_PASID_TABLE_INV;
810fb43cf73SLiu, Yi L     }
811fb43cf73SLiu, Yi L 
812fb43cf73SLiu, Yi L     if (!vtd_is_level_supported(s, VTD_PE_GET_LEVEL(pe))) {
813fb43cf73SLiu, Yi L         return -VTD_FR_PASID_TABLE_INV;
814fb43cf73SLiu, Yi L     }
815fb43cf73SLiu, Yi L 
816fb43cf73SLiu, Yi L     return 0;
817fb43cf73SLiu, Yi L }
818fb43cf73SLiu, Yi L 
81956fc1e6aSLiu Yi L /**
82056fc1e6aSLiu Yi L  * Caller of this function should check present bit if wants
82137557b09SCai Huoqing  * to use pasid entry for further usage except for fpd bit check.
82256fc1e6aSLiu Yi L  */
82356fc1e6aSLiu Yi L static int vtd_get_pe_from_pdire(IntelIOMMUState *s,
82456fc1e6aSLiu Yi L                                  uint32_t pasid,
82556fc1e6aSLiu Yi L                                  VTDPASIDDirEntry *pdire,
82656fc1e6aSLiu Yi L                                  VTDPASIDEntry *pe)
82756fc1e6aSLiu Yi L {
82856fc1e6aSLiu Yi L     dma_addr_t addr = pdire->val & VTD_PASID_TABLE_BASE_ADDR_MASK;
82956fc1e6aSLiu Yi L 
83056fc1e6aSLiu Yi L     return vtd_get_pe_in_pasid_leaf_table(s, pasid, addr, pe);
83156fc1e6aSLiu Yi L }
83256fc1e6aSLiu Yi L 
83356fc1e6aSLiu Yi L /**
83456fc1e6aSLiu Yi L  * This function gets a pasid entry from a specified pasid
83556fc1e6aSLiu Yi L  * table (includes dir and leaf table) with a specified pasid.
83656fc1e6aSLiu Yi L  * Sanity check should be done to ensure return a present
83756fc1e6aSLiu Yi L  * pasid entry to caller.
83856fc1e6aSLiu Yi L  */
83956fc1e6aSLiu Yi L static int vtd_get_pe_from_pasid_table(IntelIOMMUState *s,
840fb43cf73SLiu, Yi L                                        dma_addr_t pasid_dir_base,
841fb43cf73SLiu, Yi L                                        uint32_t pasid,
842fb43cf73SLiu, Yi L                                        VTDPASIDEntry *pe)
843fb43cf73SLiu, Yi L {
844fb43cf73SLiu, Yi L     int ret;
845fb43cf73SLiu, Yi L     VTDPASIDDirEntry pdire;
846fb43cf73SLiu, Yi L 
84756fc1e6aSLiu Yi L     ret = vtd_get_pdire_from_pdir_table(pasid_dir_base,
84856fc1e6aSLiu Yi L                                         pasid, &pdire);
849fb43cf73SLiu, Yi L     if (ret) {
850fb43cf73SLiu, Yi L         return ret;
851fb43cf73SLiu, Yi L     }
852fb43cf73SLiu, Yi L 
85356fc1e6aSLiu Yi L     if (!vtd_pdire_present(&pdire)) {
85456fc1e6aSLiu Yi L         return -VTD_FR_PASID_TABLE_INV;
85556fc1e6aSLiu Yi L     }
85656fc1e6aSLiu Yi L 
85756fc1e6aSLiu Yi L     ret = vtd_get_pe_from_pdire(s, pasid, &pdire, pe);
858fb43cf73SLiu, Yi L     if (ret) {
859fb43cf73SLiu, Yi L         return ret;
860fb43cf73SLiu, Yi L     }
861fb43cf73SLiu, Yi L 
86256fc1e6aSLiu Yi L     if (!vtd_pe_present(pe)) {
86356fc1e6aSLiu Yi L         return -VTD_FR_PASID_TABLE_INV;
86456fc1e6aSLiu Yi L     }
86556fc1e6aSLiu Yi L 
86656fc1e6aSLiu Yi L     return 0;
867fb43cf73SLiu, Yi L }
868fb43cf73SLiu, Yi L 
869fb43cf73SLiu, Yi L static int vtd_ce_get_rid2pasid_entry(IntelIOMMUState *s,
870fb43cf73SLiu, Yi L                                       VTDContextEntry *ce,
8711b2b1237SJason Wang                                       VTDPASIDEntry *pe,
8721b2b1237SJason Wang                                       uint32_t pasid)
873fb43cf73SLiu, Yi L {
874fb43cf73SLiu, Yi L     dma_addr_t pasid_dir_base;
875fb43cf73SLiu, Yi L     int ret = 0;
876fb43cf73SLiu, Yi L 
8771b2b1237SJason Wang     if (pasid == PCI_NO_PASID) {
878fb43cf73SLiu, Yi L         pasid = VTD_CE_GET_RID2PASID(ce);
8791b2b1237SJason Wang     }
880fb43cf73SLiu, Yi L     pasid_dir_base = VTD_CE_GET_PASID_DIR_TABLE(ce);
88156fc1e6aSLiu Yi L     ret = vtd_get_pe_from_pasid_table(s, pasid_dir_base, pasid, pe);
882fb43cf73SLiu, Yi L 
883fb43cf73SLiu, Yi L     return ret;
884fb43cf73SLiu, Yi L }
885fb43cf73SLiu, Yi L 
886fb43cf73SLiu, Yi L static int vtd_ce_get_pasid_fpd(IntelIOMMUState *s,
887fb43cf73SLiu, Yi L                                 VTDContextEntry *ce,
8881b2b1237SJason Wang                                 bool *pe_fpd_set,
8891b2b1237SJason Wang                                 uint32_t pasid)
890fb43cf73SLiu, Yi L {
891fb43cf73SLiu, Yi L     int ret;
892fb43cf73SLiu, Yi L     dma_addr_t pasid_dir_base;
893fb43cf73SLiu, Yi L     VTDPASIDDirEntry pdire;
894fb43cf73SLiu, Yi L     VTDPASIDEntry pe;
895fb43cf73SLiu, Yi L 
8961b2b1237SJason Wang     if (pasid == PCI_NO_PASID) {
897fb43cf73SLiu, Yi L         pasid = VTD_CE_GET_RID2PASID(ce);
8981b2b1237SJason Wang     }
899fb43cf73SLiu, Yi L     pasid_dir_base = VTD_CE_GET_PASID_DIR_TABLE(ce);
900fb43cf73SLiu, Yi L 
90156fc1e6aSLiu Yi L     /*
90256fc1e6aSLiu Yi L      * No present bit check since fpd is meaningful even
90356fc1e6aSLiu Yi L      * if the present bit is clear.
90456fc1e6aSLiu Yi L      */
90556fc1e6aSLiu Yi L     ret = vtd_get_pdire_from_pdir_table(pasid_dir_base, pasid, &pdire);
906fb43cf73SLiu, Yi L     if (ret) {
907fb43cf73SLiu, Yi L         return ret;
908fb43cf73SLiu, Yi L     }
909fb43cf73SLiu, Yi L 
910fb43cf73SLiu, Yi L     if (pdire.val & VTD_PASID_DIR_FPD) {
911fb43cf73SLiu, Yi L         *pe_fpd_set = true;
912fb43cf73SLiu, Yi L         return 0;
913fb43cf73SLiu, Yi L     }
914fb43cf73SLiu, Yi L 
91556fc1e6aSLiu Yi L     if (!vtd_pdire_present(&pdire)) {
91656fc1e6aSLiu Yi L         return -VTD_FR_PASID_TABLE_INV;
91756fc1e6aSLiu Yi L     }
91856fc1e6aSLiu Yi L 
91956fc1e6aSLiu Yi L     /*
92056fc1e6aSLiu Yi L      * No present bit check since fpd is meaningful even
92156fc1e6aSLiu Yi L      * if the present bit is clear.
92256fc1e6aSLiu Yi L      */
92356fc1e6aSLiu Yi L     ret = vtd_get_pe_from_pdire(s, pasid, &pdire, &pe);
924fb43cf73SLiu, Yi L     if (ret) {
925fb43cf73SLiu, Yi L         return ret;
926fb43cf73SLiu, Yi L     }
927fb43cf73SLiu, Yi L 
928fb43cf73SLiu, Yi L     if (pe.val[0] & VTD_PASID_ENTRY_FPD) {
929fb43cf73SLiu, Yi L         *pe_fpd_set = true;
930fb43cf73SLiu, Yi L     }
931fb43cf73SLiu, Yi L 
932fb43cf73SLiu, Yi L     return 0;
933fb43cf73SLiu, Yi L }
934fb43cf73SLiu, Yi L 
9351da12ec4SLe Tan /* Get the page-table level that hardware should use for the second-level
9361da12ec4SLe Tan  * page-table walk from the Address Width field of context-entry.
9371da12ec4SLe Tan  */
9388f7d7161SPeter Xu static inline uint32_t vtd_ce_get_level(VTDContextEntry *ce)
9391da12ec4SLe Tan {
9401da12ec4SLe Tan     return 2 + (ce->hi & VTD_CONTEXT_ENTRY_AW);
9411da12ec4SLe Tan }
9421da12ec4SLe Tan 
943fb43cf73SLiu, Yi L static uint32_t vtd_get_iova_level(IntelIOMMUState *s,
9441b2b1237SJason Wang                                    VTDContextEntry *ce,
9451b2b1237SJason Wang                                    uint32_t pasid)
946fb43cf73SLiu, Yi L {
947fb43cf73SLiu, Yi L     VTDPASIDEntry pe;
948fb43cf73SLiu, Yi L 
949fb43cf73SLiu, Yi L     if (s->root_scalable) {
9501b2b1237SJason Wang         vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
951fb43cf73SLiu, Yi L         return VTD_PE_GET_LEVEL(&pe);
952fb43cf73SLiu, Yi L     }
953fb43cf73SLiu, Yi L 
954fb43cf73SLiu, Yi L     return vtd_ce_get_level(ce);
955fb43cf73SLiu, Yi L }
956fb43cf73SLiu, Yi L 
9578f7d7161SPeter Xu static inline uint32_t vtd_ce_get_agaw(VTDContextEntry *ce)
9581da12ec4SLe Tan {
9591da12ec4SLe Tan     return 30 + (ce->hi & VTD_CONTEXT_ENTRY_AW) * 9;
9601da12ec4SLe Tan }
9611da12ec4SLe Tan 
962fb43cf73SLiu, Yi L static uint32_t vtd_get_iova_agaw(IntelIOMMUState *s,
9631b2b1237SJason Wang                                   VTDContextEntry *ce,
9641b2b1237SJason Wang                                   uint32_t pasid)
965fb43cf73SLiu, Yi L {
966fb43cf73SLiu, Yi L     VTDPASIDEntry pe;
967fb43cf73SLiu, Yi L 
968fb43cf73SLiu, Yi L     if (s->root_scalable) {
9691b2b1237SJason Wang         vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
970fb43cf73SLiu, Yi L         return 30 + ((pe.val[0] >> 2) & VTD_SM_PASID_ENTRY_AW) * 9;
971fb43cf73SLiu, Yi L     }
972fb43cf73SLiu, Yi L 
973fb43cf73SLiu, Yi L     return vtd_ce_get_agaw(ce);
974fb43cf73SLiu, Yi L }
975fb43cf73SLiu, Yi L 
976127ff5c3SPeter Xu static inline uint32_t vtd_ce_get_type(VTDContextEntry *ce)
977127ff5c3SPeter Xu {
978127ff5c3SPeter Xu     return ce->lo & VTD_CONTEXT_ENTRY_TT;
979127ff5c3SPeter Xu }
980127ff5c3SPeter Xu 
981fb43cf73SLiu, Yi L /* Only for Legacy Mode. Return true if check passed, otherwise false */
982f80c9874SPeter Xu static inline bool vtd_ce_type_check(X86IOMMUState *x86_iommu,
983f80c9874SPeter Xu                                      VTDContextEntry *ce)
984f80c9874SPeter Xu {
985f80c9874SPeter Xu     switch (vtd_ce_get_type(ce)) {
986f80c9874SPeter Xu     case VTD_CONTEXT_TT_MULTI_LEVEL:
987f80c9874SPeter Xu         /* Always supported */
988f80c9874SPeter Xu         break;
989f80c9874SPeter Xu     case VTD_CONTEXT_TT_DEV_IOTLB:
990f80c9874SPeter Xu         if (!x86_iommu->dt_supported) {
991095955b2SPeter Xu             error_report_once("%s: DT specified but not supported", __func__);
992f80c9874SPeter Xu             return false;
993f80c9874SPeter Xu         }
994f80c9874SPeter Xu         break;
995dbaabb25SPeter Xu     case VTD_CONTEXT_TT_PASS_THROUGH:
996dbaabb25SPeter Xu         if (!x86_iommu->pt_supported) {
997095955b2SPeter Xu             error_report_once("%s: PT specified but not supported", __func__);
998dbaabb25SPeter Xu             return false;
999dbaabb25SPeter Xu         }
1000dbaabb25SPeter Xu         break;
1001f80c9874SPeter Xu     default:
1002fb43cf73SLiu, Yi L         /* Unknown type */
1003095955b2SPeter Xu         error_report_once("%s: unknown ce type: %"PRIu32, __func__,
1004095955b2SPeter Xu                           vtd_ce_get_type(ce));
1005f80c9874SPeter Xu         return false;
1006f80c9874SPeter Xu     }
1007f80c9874SPeter Xu     return true;
1008f80c9874SPeter Xu }
1009f80c9874SPeter Xu 
1010fb43cf73SLiu, Yi L static inline uint64_t vtd_iova_limit(IntelIOMMUState *s,
10111b2b1237SJason Wang                                       VTDContextEntry *ce, uint8_t aw,
10121b2b1237SJason Wang                                       uint32_t pasid)
1013f06a696dSPeter Xu {
10141b2b1237SJason Wang     uint32_t ce_agaw = vtd_get_iova_agaw(s, ce, pasid);
101537f51384SPrasad Singamsetty     return 1ULL << MIN(ce_agaw, aw);
1016f06a696dSPeter Xu }
1017f06a696dSPeter Xu 
1018f06a696dSPeter Xu /* Return true if IOVA passes range check, otherwise false. */
1019fb43cf73SLiu, Yi L static inline bool vtd_iova_range_check(IntelIOMMUState *s,
1020fb43cf73SLiu, Yi L                                         uint64_t iova, VTDContextEntry *ce,
10211b2b1237SJason Wang                                         uint8_t aw, uint32_t pasid)
1022f06a696dSPeter Xu {
1023f06a696dSPeter Xu     /*
1024f06a696dSPeter Xu      * Check if @iova is above 2^X-1, where X is the minimum of MGAW
1025f06a696dSPeter Xu      * in CAP_REG and AW in context-entry.
1026f06a696dSPeter Xu      */
10271b2b1237SJason Wang     return !(iova & ~(vtd_iova_limit(s, ce, aw, pasid) - 1));
1028fb43cf73SLiu, Yi L }
1029fb43cf73SLiu, Yi L 
1030fb43cf73SLiu, Yi L static dma_addr_t vtd_get_iova_pgtbl_base(IntelIOMMUState *s,
10311b2b1237SJason Wang                                           VTDContextEntry *ce,
10321b2b1237SJason Wang                                           uint32_t pasid)
1033fb43cf73SLiu, Yi L {
1034fb43cf73SLiu, Yi L     VTDPASIDEntry pe;
1035fb43cf73SLiu, Yi L 
1036fb43cf73SLiu, Yi L     if (s->root_scalable) {
10371b2b1237SJason Wang         vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
1038fb43cf73SLiu, Yi L         return pe.val[0] & VTD_SM_PASID_ENTRY_SLPTPTR;
1039fb43cf73SLiu, Yi L     }
1040fb43cf73SLiu, Yi L 
1041fb43cf73SLiu, Yi L     return vtd_ce_get_slpt_base(ce);
1042f06a696dSPeter Xu }
1043f06a696dSPeter Xu 
104492e5d85eSPrasad Singamsetty /*
104592e5d85eSPrasad Singamsetty  * Rsvd field masks for spte:
1046ce586f3bSQi, Yadong  *     vtd_spte_rsvd 4k pages
1047ce586f3bSQi, Yadong  *     vtd_spte_rsvd_large large pages
1048212c5fe1SVladimir Sementsov-Ogievskiy  *
1049212c5fe1SVladimir Sementsov-Ogievskiy  * We support only 3-level and 4-level page tables (see vtd_init() which
1050212c5fe1SVladimir Sementsov-Ogievskiy  * sets only VTD_CAP_SAGAW_39bit and maybe VTD_CAP_SAGAW_48bit bits in s->cap).
105192e5d85eSPrasad Singamsetty  */
1052212c5fe1SVladimir Sementsov-Ogievskiy #define VTD_SPTE_RSVD_LEN 5
1053212c5fe1SVladimir Sementsov-Ogievskiy static uint64_t vtd_spte_rsvd[VTD_SPTE_RSVD_LEN];
1054212c5fe1SVladimir Sementsov-Ogievskiy static uint64_t vtd_spte_rsvd_large[VTD_SPTE_RSVD_LEN];
10551da12ec4SLe Tan 
10561da12ec4SLe Tan static bool vtd_slpte_nonzero_rsvd(uint64_t slpte, uint32_t level)
10571da12ec4SLe Tan {
1058212c5fe1SVladimir Sementsov-Ogievskiy     uint64_t rsvd_mask;
1059212c5fe1SVladimir Sementsov-Ogievskiy 
1060212c5fe1SVladimir Sementsov-Ogievskiy     /*
1061212c5fe1SVladimir Sementsov-Ogievskiy      * We should have caught a guest-mis-programmed level earlier,
1062212c5fe1SVladimir Sementsov-Ogievskiy      * via vtd_is_level_supported.
1063212c5fe1SVladimir Sementsov-Ogievskiy      */
1064212c5fe1SVladimir Sementsov-Ogievskiy     assert(level < VTD_SPTE_RSVD_LEN);
1065212c5fe1SVladimir Sementsov-Ogievskiy     /*
1066212c5fe1SVladimir Sementsov-Ogievskiy      * Zero level doesn't exist. The smallest level is VTD_SL_PT_LEVEL=1 and
1067212c5fe1SVladimir Sementsov-Ogievskiy      * checked by vtd_is_last_slpte().
1068212c5fe1SVladimir Sementsov-Ogievskiy      */
1069212c5fe1SVladimir Sementsov-Ogievskiy     assert(level);
1070ce586f3bSQi, Yadong 
1071ce586f3bSQi, Yadong     if ((level == VTD_SL_PD_LEVEL || level == VTD_SL_PDP_LEVEL) &&
1072ce586f3bSQi, Yadong         (slpte & VTD_SL_PT_PAGE_SIZE_MASK)) {
1073ce586f3bSQi, Yadong         /* large page */
1074ce586f3bSQi, Yadong         rsvd_mask = vtd_spte_rsvd_large[level];
1075212c5fe1SVladimir Sementsov-Ogievskiy     } else {
1076212c5fe1SVladimir Sementsov-Ogievskiy         rsvd_mask = vtd_spte_rsvd[level];
10771da12ec4SLe Tan     }
1078ce586f3bSQi, Yadong 
1079ce586f3bSQi, Yadong     return slpte & rsvd_mask;
10801da12ec4SLe Tan }
10811da12ec4SLe Tan 
10826e905564SPeter Xu /* Given the @iova, get relevant @slptep. @slpte_level will be the last level
10831da12ec4SLe Tan  * of the translation, can be used for deciding the size of large page.
10841da12ec4SLe Tan  */
1085fb43cf73SLiu, Yi L static int vtd_iova_to_slpte(IntelIOMMUState *s, VTDContextEntry *ce,
1086fb43cf73SLiu, Yi L                              uint64_t iova, bool is_write,
10871da12ec4SLe Tan                              uint64_t *slptep, uint32_t *slpte_level,
10881b2b1237SJason Wang                              bool *reads, bool *writes, uint8_t aw_bits,
10891b2b1237SJason Wang                              uint32_t pasid)
10901da12ec4SLe Tan {
10911b2b1237SJason Wang     dma_addr_t addr = vtd_get_iova_pgtbl_base(s, ce, pasid);
10921b2b1237SJason Wang     uint32_t level = vtd_get_iova_level(s, ce, pasid);
10931da12ec4SLe Tan     uint32_t offset;
10941da12ec4SLe Tan     uint64_t slpte;
10951da12ec4SLe Tan     uint64_t access_right_check;
1096ea97a1bdSJason Wang     uint64_t xlat, size;
10971da12ec4SLe Tan 
10981b2b1237SJason Wang     if (!vtd_iova_range_check(s, iova, ce, aw_bits, pasid)) {
10991b2b1237SJason Wang         error_report_once("%s: detected IOVA overflow (iova=0x%" PRIx64 ","
11001b2b1237SJason Wang                           "pasid=0x%" PRIx32 ")", __func__, iova, pasid);
11011da12ec4SLe Tan         return -VTD_FR_ADDR_BEYOND_MGAW;
11021da12ec4SLe Tan     }
11031da12ec4SLe Tan 
11041da12ec4SLe Tan     /* FIXME: what is the Atomics request here? */
11051da12ec4SLe Tan     access_right_check = is_write ? VTD_SL_W : VTD_SL_R;
11061da12ec4SLe Tan 
11071da12ec4SLe Tan     while (true) {
11086e905564SPeter Xu         offset = vtd_iova_level_offset(iova, level);
11091da12ec4SLe Tan         slpte = vtd_get_slpte(addr, offset);
11101da12ec4SLe Tan 
11111da12ec4SLe Tan         if (slpte == (uint64_t)-1) {
11124e4abd11SPeter Xu             error_report_once("%s: detected read error on DMAR slpte "
11131b2b1237SJason Wang                               "(iova=0x%" PRIx64 ", pasid=0x%" PRIx32 ")",
11141b2b1237SJason Wang                               __func__, iova, pasid);
11151b2b1237SJason Wang             if (level == vtd_get_iova_level(s, ce, pasid)) {
11161da12ec4SLe Tan                 /* Invalid programming of context-entry */
11171da12ec4SLe Tan                 return -VTD_FR_CONTEXT_ENTRY_INV;
11181da12ec4SLe Tan             } else {
11191da12ec4SLe Tan                 return -VTD_FR_PAGING_ENTRY_INV;
11201da12ec4SLe Tan             }
11211da12ec4SLe Tan         }
11221da12ec4SLe Tan         *reads = (*reads) && (slpte & VTD_SL_R);
11231da12ec4SLe Tan         *writes = (*writes) && (slpte & VTD_SL_W);
11241da12ec4SLe Tan         if (!(slpte & access_right_check)) {
11254e4abd11SPeter Xu             error_report_once("%s: detected slpte permission error "
11264e4abd11SPeter Xu                               "(iova=0x%" PRIx64 ", level=0x%" PRIx32 ", "
11271b2b1237SJason Wang                               "slpte=0x%" PRIx64 ", write=%d, pasid=0x%"
11281b2b1237SJason Wang                               PRIx32 ")", __func__, iova, level,
11291b2b1237SJason Wang                               slpte, is_write, pasid);
11301da12ec4SLe Tan             return is_write ? -VTD_FR_WRITE : -VTD_FR_READ;
11311da12ec4SLe Tan         }
11321da12ec4SLe Tan         if (vtd_slpte_nonzero_rsvd(slpte, level)) {
11334e4abd11SPeter Xu             error_report_once("%s: detected splte reserve non-zero "
11344e4abd11SPeter Xu                               "iova=0x%" PRIx64 ", level=0x%" PRIx32
11351b2b1237SJason Wang                               "slpte=0x%" PRIx64 ", pasid=0x%" PRIX32 ")",
11361b2b1237SJason Wang                               __func__, iova, level, slpte, pasid);
11371da12ec4SLe Tan             return -VTD_FR_PAGING_ENTRY_RSVD;
11381da12ec4SLe Tan         }
11391da12ec4SLe Tan 
11401da12ec4SLe Tan         if (vtd_is_last_slpte(slpte, level)) {
11411da12ec4SLe Tan             *slptep = slpte;
11421da12ec4SLe Tan             *slpte_level = level;
1143ea97a1bdSJason Wang             break;
11441da12ec4SLe Tan         }
114537f51384SPrasad Singamsetty         addr = vtd_get_slpte_addr(slpte, aw_bits);
11461da12ec4SLe Tan         level--;
11471da12ec4SLe Tan     }
1148ea97a1bdSJason Wang 
1149ea97a1bdSJason Wang     xlat = vtd_get_slpte_addr(*slptep, aw_bits);
1150ea97a1bdSJason Wang     size = ~vtd_slpt_level_page_mask(level) + 1;
1151ea97a1bdSJason Wang 
1152ea97a1bdSJason Wang     /*
1153ea97a1bdSJason Wang      * From VT-d spec 3.14: Untranslated requests and translation
1154ea97a1bdSJason Wang      * requests that result in an address in the interrupt range will be
1155ea97a1bdSJason Wang      * blocked with condition code LGN.4 or SGN.8.
1156ea97a1bdSJason Wang      */
1157ea97a1bdSJason Wang     if ((xlat > VTD_INTERRUPT_ADDR_LAST ||
1158ea97a1bdSJason Wang          xlat + size - 1 < VTD_INTERRUPT_ADDR_FIRST)) {
1159ea97a1bdSJason Wang         return 0;
1160ea97a1bdSJason Wang     } else {
1161ea97a1bdSJason Wang         error_report_once("%s: xlat address is in interrupt range "
1162ea97a1bdSJason Wang                           "(iova=0x%" PRIx64 ", level=0x%" PRIx32 ", "
1163ea97a1bdSJason Wang                           "slpte=0x%" PRIx64 ", write=%d, "
11641b2b1237SJason Wang                           "xlat=0x%" PRIx64 ", size=0x%" PRIx64 ", "
11651b2b1237SJason Wang                           "pasid=0x%" PRIx32 ")",
1166ea97a1bdSJason Wang                           __func__, iova, level, slpte, is_write,
11671b2b1237SJason Wang                           xlat, size, pasid);
1168ea97a1bdSJason Wang         return s->scalable_mode ? -VTD_FR_SM_INTERRUPT_ADDR :
1169ea97a1bdSJason Wang                                   -VTD_FR_INTERRUPT_ADDR;
1170ea97a1bdSJason Wang     }
11711da12ec4SLe Tan }
11721da12ec4SLe Tan 
11735039caf3SEugenio Pérez typedef int (*vtd_page_walk_hook)(IOMMUTLBEvent *event, void *private);
1174f06a696dSPeter Xu 
1175fe215b0cSPeter Xu /**
1176fe215b0cSPeter Xu  * Constant information used during page walking
1177fe215b0cSPeter Xu  *
1178fe215b0cSPeter Xu  * @hook_fn: hook func to be called when detected page
1179fe215b0cSPeter Xu  * @private: private data to be passed into hook func
1180fe215b0cSPeter Xu  * @notify_unmap: whether we should notify invalid entries
11812f764fa8SPeter Xu  * @as: VT-d address space of the device
1182fe215b0cSPeter Xu  * @aw: maximum address width
1183d118c06eSPeter Xu  * @domain: domain ID of the page walk
1184fe215b0cSPeter Xu  */
1185fe215b0cSPeter Xu typedef struct {
11862f764fa8SPeter Xu     VTDAddressSpace *as;
1187fe215b0cSPeter Xu     vtd_page_walk_hook hook_fn;
1188fe215b0cSPeter Xu     void *private;
1189fe215b0cSPeter Xu     bool notify_unmap;
1190fe215b0cSPeter Xu     uint8_t aw;
1191d118c06eSPeter Xu     uint16_t domain_id;
1192fe215b0cSPeter Xu } vtd_page_walk_info;
1193fe215b0cSPeter Xu 
11945039caf3SEugenio Pérez static int vtd_page_walk_one(IOMMUTLBEvent *event, vtd_page_walk_info *info)
119536d2d52bSPeter Xu {
119663b88968SPeter Xu     VTDAddressSpace *as = info->as;
1197fe215b0cSPeter Xu     vtd_page_walk_hook hook_fn = info->hook_fn;
1198fe215b0cSPeter Xu     void *private = info->private;
11995039caf3SEugenio Pérez     IOMMUTLBEntry *entry = &event->entry;
120063b88968SPeter Xu     DMAMap target = {
120163b88968SPeter Xu         .iova = entry->iova,
120263b88968SPeter Xu         .size = entry->addr_mask,
120363b88968SPeter Xu         .translated_addr = entry->translated_addr,
120463b88968SPeter Xu         .perm = entry->perm,
120563b88968SPeter Xu     };
1206a89b34beSEugenio Pérez     const DMAMap *mapped = iova_tree_find(as->iova_tree, &target);
120763b88968SPeter Xu 
12085039caf3SEugenio Pérez     if (event->type == IOMMU_NOTIFIER_UNMAP && !info->notify_unmap) {
120963b88968SPeter Xu         trace_vtd_page_walk_one_skip_unmap(entry->iova, entry->addr_mask);
121063b88968SPeter Xu         return 0;
121163b88968SPeter Xu     }
1212fe215b0cSPeter Xu 
121336d2d52bSPeter Xu     assert(hook_fn);
121463b88968SPeter Xu 
121563b88968SPeter Xu     /* Update local IOVA mapped ranges */
12165039caf3SEugenio Pérez     if (event->type == IOMMU_NOTIFIER_MAP) {
121763b88968SPeter Xu         if (mapped) {
121863b88968SPeter Xu             /* If it's exactly the same translation, skip */
121963b88968SPeter Xu             if (!memcmp(mapped, &target, sizeof(target))) {
122063b88968SPeter Xu                 trace_vtd_page_walk_one_skip_map(entry->iova, entry->addr_mask,
122163b88968SPeter Xu                                                  entry->translated_addr);
122263b88968SPeter Xu                 return 0;
122363b88968SPeter Xu             } else {
122463b88968SPeter Xu                 /*
122563b88968SPeter Xu                  * Translation changed.  Normally this should not
122663b88968SPeter Xu                  * happen, but it can happen when with buggy guest
122763b88968SPeter Xu                  * OSes.  Note that there will be a small window that
122863b88968SPeter Xu                  * we don't have map at all.  But that's the best
122963b88968SPeter Xu                  * effort we can do.  The ideal way to emulate this is
123063b88968SPeter Xu                  * atomically modify the PTE to follow what has
123163b88968SPeter Xu                  * changed, but we can't.  One example is that vfio
123263b88968SPeter Xu                  * driver only has VFIO_IOMMU_[UN]MAP_DMA but no
123363b88968SPeter Xu                  * interface to modify a mapping (meanwhile it seems
123463b88968SPeter Xu                  * meaningless to even provide one).  Anyway, let's
123563b88968SPeter Xu                  * mark this as a TODO in case one day we'll have
123663b88968SPeter Xu                  * a better solution.
123763b88968SPeter Xu                  */
123863b88968SPeter Xu                 IOMMUAccessFlags cache_perm = entry->perm;
123963b88968SPeter Xu                 int ret;
124063b88968SPeter Xu 
124163b88968SPeter Xu                 /* Emulate an UNMAP */
12425039caf3SEugenio Pérez                 event->type = IOMMU_NOTIFIER_UNMAP;
124363b88968SPeter Xu                 entry->perm = IOMMU_NONE;
124463b88968SPeter Xu                 trace_vtd_page_walk_one(info->domain_id,
124563b88968SPeter Xu                                         entry->iova,
124663b88968SPeter Xu                                         entry->translated_addr,
124763b88968SPeter Xu                                         entry->addr_mask,
124863b88968SPeter Xu                                         entry->perm);
12495039caf3SEugenio Pérez                 ret = hook_fn(event, private);
125063b88968SPeter Xu                 if (ret) {
125163b88968SPeter Xu                     return ret;
125263b88968SPeter Xu                 }
125363b88968SPeter Xu                 /* Drop any existing mapping */
125469292a8eSEugenio Pérez                 iova_tree_remove(as->iova_tree, target);
12555039caf3SEugenio Pérez                 /* Recover the correct type */
12565039caf3SEugenio Pérez                 event->type = IOMMU_NOTIFIER_MAP;
125763b88968SPeter Xu                 entry->perm = cache_perm;
125863b88968SPeter Xu             }
125963b88968SPeter Xu         }
126063b88968SPeter Xu         iova_tree_insert(as->iova_tree, &target);
126163b88968SPeter Xu     } else {
126263b88968SPeter Xu         if (!mapped) {
126363b88968SPeter Xu             /* Skip since we didn't map this range at all */
126463b88968SPeter Xu             trace_vtd_page_walk_one_skip_unmap(entry->iova, entry->addr_mask);
126563b88968SPeter Xu             return 0;
126663b88968SPeter Xu         }
126769292a8eSEugenio Pérez         iova_tree_remove(as->iova_tree, target);
126863b88968SPeter Xu     }
126963b88968SPeter Xu 
1270d118c06eSPeter Xu     trace_vtd_page_walk_one(info->domain_id, entry->iova,
1271d118c06eSPeter Xu                             entry->translated_addr, entry->addr_mask,
1272d118c06eSPeter Xu                             entry->perm);
12735039caf3SEugenio Pérez     return hook_fn(event, private);
127436d2d52bSPeter Xu }
127536d2d52bSPeter Xu 
1276f06a696dSPeter Xu /**
1277f06a696dSPeter Xu  * vtd_page_walk_level - walk over specific level for IOVA range
1278f06a696dSPeter Xu  *
1279f06a696dSPeter Xu  * @addr: base GPA addr to start the walk
1280f06a696dSPeter Xu  * @start: IOVA range start address
1281f06a696dSPeter Xu  * @end: IOVA range end address (start <= addr < end)
1282f06a696dSPeter Xu  * @read: whether parent level has read permission
1283f06a696dSPeter Xu  * @write: whether parent level has write permission
1284fe215b0cSPeter Xu  * @info: constant information for the page walk
1285f06a696dSPeter Xu  */
1286f06a696dSPeter Xu static int vtd_page_walk_level(dma_addr_t addr, uint64_t start,
1287fe215b0cSPeter Xu                                uint64_t end, uint32_t level, bool read,
1288fe215b0cSPeter Xu                                bool write, vtd_page_walk_info *info)
1289f06a696dSPeter Xu {
1290f06a696dSPeter Xu     bool read_cur, write_cur, entry_valid;
1291f06a696dSPeter Xu     uint32_t offset;
1292f06a696dSPeter Xu     uint64_t slpte;
1293f06a696dSPeter Xu     uint64_t subpage_size, subpage_mask;
12945039caf3SEugenio Pérez     IOMMUTLBEvent event;
1295f06a696dSPeter Xu     uint64_t iova = start;
1296f06a696dSPeter Xu     uint64_t iova_next;
1297f06a696dSPeter Xu     int ret = 0;
1298f06a696dSPeter Xu 
1299f06a696dSPeter Xu     trace_vtd_page_walk_level(addr, level, start, end);
1300f06a696dSPeter Xu 
1301f06a696dSPeter Xu     subpage_size = 1ULL << vtd_slpt_level_shift(level);
1302f06a696dSPeter Xu     subpage_mask = vtd_slpt_level_page_mask(level);
1303f06a696dSPeter Xu 
1304f06a696dSPeter Xu     while (iova < end) {
1305f06a696dSPeter Xu         iova_next = (iova & subpage_mask) + subpage_size;
1306f06a696dSPeter Xu 
1307f06a696dSPeter Xu         offset = vtd_iova_level_offset(iova, level);
1308f06a696dSPeter Xu         slpte = vtd_get_slpte(addr, offset);
1309f06a696dSPeter Xu 
1310f06a696dSPeter Xu         if (slpte == (uint64_t)-1) {
1311f06a696dSPeter Xu             trace_vtd_page_walk_skip_read(iova, iova_next);
1312f06a696dSPeter Xu             goto next;
1313f06a696dSPeter Xu         }
1314f06a696dSPeter Xu 
1315f06a696dSPeter Xu         if (vtd_slpte_nonzero_rsvd(slpte, level)) {
1316f06a696dSPeter Xu             trace_vtd_page_walk_skip_reserve(iova, iova_next);
1317f06a696dSPeter Xu             goto next;
1318f06a696dSPeter Xu         }
1319f06a696dSPeter Xu 
1320f06a696dSPeter Xu         /* Permissions are stacked with parents' */
1321f06a696dSPeter Xu         read_cur = read && (slpte & VTD_SL_R);
1322f06a696dSPeter Xu         write_cur = write && (slpte & VTD_SL_W);
1323f06a696dSPeter Xu 
1324f06a696dSPeter Xu         /*
1325f06a696dSPeter Xu          * As long as we have either read/write permission, this is a
1326f06a696dSPeter Xu          * valid entry. The rule works for both page entries and page
1327f06a696dSPeter Xu          * table entries.
1328f06a696dSPeter Xu          */
1329f06a696dSPeter Xu         entry_valid = read_cur | write_cur;
1330f06a696dSPeter Xu 
133163b88968SPeter Xu         if (!vtd_is_last_slpte(slpte, level) && entry_valid) {
133263b88968SPeter Xu             /*
133363b88968SPeter Xu              * This is a valid PDE (or even bigger than PDE).  We need
133463b88968SPeter Xu              * to walk one further level.
133563b88968SPeter Xu              */
133663b88968SPeter Xu             ret = vtd_page_walk_level(vtd_get_slpte_addr(slpte, info->aw),
133763b88968SPeter Xu                                       iova, MIN(iova_next, end), level - 1,
133863b88968SPeter Xu                                       read_cur, write_cur, info);
133963b88968SPeter Xu         } else {
134063b88968SPeter Xu             /*
134163b88968SPeter Xu              * This means we are either:
134263b88968SPeter Xu              *
134363b88968SPeter Xu              * (1) the real page entry (either 4K page, or huge page)
134463b88968SPeter Xu              * (2) the whole range is invalid
134563b88968SPeter Xu              *
134663b88968SPeter Xu              * In either case, we send an IOTLB notification down.
134763b88968SPeter Xu              */
13485039caf3SEugenio Pérez             event.entry.target_as = &address_space_memory;
13495039caf3SEugenio Pérez             event.entry.iova = iova & subpage_mask;
13505039caf3SEugenio Pérez             event.entry.perm = IOMMU_ACCESS_FLAG(read_cur, write_cur);
13515039caf3SEugenio Pérez             event.entry.addr_mask = ~subpage_mask;
1352f06a696dSPeter Xu             /* NOTE: this is only meaningful if entry_valid == true */
13535039caf3SEugenio Pérez             event.entry.translated_addr = vtd_get_slpte_addr(slpte, info->aw);
13545039caf3SEugenio Pérez             event.type = event.entry.perm ? IOMMU_NOTIFIER_MAP :
13555039caf3SEugenio Pérez                                             IOMMU_NOTIFIER_UNMAP;
13565039caf3SEugenio Pérez             ret = vtd_page_walk_one(&event, info);
135763b88968SPeter Xu         }
135863b88968SPeter Xu 
1359f06a696dSPeter Xu         if (ret < 0) {
1360f06a696dSPeter Xu             return ret;
1361f06a696dSPeter Xu         }
1362f06a696dSPeter Xu 
1363f06a696dSPeter Xu next:
1364f06a696dSPeter Xu         iova = iova_next;
1365f06a696dSPeter Xu     }
1366f06a696dSPeter Xu 
1367f06a696dSPeter Xu     return 0;
1368f06a696dSPeter Xu }
1369f06a696dSPeter Xu 
1370f06a696dSPeter Xu /**
1371f06a696dSPeter Xu  * vtd_page_walk - walk specific IOVA range, and call the hook
1372f06a696dSPeter Xu  *
1373fb43cf73SLiu, Yi L  * @s: intel iommu state
1374f06a696dSPeter Xu  * @ce: context entry to walk upon
1375f06a696dSPeter Xu  * @start: IOVA address to start the walk
1376f06a696dSPeter Xu  * @end: IOVA range end address (start <= addr < end)
1377fe215b0cSPeter Xu  * @info: page walking information struct
1378f06a696dSPeter Xu  */
1379fb43cf73SLiu, Yi L static int vtd_page_walk(IntelIOMMUState *s, VTDContextEntry *ce,
1380fb43cf73SLiu, Yi L                          uint64_t start, uint64_t end,
13811b2b1237SJason Wang                          vtd_page_walk_info *info,
13821b2b1237SJason Wang                          uint32_t pasid)
1383f06a696dSPeter Xu {
13841b2b1237SJason Wang     dma_addr_t addr = vtd_get_iova_pgtbl_base(s, ce, pasid);
13851b2b1237SJason Wang     uint32_t level = vtd_get_iova_level(s, ce, pasid);
1386f06a696dSPeter Xu 
13871b2b1237SJason Wang     if (!vtd_iova_range_check(s, start, ce, info->aw, pasid)) {
1388f06a696dSPeter Xu         return -VTD_FR_ADDR_BEYOND_MGAW;
1389f06a696dSPeter Xu     }
1390f06a696dSPeter Xu 
13911b2b1237SJason Wang     if (!vtd_iova_range_check(s, end, ce, info->aw, pasid)) {
1392f06a696dSPeter Xu         /* Fix end so that it reaches the maximum */
13931b2b1237SJason Wang         end = vtd_iova_limit(s, ce, info->aw, pasid);
1394f06a696dSPeter Xu     }
1395f06a696dSPeter Xu 
1396fe215b0cSPeter Xu     return vtd_page_walk_level(addr, start, end, level, true, true, info);
1397f06a696dSPeter Xu }
1398f06a696dSPeter Xu 
1399fb43cf73SLiu, Yi L static int vtd_root_entry_rsvd_bits_check(IntelIOMMUState *s,
1400fb43cf73SLiu, Yi L                                           VTDRootEntry *re)
1401fb43cf73SLiu, Yi L {
1402fb43cf73SLiu, Yi L     /* Legacy Mode reserved bits check */
1403fb43cf73SLiu, Yi L     if (!s->root_scalable &&
1404fb43cf73SLiu, Yi L         (re->hi || (re->lo & VTD_ROOT_ENTRY_RSVD(s->aw_bits))))
1405fb43cf73SLiu, Yi L         goto rsvd_err;
1406fb43cf73SLiu, Yi L 
1407fb43cf73SLiu, Yi L     /* Scalable Mode reserved bits check */
1408fb43cf73SLiu, Yi L     if (s->root_scalable &&
1409fb43cf73SLiu, Yi L         ((re->lo & VTD_ROOT_ENTRY_RSVD(s->aw_bits)) ||
1410fb43cf73SLiu, Yi L          (re->hi & VTD_ROOT_ENTRY_RSVD(s->aw_bits))))
1411fb43cf73SLiu, Yi L         goto rsvd_err;
1412fb43cf73SLiu, Yi L 
1413fb43cf73SLiu, Yi L     return 0;
1414fb43cf73SLiu, Yi L 
1415fb43cf73SLiu, Yi L rsvd_err:
1416fb43cf73SLiu, Yi L     error_report_once("%s: invalid root entry: hi=0x%"PRIx64
1417fb43cf73SLiu, Yi L                       ", lo=0x%"PRIx64,
1418fb43cf73SLiu, Yi L                       __func__, re->hi, re->lo);
1419fb43cf73SLiu, Yi L     return -VTD_FR_ROOT_ENTRY_RSVD;
1420fb43cf73SLiu, Yi L }
1421fb43cf73SLiu, Yi L 
1422fb43cf73SLiu, Yi L static inline int vtd_context_entry_rsvd_bits_check(IntelIOMMUState *s,
1423fb43cf73SLiu, Yi L                                                     VTDContextEntry *ce)
1424fb43cf73SLiu, Yi L {
1425fb43cf73SLiu, Yi L     if (!s->root_scalable &&
1426fb43cf73SLiu, Yi L         (ce->hi & VTD_CONTEXT_ENTRY_RSVD_HI ||
1427fb43cf73SLiu, Yi L          ce->lo & VTD_CONTEXT_ENTRY_RSVD_LO(s->aw_bits))) {
1428fb43cf73SLiu, Yi L         error_report_once("%s: invalid context entry: hi=%"PRIx64
1429fb43cf73SLiu, Yi L                           ", lo=%"PRIx64" (reserved nonzero)",
1430fb43cf73SLiu, Yi L                           __func__, ce->hi, ce->lo);
1431fb43cf73SLiu, Yi L         return -VTD_FR_CONTEXT_ENTRY_RSVD;
1432fb43cf73SLiu, Yi L     }
1433fb43cf73SLiu, Yi L 
1434fb43cf73SLiu, Yi L     if (s->root_scalable &&
1435fb43cf73SLiu, Yi L         (ce->val[0] & VTD_SM_CONTEXT_ENTRY_RSVD_VAL0(s->aw_bits) ||
1436fb43cf73SLiu, Yi L          ce->val[1] & VTD_SM_CONTEXT_ENTRY_RSVD_VAL1 ||
1437fb43cf73SLiu, Yi L          ce->val[2] ||
1438fb43cf73SLiu, Yi L          ce->val[3])) {
1439fb43cf73SLiu, Yi L         error_report_once("%s: invalid context entry: val[3]=%"PRIx64
1440fb43cf73SLiu, Yi L                           ", val[2]=%"PRIx64
1441fb43cf73SLiu, Yi L                           ", val[1]=%"PRIx64
1442fb43cf73SLiu, Yi L                           ", val[0]=%"PRIx64" (reserved nonzero)",
1443fb43cf73SLiu, Yi L                           __func__, ce->val[3], ce->val[2],
1444fb43cf73SLiu, Yi L                           ce->val[1], ce->val[0]);
1445fb43cf73SLiu, Yi L         return -VTD_FR_CONTEXT_ENTRY_RSVD;
1446fb43cf73SLiu, Yi L     }
1447fb43cf73SLiu, Yi L 
1448fb43cf73SLiu, Yi L     return 0;
1449fb43cf73SLiu, Yi L }
1450fb43cf73SLiu, Yi L 
1451fb43cf73SLiu, Yi L static int vtd_ce_rid2pasid_check(IntelIOMMUState *s,
1452fb43cf73SLiu, Yi L                                   VTDContextEntry *ce)
1453fb43cf73SLiu, Yi L {
1454fb43cf73SLiu, Yi L     VTDPASIDEntry pe;
1455fb43cf73SLiu, Yi L 
1456fb43cf73SLiu, Yi L     /*
1457fb43cf73SLiu, Yi L      * Make sure in Scalable Mode, a present context entry
1458fb43cf73SLiu, Yi L      * has valid rid2pasid setting, which includes valid
1459fb43cf73SLiu, Yi L      * rid2pasid field and corresponding pasid entry setting
1460fb43cf73SLiu, Yi L      */
14611b2b1237SJason Wang     return vtd_ce_get_rid2pasid_entry(s, ce, &pe, PCI_NO_PASID);
1462fb43cf73SLiu, Yi L }
1463fb43cf73SLiu, Yi L 
14641da12ec4SLe Tan /* Map a device to its corresponding domain (context-entry) */
14651da12ec4SLe Tan static int vtd_dev_to_context_entry(IntelIOMMUState *s, uint8_t bus_num,
14661da12ec4SLe Tan                                     uint8_t devfn, VTDContextEntry *ce)
14671da12ec4SLe Tan {
14681da12ec4SLe Tan     VTDRootEntry re;
14691da12ec4SLe Tan     int ret_fr;
1470f80c9874SPeter Xu     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
14711da12ec4SLe Tan 
14721da12ec4SLe Tan     ret_fr = vtd_get_root_entry(s, bus_num, &re);
14731da12ec4SLe Tan     if (ret_fr) {
14741da12ec4SLe Tan         return ret_fr;
14751da12ec4SLe Tan     }
14761da12ec4SLe Tan 
1477fb43cf73SLiu, Yi L     if (!vtd_root_entry_present(s, &re, devfn)) {
14786c441e1dSPeter Xu         /* Not error - it's okay we don't have root entry. */
14796c441e1dSPeter Xu         trace_vtd_re_not_present(bus_num);
14801da12ec4SLe Tan         return -VTD_FR_ROOT_ENTRY_P;
1481f80c9874SPeter Xu     }
1482f80c9874SPeter Xu 
1483fb43cf73SLiu, Yi L     ret_fr = vtd_root_entry_rsvd_bits_check(s, &re);
1484fb43cf73SLiu, Yi L     if (ret_fr) {
1485fb43cf73SLiu, Yi L         return ret_fr;
14861da12ec4SLe Tan     }
14871da12ec4SLe Tan 
1488fb43cf73SLiu, Yi L     ret_fr = vtd_get_context_entry_from_root(s, &re, devfn, ce);
14891da12ec4SLe Tan     if (ret_fr) {
14901da12ec4SLe Tan         return ret_fr;
14911da12ec4SLe Tan     }
14921da12ec4SLe Tan 
14938f7d7161SPeter Xu     if (!vtd_ce_present(ce)) {
14946c441e1dSPeter Xu         /* Not error - it's okay we don't have context entry. */
14956c441e1dSPeter Xu         trace_vtd_ce_not_present(bus_num, devfn);
14961da12ec4SLe Tan         return -VTD_FR_CONTEXT_ENTRY_P;
1497f80c9874SPeter Xu     }
1498f80c9874SPeter Xu 
1499fb43cf73SLiu, Yi L     ret_fr = vtd_context_entry_rsvd_bits_check(s, ce);
1500fb43cf73SLiu, Yi L     if (ret_fr) {
1501fb43cf73SLiu, Yi L         return ret_fr;
15021da12ec4SLe Tan     }
1503f80c9874SPeter Xu 
15041da12ec4SLe Tan     /* Check if the programming of context-entry is valid */
1505fb43cf73SLiu, Yi L     if (!s->root_scalable &&
1506fb43cf73SLiu, Yi L         !vtd_is_level_supported(s, vtd_ce_get_level(ce))) {
1507095955b2SPeter Xu         error_report_once("%s: invalid context entry: hi=%"PRIx64
1508095955b2SPeter Xu                           ", lo=%"PRIx64" (level %d not supported)",
1509fb43cf73SLiu, Yi L                           __func__, ce->hi, ce->lo,
1510fb43cf73SLiu, Yi L                           vtd_ce_get_level(ce));
15111da12ec4SLe Tan         return -VTD_FR_CONTEXT_ENTRY_INV;
1512f80c9874SPeter Xu     }
1513f80c9874SPeter Xu 
1514fb43cf73SLiu, Yi L     if (!s->root_scalable) {
1515f80c9874SPeter Xu         /* Do translation type check */
1516f80c9874SPeter Xu         if (!vtd_ce_type_check(x86_iommu, ce)) {
1517095955b2SPeter Xu             /* Errors dumped in vtd_ce_type_check() */
15181da12ec4SLe Tan             return -VTD_FR_CONTEXT_ENTRY_INV;
15191da12ec4SLe Tan         }
1520fb43cf73SLiu, Yi L     } else {
1521fb43cf73SLiu, Yi L         /*
1522fb43cf73SLiu, Yi L          * Check if the programming of context-entry.rid2pasid
1523fb43cf73SLiu, Yi L          * and corresponding pasid setting is valid, and thus
1524fb43cf73SLiu, Yi L          * avoids to check pasid entry fetching result in future
1525fb43cf73SLiu, Yi L          * helper function calling.
1526fb43cf73SLiu, Yi L          */
1527fb43cf73SLiu, Yi L         ret_fr = vtd_ce_rid2pasid_check(s, ce);
1528fb43cf73SLiu, Yi L         if (ret_fr) {
1529fb43cf73SLiu, Yi L             return ret_fr;
1530fb43cf73SLiu, Yi L         }
1531fb43cf73SLiu, Yi L     }
1532f80c9874SPeter Xu 
15331da12ec4SLe Tan     return 0;
15341da12ec4SLe Tan }
15351da12ec4SLe Tan 
15365039caf3SEugenio Pérez static int vtd_sync_shadow_page_hook(IOMMUTLBEvent *event,
153763b88968SPeter Xu                                      void *private)
153863b88968SPeter Xu {
15395039caf3SEugenio Pérez     memory_region_notify_iommu(private, 0, *event);
154063b88968SPeter Xu     return 0;
154163b88968SPeter Xu }
154263b88968SPeter Xu 
1543fb43cf73SLiu, Yi L static uint16_t vtd_get_domain_id(IntelIOMMUState *s,
15441b2b1237SJason Wang                                   VTDContextEntry *ce,
15451b2b1237SJason Wang                                   uint32_t pasid)
1546fb43cf73SLiu, Yi L {
1547fb43cf73SLiu, Yi L     VTDPASIDEntry pe;
1548fb43cf73SLiu, Yi L 
1549fb43cf73SLiu, Yi L     if (s->root_scalable) {
15501b2b1237SJason Wang         vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
1551fb43cf73SLiu, Yi L         return VTD_SM_PASID_ENTRY_DID(pe.val[1]);
1552fb43cf73SLiu, Yi L     }
1553fb43cf73SLiu, Yi L 
1554fb43cf73SLiu, Yi L     return VTD_CONTEXT_ENTRY_DID(ce->hi);
1555fb43cf73SLiu, Yi L }
1556fb43cf73SLiu, Yi L 
155763b88968SPeter Xu static int vtd_sync_shadow_page_table_range(VTDAddressSpace *vtd_as,
155863b88968SPeter Xu                                             VTDContextEntry *ce,
155963b88968SPeter Xu                                             hwaddr addr, hwaddr size)
156063b88968SPeter Xu {
156163b88968SPeter Xu     IntelIOMMUState *s = vtd_as->iommu_state;
156263b88968SPeter Xu     vtd_page_walk_info info = {
156363b88968SPeter Xu         .hook_fn = vtd_sync_shadow_page_hook,
156463b88968SPeter Xu         .private = (void *)&vtd_as->iommu,
156563b88968SPeter Xu         .notify_unmap = true,
156663b88968SPeter Xu         .aw = s->aw_bits,
156763b88968SPeter Xu         .as = vtd_as,
15681b2b1237SJason Wang         .domain_id = vtd_get_domain_id(s, ce, vtd_as->pasid),
156963b88968SPeter Xu     };
157063b88968SPeter Xu 
15711b2b1237SJason Wang     return vtd_page_walk(s, ce, addr, addr + size, &info, vtd_as->pasid);
157263b88968SPeter Xu }
157363b88968SPeter Xu 
15743e090e34SPeter Xu static int vtd_address_space_sync(VTDAddressSpace *vtd_as)
157563b88968SPeter Xu {
157695ecd3dfSPeter Xu     int ret;
157795ecd3dfSPeter Xu     VTDContextEntry ce;
1578c28b535dSPeter Xu     IOMMUNotifier *n;
157995ecd3dfSPeter Xu 
15803e090e34SPeter Xu     /* If no MAP notifier registered, we simply invalidate all the cache */
15813e090e34SPeter Xu     if (!vtd_as_has_map_notifier(vtd_as)) {
15823e090e34SPeter Xu         IOMMU_NOTIFIER_FOREACH(n, &vtd_as->iommu) {
15833e090e34SPeter Xu             memory_region_unmap_iommu_notifier_range(n);
15843e090e34SPeter Xu         }
1585f7701e2cSEugenio Pérez         return 0;
1586f7701e2cSEugenio Pérez     }
1587f7701e2cSEugenio Pérez 
158895ecd3dfSPeter Xu     ret = vtd_dev_to_context_entry(vtd_as->iommu_state,
158995ecd3dfSPeter Xu                                    pci_bus_num(vtd_as->bus),
159095ecd3dfSPeter Xu                                    vtd_as->devfn, &ce);
159195ecd3dfSPeter Xu     if (ret) {
1592c28b535dSPeter Xu         if (ret == -VTD_FR_CONTEXT_ENTRY_P) {
1593c28b535dSPeter Xu             /*
1594c28b535dSPeter Xu              * It's a valid scenario to have a context entry that is
1595c28b535dSPeter Xu              * not present.  For example, when a device is removed
1596c28b535dSPeter Xu              * from an existing domain then the context entry will be
1597c28b535dSPeter Xu              * zeroed by the guest before it was put into another
1598c28b535dSPeter Xu              * domain.  When this happens, instead of synchronizing
1599c28b535dSPeter Xu              * the shadow pages we should invalidate all existing
1600c28b535dSPeter Xu              * mappings and notify the backends.
1601c28b535dSPeter Xu              */
1602c28b535dSPeter Xu             IOMMU_NOTIFIER_FOREACH(n, &vtd_as->iommu) {
1603c28b535dSPeter Xu                 vtd_address_space_unmap(vtd_as, n);
1604c28b535dSPeter Xu             }
1605c28b535dSPeter Xu             ret = 0;
1606c28b535dSPeter Xu         }
160795ecd3dfSPeter Xu         return ret;
160895ecd3dfSPeter Xu     }
160995ecd3dfSPeter Xu 
161095ecd3dfSPeter Xu     return vtd_sync_shadow_page_table_range(vtd_as, &ce, 0, UINT64_MAX);
161163b88968SPeter Xu }
161263b88968SPeter Xu 
1613dbaabb25SPeter Xu /*
161437557b09SCai Huoqing  * Check if specific device is configured to bypass address
1615fb43cf73SLiu, Yi L  * translation for DMA requests. In Scalable Mode, bypass
1616fb43cf73SLiu, Yi L  * 1st-level translation or 2nd-level translation, it depends
1617fb43cf73SLiu, Yi L  * on PGTT setting.
1618dbaabb25SPeter Xu  */
16191b2b1237SJason Wang static bool vtd_dev_pt_enabled(IntelIOMMUState *s, VTDContextEntry *ce,
16201b2b1237SJason Wang                                uint32_t pasid)
16215178d78fSJason Wang {
16225178d78fSJason Wang     VTDPASIDEntry pe;
16235178d78fSJason Wang     int ret;
16245178d78fSJason Wang 
16255178d78fSJason Wang     if (s->root_scalable) {
16261b2b1237SJason Wang         ret = vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
16275178d78fSJason Wang         if (ret) {
1628fb1d084bSJason Wang             /*
1629fb1d084bSJason Wang              * This error is guest triggerable. We should assumt PT
1630fb1d084bSJason Wang              * not enabled for safety.
1631fb1d084bSJason Wang              */
16325178d78fSJason Wang             return false;
16335178d78fSJason Wang         }
16345178d78fSJason Wang         return (VTD_PE_GET_TYPE(&pe) == VTD_SM_PASID_ENTRY_PT);
16355178d78fSJason Wang     }
16365178d78fSJason Wang 
16375178d78fSJason Wang     return (vtd_ce_get_type(ce) == VTD_CONTEXT_TT_PASS_THROUGH);
16385178d78fSJason Wang 
16395178d78fSJason Wang }
16405178d78fSJason Wang 
16415178d78fSJason Wang static bool vtd_as_pt_enabled(VTDAddressSpace *as)
1642dbaabb25SPeter Xu {
1643dbaabb25SPeter Xu     IntelIOMMUState *s;
1644dbaabb25SPeter Xu     VTDContextEntry ce;
1645dbaabb25SPeter Xu 
1646dbaabb25SPeter Xu     assert(as);
1647dbaabb25SPeter Xu 
1648fb43cf73SLiu, Yi L     s = as->iommu_state;
1649fb1d084bSJason Wang     if (vtd_dev_to_context_entry(s, pci_bus_num(as->bus), as->devfn,
1650fb1d084bSJason Wang                                  &ce)) {
1651dbaabb25SPeter Xu         /*
1652dbaabb25SPeter Xu          * Possibly failed to parse the context entry for some reason
1653dbaabb25SPeter Xu          * (e.g., during init, or any guest configuration errors on
1654dbaabb25SPeter Xu          * context entries). We should assume PT not enabled for
1655dbaabb25SPeter Xu          * safety.
1656dbaabb25SPeter Xu          */
1657dbaabb25SPeter Xu         return false;
1658dbaabb25SPeter Xu     }
1659dbaabb25SPeter Xu 
16601b2b1237SJason Wang     return vtd_dev_pt_enabled(s, &ce, as->pasid);
1661dbaabb25SPeter Xu }
1662dbaabb25SPeter Xu 
1663dbaabb25SPeter Xu /* Return whether the device is using IOMMU translation. */
1664dbaabb25SPeter Xu static bool vtd_switch_address_space(VTDAddressSpace *as)
1665dbaabb25SPeter Xu {
16661b2b1237SJason Wang     bool use_iommu, pt;
166766a4a031SPeter Xu     /* Whether we need to take the BQL on our own */
1668195801d7SStefan Hajnoczi     bool take_bql = !bql_locked();
1669dbaabb25SPeter Xu 
1670dbaabb25SPeter Xu     assert(as);
1671dbaabb25SPeter Xu 
16725178d78fSJason Wang     use_iommu = as->iommu_state->dmar_enabled && !vtd_as_pt_enabled(as);
16731b2b1237SJason Wang     pt = as->iommu_state->dmar_enabled && vtd_as_pt_enabled(as);
1674dbaabb25SPeter Xu 
1675dbaabb25SPeter Xu     trace_vtd_switch_address_space(pci_bus_num(as->bus),
1676dbaabb25SPeter Xu                                    VTD_PCI_SLOT(as->devfn),
1677dbaabb25SPeter Xu                                    VTD_PCI_FUNC(as->devfn),
1678dbaabb25SPeter Xu                                    use_iommu);
1679dbaabb25SPeter Xu 
168066a4a031SPeter Xu     /*
168166a4a031SPeter Xu      * It's possible that we reach here without BQL, e.g., when called
168266a4a031SPeter Xu      * from vtd_pt_enable_fast_path(). However the memory APIs need
168366a4a031SPeter Xu      * it. We'd better make sure we have had it already, or, take it.
168466a4a031SPeter Xu      */
168566a4a031SPeter Xu     if (take_bql) {
1686195801d7SStefan Hajnoczi         bql_lock();
168766a4a031SPeter Xu     }
168866a4a031SPeter Xu 
1689dbaabb25SPeter Xu     /* Turn off first then on the other */
1690dbaabb25SPeter Xu     if (use_iommu) {
16914b519ef1SPeter Xu         memory_region_set_enabled(&as->nodmar, false);
16923df9d748SAlexey Kardashevskiy         memory_region_set_enabled(MEMORY_REGION(&as->iommu), true);
16931b2b1237SJason Wang         /*
16941b2b1237SJason Wang          * vt-d spec v3.4 3.14:
16951b2b1237SJason Wang          *
16961b2b1237SJason Wang          * """
16971b2b1237SJason Wang          * Requests-with-PASID with input address in range 0xFEEx_xxxx
16981b2b1237SJason Wang          * are translated normally like any other request-with-PASID
16991b2b1237SJason Wang          * through DMA-remapping hardware.
17001b2b1237SJason Wang          * """
17011b2b1237SJason Wang          *
17021b2b1237SJason Wang          * Need to disable ir for as with PASID.
17031b2b1237SJason Wang          */
17041b2b1237SJason Wang         if (as->pasid != PCI_NO_PASID) {
17051b2b1237SJason Wang             memory_region_set_enabled(&as->iommu_ir, false);
17061b2b1237SJason Wang         } else {
17071b2b1237SJason Wang             memory_region_set_enabled(&as->iommu_ir, true);
17081b2b1237SJason Wang         }
1709dbaabb25SPeter Xu     } else {
17103df9d748SAlexey Kardashevskiy         memory_region_set_enabled(MEMORY_REGION(&as->iommu), false);
17114b519ef1SPeter Xu         memory_region_set_enabled(&as->nodmar, true);
1712dbaabb25SPeter Xu     }
1713dbaabb25SPeter Xu 
17141b2b1237SJason Wang     /*
17151b2b1237SJason Wang      * vtd-spec v3.4 3.14:
17161b2b1237SJason Wang      *
17171b2b1237SJason Wang      * """
17181b2b1237SJason Wang      * Requests-with-PASID with input address in range 0xFEEx_xxxx are
17191b2b1237SJason Wang      * translated normally like any other request-with-PASID through
17201b2b1237SJason Wang      * DMA-remapping hardware. However, if such a request is processed
17211b2b1237SJason Wang      * using pass-through translation, it will be blocked as described
17221b2b1237SJason Wang      * in the paragraph below.
17231b2b1237SJason Wang      *
17241b2b1237SJason Wang      * Software must not program paging-structure entries to remap any
17251b2b1237SJason Wang      * address to the interrupt address range. Untranslated requests
17261b2b1237SJason Wang      * and translation requests that result in an address in the
17271b2b1237SJason Wang      * interrupt range will be blocked with condition code LGN.4 or
17281b2b1237SJason Wang      * SGN.8.
17291b2b1237SJason Wang      * """
17301b2b1237SJason Wang      *
17311b2b1237SJason Wang      * We enable per as memory region (iommu_ir_fault) for catching
1732bad5cfcdSMichael Tokarev      * the translation for interrupt range through PASID + PT.
17331b2b1237SJason Wang      */
17341b2b1237SJason Wang     if (pt && as->pasid != PCI_NO_PASID) {
17351b2b1237SJason Wang         memory_region_set_enabled(&as->iommu_ir_fault, true);
17361b2b1237SJason Wang     } else {
17371b2b1237SJason Wang         memory_region_set_enabled(&as->iommu_ir_fault, false);
17381b2b1237SJason Wang     }
17391b2b1237SJason Wang 
174066a4a031SPeter Xu     if (take_bql) {
1741195801d7SStefan Hajnoczi         bql_unlock();
174266a4a031SPeter Xu     }
174366a4a031SPeter Xu 
1744dbaabb25SPeter Xu     return use_iommu;
1745dbaabb25SPeter Xu }
1746dbaabb25SPeter Xu 
1747dbaabb25SPeter Xu static void vtd_switch_address_space_all(IntelIOMMUState *s)
1748dbaabb25SPeter Xu {
1749da8d439cSJason Wang     VTDAddressSpace *vtd_as;
1750dbaabb25SPeter Xu     GHashTableIter iter;
1751dbaabb25SPeter Xu 
1752da8d439cSJason Wang     g_hash_table_iter_init(&iter, s->vtd_address_spaces);
1753da8d439cSJason Wang     while (g_hash_table_iter_next(&iter, NULL, (void **)&vtd_as)) {
1754da8d439cSJason Wang         vtd_switch_address_space(vtd_as);
1755dbaabb25SPeter Xu     }
17561da12ec4SLe Tan }
17571da12ec4SLe Tan 
17581da12ec4SLe Tan static const bool vtd_qualified_faults[] = {
17591da12ec4SLe Tan     [VTD_FR_RESERVED] = false,
17601da12ec4SLe Tan     [VTD_FR_ROOT_ENTRY_P] = false,
17611da12ec4SLe Tan     [VTD_FR_CONTEXT_ENTRY_P] = true,
17621da12ec4SLe Tan     [VTD_FR_CONTEXT_ENTRY_INV] = true,
17631da12ec4SLe Tan     [VTD_FR_ADDR_BEYOND_MGAW] = true,
17641da12ec4SLe Tan     [VTD_FR_WRITE] = true,
17651da12ec4SLe Tan     [VTD_FR_READ] = true,
17661da12ec4SLe Tan     [VTD_FR_PAGING_ENTRY_INV] = true,
17671da12ec4SLe Tan     [VTD_FR_ROOT_TABLE_INV] = false,
17681da12ec4SLe Tan     [VTD_FR_CONTEXT_TABLE_INV] = false,
1769ea97a1bdSJason Wang     [VTD_FR_INTERRUPT_ADDR] = true,
17701da12ec4SLe Tan     [VTD_FR_ROOT_ENTRY_RSVD] = false,
17711da12ec4SLe Tan     [VTD_FR_PAGING_ENTRY_RSVD] = true,
17721da12ec4SLe Tan     [VTD_FR_CONTEXT_ENTRY_TT] = true,
1773fb43cf73SLiu, Yi L     [VTD_FR_PASID_TABLE_INV] = false,
1774ea97a1bdSJason Wang     [VTD_FR_SM_INTERRUPT_ADDR] = true,
17751da12ec4SLe Tan     [VTD_FR_MAX] = false,
17761da12ec4SLe Tan };
17771da12ec4SLe Tan 
17781da12ec4SLe Tan /* To see if a fault condition is "qualified", which is reported to software
17791da12ec4SLe Tan  * only if the FPD field in the context-entry used to process the faulting
17801da12ec4SLe Tan  * request is 0.
17811da12ec4SLe Tan  */
17821da12ec4SLe Tan static inline bool vtd_is_qualified_fault(VTDFaultReason fault)
17831da12ec4SLe Tan {
17841da12ec4SLe Tan     return vtd_qualified_faults[fault];
17851da12ec4SLe Tan }
17861da12ec4SLe Tan 
17871da12ec4SLe Tan static inline bool vtd_is_interrupt_addr(hwaddr addr)
17881da12ec4SLe Tan {
17891da12ec4SLe Tan     return VTD_INTERRUPT_ADDR_FIRST <= addr && addr <= VTD_INTERRUPT_ADDR_LAST;
17901da12ec4SLe Tan }
17911da12ec4SLe Tan 
1792da8d439cSJason Wang static gboolean vtd_find_as_by_sid(gpointer key, gpointer value,
1793da8d439cSJason Wang                                    gpointer user_data)
1794da8d439cSJason Wang {
1795da8d439cSJason Wang     struct vtd_as_key *as_key = (struct vtd_as_key *)key;
1796da8d439cSJason Wang     uint16_t target_sid = *(uint16_t *)user_data;
1797da8d439cSJason Wang     uint16_t sid = PCI_BUILD_BDF(pci_bus_num(as_key->bus), as_key->devfn);
1798da8d439cSJason Wang     return sid == target_sid;
1799da8d439cSJason Wang }
1800da8d439cSJason Wang 
1801da8d439cSJason Wang static VTDAddressSpace *vtd_get_as_by_sid(IntelIOMMUState *s, uint16_t sid)
1802da8d439cSJason Wang {
1803da8d439cSJason Wang     uint8_t bus_num = PCI_BUS_NUM(sid);
1804da8d439cSJason Wang     VTDAddressSpace *vtd_as = s->vtd_as_cache[bus_num];
1805da8d439cSJason Wang 
1806da8d439cSJason Wang     if (vtd_as &&
1807da8d439cSJason Wang         (sid == PCI_BUILD_BDF(pci_bus_num(vtd_as->bus), vtd_as->devfn))) {
1808da8d439cSJason Wang         return vtd_as;
1809da8d439cSJason Wang     }
1810da8d439cSJason Wang 
1811da8d439cSJason Wang     vtd_as = g_hash_table_find(s->vtd_address_spaces, vtd_find_as_by_sid, &sid);
1812da8d439cSJason Wang     s->vtd_as_cache[bus_num] = vtd_as;
1813da8d439cSJason Wang 
1814da8d439cSJason Wang     return vtd_as;
1815da8d439cSJason Wang }
1816da8d439cSJason Wang 
1817dbaabb25SPeter Xu static void vtd_pt_enable_fast_path(IntelIOMMUState *s, uint16_t source_id)
1818dbaabb25SPeter Xu {
1819dbaabb25SPeter Xu     VTDAddressSpace *vtd_as;
1820dbaabb25SPeter Xu     bool success = false;
1821dbaabb25SPeter Xu 
1822da8d439cSJason Wang     vtd_as = vtd_get_as_by_sid(s, source_id);
1823dbaabb25SPeter Xu     if (!vtd_as) {
1824dbaabb25SPeter Xu         goto out;
1825dbaabb25SPeter Xu     }
1826dbaabb25SPeter Xu 
1827dbaabb25SPeter Xu     if (vtd_switch_address_space(vtd_as) == false) {
1828dbaabb25SPeter Xu         /* We switched off IOMMU region successfully. */
1829dbaabb25SPeter Xu         success = true;
1830dbaabb25SPeter Xu     }
1831dbaabb25SPeter Xu 
1832dbaabb25SPeter Xu out:
1833dbaabb25SPeter Xu     trace_vtd_pt_enable_fast_path(source_id, success);
1834dbaabb25SPeter Xu }
1835dbaabb25SPeter Xu 
1836940e5527SJason Wang static void vtd_report_fault(IntelIOMMUState *s,
1837940e5527SJason Wang                              int err, bool is_fpd_set,
1838940e5527SJason Wang                              uint16_t source_id,
1839940e5527SJason Wang                              hwaddr addr,
18401b2b1237SJason Wang                              bool is_write,
18411b2b1237SJason Wang                              bool is_pasid,
18421b2b1237SJason Wang                              uint32_t pasid)
1843940e5527SJason Wang {
1844940e5527SJason Wang     if (is_fpd_set && vtd_is_qualified_fault(err)) {
1845940e5527SJason Wang         trace_vtd_fault_disabled();
1846940e5527SJason Wang     } else {
18471b2b1237SJason Wang         vtd_report_dmar_fault(s, source_id, addr, err, is_write,
18481b2b1237SJason Wang                               is_pasid, pasid);
1849940e5527SJason Wang     }
1850940e5527SJason Wang }
1851940e5527SJason Wang 
18521da12ec4SLe Tan /* Map dev to context-entry then do a paging-structures walk to do a iommu
18531da12ec4SLe Tan  * translation.
185479e2b9aeSPaolo Bonzini  *
185579e2b9aeSPaolo Bonzini  * Called from RCU critical section.
185679e2b9aeSPaolo Bonzini  *
18571da12ec4SLe Tan  * @bus_num: The bus number
18581da12ec4SLe Tan  * @devfn: The devfn, which is the  combined of device and function number
18591da12ec4SLe Tan  * @is_write: The access is a write operation
18601da12ec4SLe Tan  * @entry: IOMMUTLBEntry that contain the addr to be translated and result
1861b9313021SPeter Xu  *
1862b9313021SPeter Xu  * Returns true if translation is successful, otherwise false.
18631da12ec4SLe Tan  */
1864b9313021SPeter Xu static bool vtd_do_iommu_translate(VTDAddressSpace *vtd_as, PCIBus *bus,
18651da12ec4SLe Tan                                    uint8_t devfn, hwaddr addr, bool is_write,
18661da12ec4SLe Tan                                    IOMMUTLBEntry *entry)
18671da12ec4SLe Tan {
1868d92fa2dcSLe Tan     IntelIOMMUState *s = vtd_as->iommu_state;
18691da12ec4SLe Tan     VTDContextEntry ce;
18707df953bdSKnut Omang     uint8_t bus_num = pci_bus_num(bus);
18711d9efa73SPeter Xu     VTDContextCacheEntry *cc_entry;
1872d66b969bSJason Wang     uint64_t slpte, page_mask;
18731b2b1237SJason Wang     uint32_t level, pasid = vtd_as->pasid;
1874da8d439cSJason Wang     uint16_t source_id = PCI_BUILD_BDF(bus_num, devfn);
18751da12ec4SLe Tan     int ret_fr;
18761da12ec4SLe Tan     bool is_fpd_set = false;
18771da12ec4SLe Tan     bool reads = true;
18781da12ec4SLe Tan     bool writes = true;
187907f7b733SPeter Xu     uint8_t access_flags;
18801b2b1237SJason Wang     bool rid2pasid = (pasid == PCI_NO_PASID) && s->root_scalable;
1881b5a280c0SLe Tan     VTDIOTLBEntry *iotlb_entry;
18821da12ec4SLe Tan 
1883046ab7e9SPeter Xu     /*
1884046ab7e9SPeter Xu      * We have standalone memory region for interrupt addresses, we
1885046ab7e9SPeter Xu      * should never receive translation requests in this region.
18861da12ec4SLe Tan      */
1887046ab7e9SPeter Xu     assert(!vtd_is_interrupt_addr(addr));
1888046ab7e9SPeter Xu 
18891d9efa73SPeter Xu     vtd_iommu_lock(s);
18901d9efa73SPeter Xu 
18911d9efa73SPeter Xu     cc_entry = &vtd_as->context_cache_entry;
18921d9efa73SPeter Xu 
18931b2b1237SJason Wang     /* Try to fetch slpte form IOTLB, we don't need RID2PASID logic */
18941b2b1237SJason Wang     if (!rid2pasid) {
18951b2b1237SJason Wang         iotlb_entry = vtd_lookup_iotlb(s, source_id, pasid, addr);
1896b5a280c0SLe Tan         if (iotlb_entry) {
18976c441e1dSPeter Xu             trace_vtd_iotlb_page_hit(source_id, addr, iotlb_entry->slpte,
18986c441e1dSPeter Xu                                      iotlb_entry->domain_id);
1899b5a280c0SLe Tan             slpte = iotlb_entry->slpte;
190007f7b733SPeter Xu             access_flags = iotlb_entry->access_flags;
1901d66b969bSJason Wang             page_mask = iotlb_entry->mask;
1902b5a280c0SLe Tan             goto out;
1903b5a280c0SLe Tan         }
19041b2b1237SJason Wang     }
1905b9313021SPeter Xu 
1906d92fa2dcSLe Tan     /* Try to fetch context-entry from cache first */
1907d92fa2dcSLe Tan     if (cc_entry->context_cache_gen == s->context_cache_gen) {
19086c441e1dSPeter Xu         trace_vtd_iotlb_cc_hit(bus_num, devfn, cc_entry->context_entry.hi,
19096c441e1dSPeter Xu                                cc_entry->context_entry.lo,
19106c441e1dSPeter Xu                                cc_entry->context_cache_gen);
1911d92fa2dcSLe Tan         ce = cc_entry->context_entry;
1912d92fa2dcSLe Tan         is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;
1913fb43cf73SLiu, Yi L         if (!is_fpd_set && s->root_scalable) {
19141b2b1237SJason Wang             ret_fr = vtd_ce_get_pasid_fpd(s, &ce, &is_fpd_set, pasid);
1915940e5527SJason Wang             if (ret_fr) {
1916940e5527SJason Wang                 vtd_report_fault(s, -ret_fr, is_fpd_set,
19171b2b1237SJason Wang                                  source_id, addr, is_write,
19181b2b1237SJason Wang                                  false, 0);
1919940e5527SJason Wang                 goto error;
1920940e5527SJason Wang             }
1921fb43cf73SLiu, Yi L         }
1922d92fa2dcSLe Tan     } else {
19231da12ec4SLe Tan         ret_fr = vtd_dev_to_context_entry(s, bus_num, devfn, &ce);
19241da12ec4SLe Tan         is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;
1925fb43cf73SLiu, Yi L         if (!ret_fr && !is_fpd_set && s->root_scalable) {
19261b2b1237SJason Wang             ret_fr = vtd_ce_get_pasid_fpd(s, &ce, &is_fpd_set, pasid);
19271da12ec4SLe Tan         }
1928940e5527SJason Wang         if (ret_fr) {
1929940e5527SJason Wang             vtd_report_fault(s, -ret_fr, is_fpd_set,
19301b2b1237SJason Wang                              source_id, addr, is_write,
19311b2b1237SJason Wang                              false, 0);
1932940e5527SJason Wang             goto error;
1933940e5527SJason Wang         }
1934d92fa2dcSLe Tan         /* Update context-cache */
19356c441e1dSPeter Xu         trace_vtd_iotlb_cc_update(bus_num, devfn, ce.hi, ce.lo,
19366c441e1dSPeter Xu                                   cc_entry->context_cache_gen,
19376c441e1dSPeter Xu                                   s->context_cache_gen);
1938d92fa2dcSLe Tan         cc_entry->context_entry = ce;
1939d92fa2dcSLe Tan         cc_entry->context_cache_gen = s->context_cache_gen;
1940d92fa2dcSLe Tan     }
19411da12ec4SLe Tan 
19421b2b1237SJason Wang     if (rid2pasid) {
19431b2b1237SJason Wang         pasid = VTD_CE_GET_RID2PASID(&ce);
19441b2b1237SJason Wang     }
19451b2b1237SJason Wang 
1946dbaabb25SPeter Xu     /*
1947dbaabb25SPeter Xu      * We don't need to translate for pass-through context entries.
1948dbaabb25SPeter Xu      * Also, let's ignore IOTLB caching as well for PT devices.
1949dbaabb25SPeter Xu      */
19501b2b1237SJason Wang     if (vtd_dev_pt_enabled(s, &ce, pasid)) {
1951892721d9SPeter Xu         entry->iova = addr & VTD_PAGE_MASK_4K;
1952dbaabb25SPeter Xu         entry->translated_addr = entry->iova;
1953892721d9SPeter Xu         entry->addr_mask = ~VTD_PAGE_MASK_4K;
1954dbaabb25SPeter Xu         entry->perm = IOMMU_RW;
1955dbaabb25SPeter Xu         trace_vtd_translate_pt(source_id, entry->iova);
1956dbaabb25SPeter Xu 
1957dbaabb25SPeter Xu         /*
1958dbaabb25SPeter Xu          * When this happens, it means firstly caching-mode is not
1959dbaabb25SPeter Xu          * enabled, and this is the first passthrough translation for
1960dbaabb25SPeter Xu          * the device. Let's enable the fast path for passthrough.
1961dbaabb25SPeter Xu          *
1962dbaabb25SPeter Xu          * When passthrough is disabled again for the device, we can
1963dbaabb25SPeter Xu          * capture it via the context entry invalidation, then the
1964dbaabb25SPeter Xu          * IOMMU region can be swapped back.
1965dbaabb25SPeter Xu          */
1966dbaabb25SPeter Xu         vtd_pt_enable_fast_path(s, source_id);
19671d9efa73SPeter Xu         vtd_iommu_unlock(s);
1968b9313021SPeter Xu         return true;
1969dbaabb25SPeter Xu     }
1970dbaabb25SPeter Xu 
19711b2b1237SJason Wang     /* Try to fetch slpte form IOTLB for RID2PASID slow path */
19721b2b1237SJason Wang     if (rid2pasid) {
19731b2b1237SJason Wang         iotlb_entry = vtd_lookup_iotlb(s, source_id, pasid, addr);
19741b2b1237SJason Wang         if (iotlb_entry) {
19751b2b1237SJason Wang             trace_vtd_iotlb_page_hit(source_id, addr, iotlb_entry->slpte,
19761b2b1237SJason Wang                                      iotlb_entry->domain_id);
19771b2b1237SJason Wang             slpte = iotlb_entry->slpte;
19781b2b1237SJason Wang             access_flags = iotlb_entry->access_flags;
19791b2b1237SJason Wang             page_mask = iotlb_entry->mask;
19801b2b1237SJason Wang             goto out;
19811b2b1237SJason Wang         }
19821b2b1237SJason Wang     }
19831b2b1237SJason Wang 
1984fb43cf73SLiu, Yi L     ret_fr = vtd_iova_to_slpte(s, &ce, addr, is_write, &slpte, &level,
19851b2b1237SJason Wang                                &reads, &writes, s->aw_bits, pasid);
1986940e5527SJason Wang     if (ret_fr) {
1987940e5527SJason Wang         vtd_report_fault(s, -ret_fr, is_fpd_set, source_id,
19881b2b1237SJason Wang                          addr, is_write, pasid != PCI_NO_PASID, pasid);
1989940e5527SJason Wang         goto error;
1990940e5527SJason Wang     }
19911da12ec4SLe Tan 
1992d66b969bSJason Wang     page_mask = vtd_slpt_level_page_mask(level);
199307f7b733SPeter Xu     access_flags = IOMMU_ACCESS_FLAG(reads, writes);
19941b2b1237SJason Wang     vtd_update_iotlb(s, source_id, vtd_get_domain_id(s, &ce, pasid),
19951b2b1237SJason Wang                      addr, slpte, access_flags, level, pasid);
1996b5a280c0SLe Tan out:
19971d9efa73SPeter Xu     vtd_iommu_unlock(s);
1998d66b969bSJason Wang     entry->iova = addr & page_mask;
199937f51384SPrasad Singamsetty     entry->translated_addr = vtd_get_slpte_addr(slpte, s->aw_bits) & page_mask;
2000d66b969bSJason Wang     entry->addr_mask = ~page_mask;
200107f7b733SPeter Xu     entry->perm = access_flags;
2002b9313021SPeter Xu     return true;
2003b9313021SPeter Xu 
2004b9313021SPeter Xu error:
20051d9efa73SPeter Xu     vtd_iommu_unlock(s);
2006b9313021SPeter Xu     entry->iova = 0;
2007b9313021SPeter Xu     entry->translated_addr = 0;
2008b9313021SPeter Xu     entry->addr_mask = 0;
2009b9313021SPeter Xu     entry->perm = IOMMU_NONE;
2010b9313021SPeter Xu     return false;
20111da12ec4SLe Tan }
20121da12ec4SLe Tan 
20131da12ec4SLe Tan static void vtd_root_table_setup(IntelIOMMUState *s)
20141da12ec4SLe Tan {
20151da12ec4SLe Tan     s->root = vtd_get_quad_raw(s, DMAR_RTADDR_REG);
201637f51384SPrasad Singamsetty     s->root &= VTD_RTADDR_ADDR_MASK(s->aw_bits);
20171da12ec4SLe Tan 
20182811af3bSPeter Xu     vtd_update_scalable_state(s);
20192811af3bSPeter Xu 
202081fb1e64SPeter Xu     trace_vtd_reg_dmar_root(s->root, s->root_scalable);
20211da12ec4SLe Tan }
20221da12ec4SLe Tan 
202302a2cbc8SPeter Xu static void vtd_iec_notify_all(IntelIOMMUState *s, bool global,
202402a2cbc8SPeter Xu                                uint32_t index, uint32_t mask)
202502a2cbc8SPeter Xu {
202602a2cbc8SPeter Xu     x86_iommu_iec_notify_all(X86_IOMMU_DEVICE(s), global, index, mask);
202702a2cbc8SPeter Xu }
202802a2cbc8SPeter Xu 
2029a5861439SPeter Xu static void vtd_interrupt_remap_table_setup(IntelIOMMUState *s)
2030a5861439SPeter Xu {
2031a5861439SPeter Xu     uint64_t value = 0;
2032a5861439SPeter Xu     value = vtd_get_quad_raw(s, DMAR_IRTA_REG);
2033a5861439SPeter Xu     s->intr_size = 1UL << ((value & VTD_IRTA_SIZE_MASK) + 1);
203437f51384SPrasad Singamsetty     s->intr_root = value & VTD_IRTA_ADDR_MASK(s->aw_bits);
203528589311SJan Kiszka     s->intr_eime = value & VTD_IRTA_EIME;
2036a5861439SPeter Xu 
203702a2cbc8SPeter Xu     /* Notify global invalidation */
203802a2cbc8SPeter Xu     vtd_iec_notify_all(s, true, 0, 0);
2039a5861439SPeter Xu 
20407feb51b7SPeter Xu     trace_vtd_reg_ir_root(s->intr_root, s->intr_size);
2041a5861439SPeter Xu }
2042a5861439SPeter Xu 
2043dd4d607eSPeter Xu static void vtd_iommu_replay_all(IntelIOMMUState *s)
2044dd4d607eSPeter Xu {
2045b4a4ba0dSPeter Xu     VTDAddressSpace *vtd_as;
2046dd4d607eSPeter Xu 
2047b4a4ba0dSPeter Xu     QLIST_FOREACH(vtd_as, &s->vtd_as_with_notifiers, next) {
20483e090e34SPeter Xu         vtd_address_space_sync(vtd_as);
2049dd4d607eSPeter Xu     }
2050dd4d607eSPeter Xu }
2051dd4d607eSPeter Xu 
2052d92fa2dcSLe Tan static void vtd_context_global_invalidate(IntelIOMMUState *s)
2053d92fa2dcSLe Tan {
2054bc535e59SPeter Xu     trace_vtd_inv_desc_cc_global();
20551d9efa73SPeter Xu     /* Protects context cache */
20561d9efa73SPeter Xu     vtd_iommu_lock(s);
2057d92fa2dcSLe Tan     s->context_cache_gen++;
2058d92fa2dcSLe Tan     if (s->context_cache_gen == VTD_CONTEXT_CACHE_GEN_MAX) {
20591d9efa73SPeter Xu         vtd_reset_context_cache_locked(s);
2060d92fa2dcSLe Tan     }
20611d9efa73SPeter Xu     vtd_iommu_unlock(s);
20622cc9ddccSPeter Xu     vtd_address_space_refresh_all(s);
2063dd4d607eSPeter Xu     /*
2064dd4d607eSPeter Xu      * From VT-d spec 6.5.2.1, a global context entry invalidation
2065dd4d607eSPeter Xu      * should be followed by a IOTLB global invalidation, so we should
2066dd4d607eSPeter Xu      * be safe even without this. Hoewever, let's replay the region as
2067dd4d607eSPeter Xu      * well to be safer, and go back here when we need finer tunes for
2068dd4d607eSPeter Xu      * VT-d emulation codes.
2069dd4d607eSPeter Xu      */
2070dd4d607eSPeter Xu     vtd_iommu_replay_all(s);
2071d92fa2dcSLe Tan }
2072d92fa2dcSLe Tan 
2073d92fa2dcSLe Tan /* Do a context-cache device-selective invalidation.
2074d92fa2dcSLe Tan  * @func_mask: FM field after shifting
2075d92fa2dcSLe Tan  */
2076d92fa2dcSLe Tan static void vtd_context_device_invalidate(IntelIOMMUState *s,
2077d92fa2dcSLe Tan                                           uint16_t source_id,
2078d92fa2dcSLe Tan                                           uint16_t func_mask)
2079d92fa2dcSLe Tan {
2080da8d439cSJason Wang     GHashTableIter as_it;
2081d92fa2dcSLe Tan     uint16_t mask;
2082d92fa2dcSLe Tan     VTDAddressSpace *vtd_as;
2083bc535e59SPeter Xu     uint8_t bus_n, devfn;
2084d92fa2dcSLe Tan 
2085bc535e59SPeter Xu     trace_vtd_inv_desc_cc_devices(source_id, func_mask);
2086bc535e59SPeter Xu 
2087d92fa2dcSLe Tan     switch (func_mask & 3) {
2088d92fa2dcSLe Tan     case 0:
2089d92fa2dcSLe Tan         mask = 0;   /* No bits in the SID field masked */
2090d92fa2dcSLe Tan         break;
2091d92fa2dcSLe Tan     case 1:
2092d92fa2dcSLe Tan         mask = 4;   /* Mask bit 2 in the SID field */
2093d92fa2dcSLe Tan         break;
2094d92fa2dcSLe Tan     case 2:
2095d92fa2dcSLe Tan         mask = 6;   /* Mask bit 2:1 in the SID field */
2096d92fa2dcSLe Tan         break;
2097d92fa2dcSLe Tan     case 3:
2098d92fa2dcSLe Tan         mask = 7;   /* Mask bit 2:0 in the SID field */
2099d92fa2dcSLe Tan         break;
210041ce9a91SEric Auger     default:
210141ce9a91SEric Auger         g_assert_not_reached();
2102d92fa2dcSLe Tan     }
21036cb99accSPeter Xu     mask = ~mask;
2104bc535e59SPeter Xu 
2105bc535e59SPeter Xu     bus_n = VTD_SID_TO_BUS(source_id);
2106d92fa2dcSLe Tan     devfn = VTD_SID_TO_DEVFN(source_id);
2107da8d439cSJason Wang 
2108da8d439cSJason Wang     g_hash_table_iter_init(&as_it, s->vtd_address_spaces);
2109da8d439cSJason Wang     while (g_hash_table_iter_next(&as_it, NULL, (void **)&vtd_as)) {
2110da8d439cSJason Wang         if ((pci_bus_num(vtd_as->bus) == bus_n) &&
2111da8d439cSJason Wang             (vtd_as->devfn & mask) == (devfn & mask)) {
2112da8d439cSJason Wang             trace_vtd_inv_desc_cc_device(bus_n, VTD_PCI_SLOT(vtd_as->devfn),
2113da8d439cSJason Wang                                          VTD_PCI_FUNC(vtd_as->devfn));
21141d9efa73SPeter Xu             vtd_iommu_lock(s);
2115d92fa2dcSLe Tan             vtd_as->context_cache_entry.context_cache_gen = 0;
21161d9efa73SPeter Xu             vtd_iommu_unlock(s);
2117dd4d607eSPeter Xu             /*
2118dbaabb25SPeter Xu              * Do switch address space when needed, in case if the
2119dbaabb25SPeter Xu              * device passthrough bit is switched.
2120dbaabb25SPeter Xu              */
2121dbaabb25SPeter Xu             vtd_switch_address_space(vtd_as);
2122dbaabb25SPeter Xu             /*
2123dd4d607eSPeter Xu              * So a device is moving out of (or moving into) a
212463b88968SPeter Xu              * domain, resync the shadow page table.
2125dd4d607eSPeter Xu              * This won't bring bad even if we have no such
2126dd4d607eSPeter Xu              * notifier registered - the IOMMU notification
2127dd4d607eSPeter Xu              * framework will skip MAP notifications if that
2128dd4d607eSPeter Xu              * happened.
2129dd4d607eSPeter Xu              */
21303e090e34SPeter Xu             vtd_address_space_sync(vtd_as);
2131d92fa2dcSLe Tan         }
2132d92fa2dcSLe Tan     }
2133d92fa2dcSLe Tan }
2134d92fa2dcSLe Tan 
21351da12ec4SLe Tan /* Context-cache invalidation
21361da12ec4SLe Tan  * Returns the Context Actual Invalidation Granularity.
21371da12ec4SLe Tan  * @val: the content of the CCMD_REG
21381da12ec4SLe Tan  */
21391da12ec4SLe Tan static uint64_t vtd_context_cache_invalidate(IntelIOMMUState *s, uint64_t val)
21401da12ec4SLe Tan {
21411da12ec4SLe Tan     uint64_t caig;
21421da12ec4SLe Tan     uint64_t type = val & VTD_CCMD_CIRG_MASK;
21431da12ec4SLe Tan 
21441da12ec4SLe Tan     switch (type) {
21451da12ec4SLe Tan     case VTD_CCMD_DOMAIN_INVL:
2146d92fa2dcSLe Tan         /* Fall through */
2147d92fa2dcSLe Tan     case VTD_CCMD_GLOBAL_INVL:
2148d92fa2dcSLe Tan         caig = VTD_CCMD_GLOBAL_INVL_A;
2149d92fa2dcSLe Tan         vtd_context_global_invalidate(s);
21501da12ec4SLe Tan         break;
21511da12ec4SLe Tan 
21521da12ec4SLe Tan     case VTD_CCMD_DEVICE_INVL:
21531da12ec4SLe Tan         caig = VTD_CCMD_DEVICE_INVL_A;
2154d92fa2dcSLe Tan         vtd_context_device_invalidate(s, VTD_CCMD_SID(val), VTD_CCMD_FM(val));
21551da12ec4SLe Tan         break;
21561da12ec4SLe Tan 
21571da12ec4SLe Tan     default:
21581376211fSPeter Xu         error_report_once("%s: invalid context: 0x%" PRIx64,
21591376211fSPeter Xu                           __func__, val);
21601da12ec4SLe Tan         caig = 0;
21611da12ec4SLe Tan     }
21621da12ec4SLe Tan     return caig;
21631da12ec4SLe Tan }
21641da12ec4SLe Tan 
2165b5a280c0SLe Tan static void vtd_iotlb_global_invalidate(IntelIOMMUState *s)
2166b5a280c0SLe Tan {
21677feb51b7SPeter Xu     trace_vtd_inv_desc_iotlb_global();
2168b5a280c0SLe Tan     vtd_reset_iotlb(s);
2169dd4d607eSPeter Xu     vtd_iommu_replay_all(s);
2170b5a280c0SLe Tan }
2171b5a280c0SLe Tan 
2172b5a280c0SLe Tan static void vtd_iotlb_domain_invalidate(IntelIOMMUState *s, uint16_t domain_id)
2173b5a280c0SLe Tan {
2174dd4d607eSPeter Xu     VTDContextEntry ce;
2175dd4d607eSPeter Xu     VTDAddressSpace *vtd_as;
2176dd4d607eSPeter Xu 
21777feb51b7SPeter Xu     trace_vtd_inv_desc_iotlb_domain(domain_id);
21787feb51b7SPeter Xu 
21791d9efa73SPeter Xu     vtd_iommu_lock(s);
2180b5a280c0SLe Tan     g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_domain,
2181b5a280c0SLe Tan                                 &domain_id);
21821d9efa73SPeter Xu     vtd_iommu_unlock(s);
2183dd4d607eSPeter Xu 
2184b4a4ba0dSPeter Xu     QLIST_FOREACH(vtd_as, &s->vtd_as_with_notifiers, next) {
2185dd4d607eSPeter Xu         if (!vtd_dev_to_context_entry(s, pci_bus_num(vtd_as->bus),
2186dd4d607eSPeter Xu                                       vtd_as->devfn, &ce) &&
21871b2b1237SJason Wang             domain_id == vtd_get_domain_id(s, &ce, vtd_as->pasid)) {
21883e090e34SPeter Xu             vtd_address_space_sync(vtd_as);
2189dd4d607eSPeter Xu         }
2190dd4d607eSPeter Xu     }
2191dd4d607eSPeter Xu }
2192dd4d607eSPeter Xu 
2193dd4d607eSPeter Xu static void vtd_iotlb_page_invalidate_notify(IntelIOMMUState *s,
2194dd4d607eSPeter Xu                                            uint16_t domain_id, hwaddr addr,
21951b2b1237SJason Wang                                              uint8_t am, uint32_t pasid)
2196dd4d607eSPeter Xu {
2197b4a4ba0dSPeter Xu     VTDAddressSpace *vtd_as;
2198dd4d607eSPeter Xu     VTDContextEntry ce;
2199dd4d607eSPeter Xu     int ret;
22004f8a62a9SPeter Xu     hwaddr size = (1 << am) * VTD_PAGE_SIZE;
2201dd4d607eSPeter Xu 
2202b4a4ba0dSPeter Xu     QLIST_FOREACH(vtd_as, &(s->vtd_as_with_notifiers), next) {
22031b2b1237SJason Wang         if (pasid != PCI_NO_PASID && pasid != vtd_as->pasid) {
22041b2b1237SJason Wang             continue;
22051b2b1237SJason Wang         }
2206dd4d607eSPeter Xu         ret = vtd_dev_to_context_entry(s, pci_bus_num(vtd_as->bus),
2207dd4d607eSPeter Xu                                        vtd_as->devfn, &ce);
22081b2b1237SJason Wang         if (!ret && domain_id == vtd_get_domain_id(s, &ce, vtd_as->pasid)) {
22094f8a62a9SPeter Xu             if (vtd_as_has_map_notifier(vtd_as)) {
22104f8a62a9SPeter Xu                 /*
22114f8a62a9SPeter Xu                  * As long as we have MAP notifications registered in
22124f8a62a9SPeter Xu                  * any of our IOMMU notifiers, we need to sync the
22134f8a62a9SPeter Xu                  * shadow page table.
22144f8a62a9SPeter Xu                  */
221563b88968SPeter Xu                 vtd_sync_shadow_page_table_range(vtd_as, &ce, addr, size);
22164f8a62a9SPeter Xu             } else {
22174f8a62a9SPeter Xu                 /*
22184f8a62a9SPeter Xu                  * For UNMAP-only notifiers, we don't need to walk the
22194f8a62a9SPeter Xu                  * page tables.  We just deliver the PSI down to
22204f8a62a9SPeter Xu                  * invalidate caches.
22214f8a62a9SPeter Xu                  */
22225039caf3SEugenio Pérez                 IOMMUTLBEvent event = {
22235039caf3SEugenio Pérez                     .type = IOMMU_NOTIFIER_UNMAP,
22245039caf3SEugenio Pérez                     .entry = {
22254f8a62a9SPeter Xu                         .target_as = &address_space_memory,
22264f8a62a9SPeter Xu                         .iova = addr,
22274f8a62a9SPeter Xu                         .translated_addr = 0,
22284f8a62a9SPeter Xu                         .addr_mask = size - 1,
22294f8a62a9SPeter Xu                         .perm = IOMMU_NONE,
22305039caf3SEugenio Pérez                     },
22314f8a62a9SPeter Xu                 };
22325039caf3SEugenio Pérez                 memory_region_notify_iommu(&vtd_as->iommu, 0, event);
22334f8a62a9SPeter Xu             }
2234dd4d607eSPeter Xu         }
2235dd4d607eSPeter Xu     }
2236b5a280c0SLe Tan }
2237b5a280c0SLe Tan 
2238b5a280c0SLe Tan static void vtd_iotlb_page_invalidate(IntelIOMMUState *s, uint16_t domain_id,
2239b5a280c0SLe Tan                                       hwaddr addr, uint8_t am)
2240b5a280c0SLe Tan {
2241b5a280c0SLe Tan     VTDIOTLBPageInvInfo info;
2242b5a280c0SLe Tan 
22437feb51b7SPeter Xu     trace_vtd_inv_desc_iotlb_pages(domain_id, addr, am);
22447feb51b7SPeter Xu 
2245b5a280c0SLe Tan     assert(am <= VTD_MAMV);
2246b5a280c0SLe Tan     info.domain_id = domain_id;
2247d66b969bSJason Wang     info.addr = addr;
2248b5a280c0SLe Tan     info.mask = ~((1 << am) - 1);
22491d9efa73SPeter Xu     vtd_iommu_lock(s);
2250b5a280c0SLe Tan     g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_page, &info);
22511d9efa73SPeter Xu     vtd_iommu_unlock(s);
22521b2b1237SJason Wang     vtd_iotlb_page_invalidate_notify(s, domain_id, addr, am, PCI_NO_PASID);
2253b5a280c0SLe Tan }
2254b5a280c0SLe Tan 
22551da12ec4SLe Tan /* Flush IOTLB
22561da12ec4SLe Tan  * Returns the IOTLB Actual Invalidation Granularity.
22571da12ec4SLe Tan  * @val: the content of the IOTLB_REG
22581da12ec4SLe Tan  */
22591da12ec4SLe Tan static uint64_t vtd_iotlb_flush(IntelIOMMUState *s, uint64_t val)
22601da12ec4SLe Tan {
22611da12ec4SLe Tan     uint64_t iaig;
22621da12ec4SLe Tan     uint64_t type = val & VTD_TLB_FLUSH_GRANU_MASK;
2263b5a280c0SLe Tan     uint16_t domain_id;
2264b5a280c0SLe Tan     hwaddr addr;
2265b5a280c0SLe Tan     uint8_t am;
22661da12ec4SLe Tan 
22671da12ec4SLe Tan     switch (type) {
22681da12ec4SLe Tan     case VTD_TLB_GLOBAL_FLUSH:
22691da12ec4SLe Tan         iaig = VTD_TLB_GLOBAL_FLUSH_A;
2270b5a280c0SLe Tan         vtd_iotlb_global_invalidate(s);
22711da12ec4SLe Tan         break;
22721da12ec4SLe Tan 
22731da12ec4SLe Tan     case VTD_TLB_DSI_FLUSH:
2274b5a280c0SLe Tan         domain_id = VTD_TLB_DID(val);
22751da12ec4SLe Tan         iaig = VTD_TLB_DSI_FLUSH_A;
2276b5a280c0SLe Tan         vtd_iotlb_domain_invalidate(s, domain_id);
22771da12ec4SLe Tan         break;
22781da12ec4SLe Tan 
22791da12ec4SLe Tan     case VTD_TLB_PSI_FLUSH:
2280b5a280c0SLe Tan         domain_id = VTD_TLB_DID(val);
2281b5a280c0SLe Tan         addr = vtd_get_quad_raw(s, DMAR_IVA_REG);
2282b5a280c0SLe Tan         am = VTD_IVA_AM(addr);
2283b5a280c0SLe Tan         addr = VTD_IVA_ADDR(addr);
2284b5a280c0SLe Tan         if (am > VTD_MAMV) {
22851376211fSPeter Xu             error_report_once("%s: address mask overflow: 0x%" PRIx64,
22861376211fSPeter Xu                               __func__, vtd_get_quad_raw(s, DMAR_IVA_REG));
2287b5a280c0SLe Tan             iaig = 0;
2288b5a280c0SLe Tan             break;
2289b5a280c0SLe Tan         }
22901da12ec4SLe Tan         iaig = VTD_TLB_PSI_FLUSH_A;
2291b5a280c0SLe Tan         vtd_iotlb_page_invalidate(s, domain_id, addr, am);
22921da12ec4SLe Tan         break;
22931da12ec4SLe Tan 
22941da12ec4SLe Tan     default:
22951376211fSPeter Xu         error_report_once("%s: invalid granularity: 0x%" PRIx64,
22961376211fSPeter Xu                           __func__, val);
22971da12ec4SLe Tan         iaig = 0;
22981da12ec4SLe Tan     }
22991da12ec4SLe Tan     return iaig;
23001da12ec4SLe Tan }
23011da12ec4SLe Tan 
23028991c460SLadi Prosek static void vtd_fetch_inv_desc(IntelIOMMUState *s);
2303ed7b8fbcSLe Tan 
2304ed7b8fbcSLe Tan static inline bool vtd_queued_inv_disable_check(IntelIOMMUState *s)
2305ed7b8fbcSLe Tan {
2306ed7b8fbcSLe Tan     return s->qi_enabled && (s->iq_tail == s->iq_head) &&
2307ed7b8fbcSLe Tan            (s->iq_last_desc_type == VTD_INV_DESC_WAIT);
2308ed7b8fbcSLe Tan }
2309ed7b8fbcSLe Tan 
2310ed7b8fbcSLe Tan static void vtd_handle_gcmd_qie(IntelIOMMUState *s, bool en)
2311ed7b8fbcSLe Tan {
2312ed7b8fbcSLe Tan     uint64_t iqa_val = vtd_get_quad_raw(s, DMAR_IQA_REG);
2313ed7b8fbcSLe Tan 
23147feb51b7SPeter Xu     trace_vtd_inv_qi_enable(en);
23157feb51b7SPeter Xu 
2316ed7b8fbcSLe Tan     if (en) {
231737f51384SPrasad Singamsetty         s->iq = iqa_val & VTD_IQA_IQA_MASK(s->aw_bits);
2318ed7b8fbcSLe Tan         /* 2^(x+8) entries */
2319c0c1d351SLiu, Yi L         s->iq_size = 1UL << ((iqa_val & VTD_IQA_QS) + 8 - (s->iq_dw ? 1 : 0));
2320ed7b8fbcSLe Tan         s->qi_enabled = true;
23217feb51b7SPeter Xu         trace_vtd_inv_qi_setup(s->iq, s->iq_size);
2322ed7b8fbcSLe Tan         /* Ok - report back to driver */
2323ed7b8fbcSLe Tan         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_QIES);
23248991c460SLadi Prosek 
23258991c460SLadi Prosek         if (s->iq_tail != 0) {
23268991c460SLadi Prosek             /*
23278991c460SLadi Prosek              * This is a spec violation but Windows guests are known to set up
23288991c460SLadi Prosek              * Queued Invalidation this way so we allow the write and process
23298991c460SLadi Prosek              * Invalidation Descriptors right away.
23308991c460SLadi Prosek              */
23318991c460SLadi Prosek             trace_vtd_warn_invalid_qi_tail(s->iq_tail);
23328991c460SLadi Prosek             if (!(vtd_get_long_raw(s, DMAR_FSTS_REG) & VTD_FSTS_IQE)) {
23338991c460SLadi Prosek                 vtd_fetch_inv_desc(s);
23348991c460SLadi Prosek             }
2335ed7b8fbcSLe Tan         }
2336ed7b8fbcSLe Tan     } else {
2337ed7b8fbcSLe Tan         if (vtd_queued_inv_disable_check(s)) {
2338ed7b8fbcSLe Tan             /* disable Queued Invalidation */
2339ed7b8fbcSLe Tan             vtd_set_quad_raw(s, DMAR_IQH_REG, 0);
2340ed7b8fbcSLe Tan             s->iq_head = 0;
2341ed7b8fbcSLe Tan             s->qi_enabled = false;
2342ed7b8fbcSLe Tan             /* Ok - report back to driver */
2343ed7b8fbcSLe Tan             vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_QIES, 0);
2344ed7b8fbcSLe Tan         } else {
23454e4abd11SPeter Xu             error_report_once("%s: detected improper state when disable QI "
23464e4abd11SPeter Xu                               "(head=0x%x, tail=0x%x, last_type=%d)",
23474e4abd11SPeter Xu                               __func__,
23484e4abd11SPeter Xu                               s->iq_head, s->iq_tail, s->iq_last_desc_type);
2349ed7b8fbcSLe Tan         }
2350ed7b8fbcSLe Tan     }
2351ed7b8fbcSLe Tan }
2352ed7b8fbcSLe Tan 
23531da12ec4SLe Tan /* Set Root Table Pointer */
23541da12ec4SLe Tan static void vtd_handle_gcmd_srtp(IntelIOMMUState *s)
23551da12ec4SLe Tan {
23561da12ec4SLe Tan     vtd_root_table_setup(s);
23571da12ec4SLe Tan     /* Ok - report back to driver */
23581da12ec4SLe Tan     vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_RTPS);
23592cc9ddccSPeter Xu     vtd_reset_caches(s);
23602cc9ddccSPeter Xu     vtd_address_space_refresh_all(s);
23611da12ec4SLe Tan }
23621da12ec4SLe Tan 
2363a5861439SPeter Xu /* Set Interrupt Remap Table Pointer */
2364a5861439SPeter Xu static void vtd_handle_gcmd_sirtp(IntelIOMMUState *s)
2365a5861439SPeter Xu {
2366a5861439SPeter Xu     vtd_interrupt_remap_table_setup(s);
2367a5861439SPeter Xu     /* Ok - report back to driver */
2368a5861439SPeter Xu     vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_IRTPS);
2369a5861439SPeter Xu }
2370a5861439SPeter Xu 
23711da12ec4SLe Tan /* Handle Translation Enable/Disable */
23721da12ec4SLe Tan static void vtd_handle_gcmd_te(IntelIOMMUState *s, bool en)
23731da12ec4SLe Tan {
2374558e0024SPeter Xu     if (s->dmar_enabled == en) {
2375558e0024SPeter Xu         return;
2376558e0024SPeter Xu     }
2377558e0024SPeter Xu 
23787feb51b7SPeter Xu     trace_vtd_dmar_enable(en);
23791da12ec4SLe Tan 
23801da12ec4SLe Tan     if (en) {
23811da12ec4SLe Tan         s->dmar_enabled = true;
23821da12ec4SLe Tan         /* Ok - report back to driver */
23831da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_TES);
23841da12ec4SLe Tan     } else {
23851da12ec4SLe Tan         s->dmar_enabled = false;
23861da12ec4SLe Tan 
23871da12ec4SLe Tan         /* Clear the index of Fault Recording Register */
23881da12ec4SLe Tan         s->next_frcd_reg = 0;
23891da12ec4SLe Tan         /* Ok - report back to driver */
23901da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_TES, 0);
23911da12ec4SLe Tan     }
2392558e0024SPeter Xu 
23932cc9ddccSPeter Xu     vtd_reset_caches(s);
23942cc9ddccSPeter Xu     vtd_address_space_refresh_all(s);
23951da12ec4SLe Tan }
23961da12ec4SLe Tan 
239780de52baSPeter Xu /* Handle Interrupt Remap Enable/Disable */
239880de52baSPeter Xu static void vtd_handle_gcmd_ire(IntelIOMMUState *s, bool en)
239980de52baSPeter Xu {
24007feb51b7SPeter Xu     trace_vtd_ir_enable(en);
240180de52baSPeter Xu 
240280de52baSPeter Xu     if (en) {
240380de52baSPeter Xu         s->intr_enabled = true;
240480de52baSPeter Xu         /* Ok - report back to driver */
240580de52baSPeter Xu         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_IRES);
240680de52baSPeter Xu     } else {
240780de52baSPeter Xu         s->intr_enabled = false;
240880de52baSPeter Xu         /* Ok - report back to driver */
240980de52baSPeter Xu         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_IRES, 0);
241080de52baSPeter Xu     }
241180de52baSPeter Xu }
241280de52baSPeter Xu 
24131da12ec4SLe Tan /* Handle write to Global Command Register */
24141da12ec4SLe Tan static void vtd_handle_gcmd_write(IntelIOMMUState *s)
24151da12ec4SLe Tan {
2416175f3a59SDavid Woodhouse     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
24171da12ec4SLe Tan     uint32_t status = vtd_get_long_raw(s, DMAR_GSTS_REG);
24181da12ec4SLe Tan     uint32_t val = vtd_get_long_raw(s, DMAR_GCMD_REG);
24191da12ec4SLe Tan     uint32_t changed = status ^ val;
24201da12ec4SLe Tan 
24217feb51b7SPeter Xu     trace_vtd_reg_write_gcmd(status, val);
24228646d9c7SDavid Woodhouse     if ((changed & VTD_GCMD_TE) && s->dma_translation) {
24231da12ec4SLe Tan         /* Translation enable/disable */
24241da12ec4SLe Tan         vtd_handle_gcmd_te(s, val & VTD_GCMD_TE);
24251da12ec4SLe Tan     }
24261da12ec4SLe Tan     if (val & VTD_GCMD_SRTP) {
24271da12ec4SLe Tan         /* Set/update the root-table pointer */
24281da12ec4SLe Tan         vtd_handle_gcmd_srtp(s);
24291da12ec4SLe Tan     }
2430ed7b8fbcSLe Tan     if (changed & VTD_GCMD_QIE) {
2431ed7b8fbcSLe Tan         /* Queued Invalidation Enable */
2432ed7b8fbcSLe Tan         vtd_handle_gcmd_qie(s, val & VTD_GCMD_QIE);
2433ed7b8fbcSLe Tan     }
2434a5861439SPeter Xu     if (val & VTD_GCMD_SIRTP) {
2435a5861439SPeter Xu         /* Set/update the interrupt remapping root-table pointer */
2436a5861439SPeter Xu         vtd_handle_gcmd_sirtp(s);
2437a5861439SPeter Xu     }
2438175f3a59SDavid Woodhouse     if ((changed & VTD_GCMD_IRE) &&
2439175f3a59SDavid Woodhouse         x86_iommu_ir_supported(x86_iommu)) {
244080de52baSPeter Xu         /* Interrupt remap enable/disable */
244180de52baSPeter Xu         vtd_handle_gcmd_ire(s, val & VTD_GCMD_IRE);
244280de52baSPeter Xu     }
24431da12ec4SLe Tan }
24441da12ec4SLe Tan 
24451da12ec4SLe Tan /* Handle write to Context Command Register */
24461da12ec4SLe Tan static void vtd_handle_ccmd_write(IntelIOMMUState *s)
24471da12ec4SLe Tan {
24481da12ec4SLe Tan     uint64_t ret;
24491da12ec4SLe Tan     uint64_t val = vtd_get_quad_raw(s, DMAR_CCMD_REG);
24501da12ec4SLe Tan 
24511da12ec4SLe Tan     /* Context-cache invalidation request */
24521da12ec4SLe Tan     if (val & VTD_CCMD_ICC) {
2453ed7b8fbcSLe Tan         if (s->qi_enabled) {
24541376211fSPeter Xu             error_report_once("Queued Invalidation enabled, "
2455ed7b8fbcSLe Tan                               "should not use register-based invalidation");
2456ed7b8fbcSLe Tan             return;
2457ed7b8fbcSLe Tan         }
24581da12ec4SLe Tan         ret = vtd_context_cache_invalidate(s, val);
24591da12ec4SLe Tan         /* Invalidation completed. Change something to show */
24601da12ec4SLe Tan         vtd_set_clear_mask_quad(s, DMAR_CCMD_REG, VTD_CCMD_ICC, 0ULL);
24611da12ec4SLe Tan         ret = vtd_set_clear_mask_quad(s, DMAR_CCMD_REG, VTD_CCMD_CAIG_MASK,
24621da12ec4SLe Tan                                       ret);
24631da12ec4SLe Tan     }
24641da12ec4SLe Tan }
24651da12ec4SLe Tan 
24661da12ec4SLe Tan /* Handle write to IOTLB Invalidation Register */
24671da12ec4SLe Tan static void vtd_handle_iotlb_write(IntelIOMMUState *s)
24681da12ec4SLe Tan {
24691da12ec4SLe Tan     uint64_t ret;
24701da12ec4SLe Tan     uint64_t val = vtd_get_quad_raw(s, DMAR_IOTLB_REG);
24711da12ec4SLe Tan 
24721da12ec4SLe Tan     /* IOTLB invalidation request */
24731da12ec4SLe Tan     if (val & VTD_TLB_IVT) {
2474ed7b8fbcSLe Tan         if (s->qi_enabled) {
24751376211fSPeter Xu             error_report_once("Queued Invalidation enabled, "
24761376211fSPeter Xu                               "should not use register-based invalidation");
2477ed7b8fbcSLe Tan             return;
2478ed7b8fbcSLe Tan         }
24791da12ec4SLe Tan         ret = vtd_iotlb_flush(s, val);
24801da12ec4SLe Tan         /* Invalidation completed. Change something to show */
24811da12ec4SLe Tan         vtd_set_clear_mask_quad(s, DMAR_IOTLB_REG, VTD_TLB_IVT, 0ULL);
24821da12ec4SLe Tan         ret = vtd_set_clear_mask_quad(s, DMAR_IOTLB_REG,
24831da12ec4SLe Tan                                       VTD_TLB_FLUSH_GRANU_MASK_A, ret);
24841da12ec4SLe Tan     }
24851da12ec4SLe Tan }
24861da12ec4SLe Tan 
2487ed7b8fbcSLe Tan /* Fetch an Invalidation Descriptor from the Invalidation Queue */
2488c0c1d351SLiu, Yi L static bool vtd_get_inv_desc(IntelIOMMUState *s,
2489ed7b8fbcSLe Tan                              VTDInvDesc *inv_desc)
2490ed7b8fbcSLe Tan {
2491c0c1d351SLiu, Yi L     dma_addr_t base_addr = s->iq;
2492c0c1d351SLiu, Yi L     uint32_t offset = s->iq_head;
2493c0c1d351SLiu, Yi L     uint32_t dw = s->iq_dw ? 32 : 16;
2494c0c1d351SLiu, Yi L     dma_addr_t addr = base_addr + offset * dw;
2495c0c1d351SLiu, Yi L 
2496ba06fe8aSPhilippe Mathieu-Daudé     if (dma_memory_read(&address_space_memory, addr,
2497ba06fe8aSPhilippe Mathieu-Daudé                         inv_desc, dw, MEMTXATTRS_UNSPECIFIED)) {
2498c0c1d351SLiu, Yi L         error_report_once("Read INV DESC failed.");
2499ed7b8fbcSLe Tan         return false;
2500ed7b8fbcSLe Tan     }
2501ed7b8fbcSLe Tan     inv_desc->lo = le64_to_cpu(inv_desc->lo);
2502ed7b8fbcSLe Tan     inv_desc->hi = le64_to_cpu(inv_desc->hi);
2503c0c1d351SLiu, Yi L     if (dw == 32) {
2504c0c1d351SLiu, Yi L         inv_desc->val[2] = le64_to_cpu(inv_desc->val[2]);
2505c0c1d351SLiu, Yi L         inv_desc->val[3] = le64_to_cpu(inv_desc->val[3]);
2506c0c1d351SLiu, Yi L     }
2507ed7b8fbcSLe Tan     return true;
2508ed7b8fbcSLe Tan }
2509ed7b8fbcSLe Tan 
2510ed7b8fbcSLe Tan static bool vtd_process_wait_desc(IntelIOMMUState *s, VTDInvDesc *inv_desc)
2511ed7b8fbcSLe Tan {
2512ed7b8fbcSLe Tan     if ((inv_desc->hi & VTD_INV_DESC_WAIT_RSVD_HI) ||
2513ed7b8fbcSLe Tan         (inv_desc->lo & VTD_INV_DESC_WAIT_RSVD_LO)) {
2514095955b2SPeter Xu         error_report_once("%s: invalid wait desc: hi=%"PRIx64", lo=%"PRIx64
2515095955b2SPeter Xu                           " (reserved nonzero)", __func__, inv_desc->hi,
2516095955b2SPeter Xu                           inv_desc->lo);
2517ed7b8fbcSLe Tan         return false;
2518ed7b8fbcSLe Tan     }
2519ed7b8fbcSLe Tan     if (inv_desc->lo & VTD_INV_DESC_WAIT_SW) {
2520ed7b8fbcSLe Tan         /* Status Write */
2521ed7b8fbcSLe Tan         uint32_t status_data = (uint32_t)(inv_desc->lo >>
2522ed7b8fbcSLe Tan                                VTD_INV_DESC_WAIT_DATA_SHIFT);
2523ed7b8fbcSLe Tan 
2524ed7b8fbcSLe Tan         assert(!(inv_desc->lo & VTD_INV_DESC_WAIT_IF));
2525ed7b8fbcSLe Tan 
2526ed7b8fbcSLe Tan         /* FIXME: need to be masked with HAW? */
2527ed7b8fbcSLe Tan         dma_addr_t status_addr = inv_desc->hi;
2528bc535e59SPeter Xu         trace_vtd_inv_desc_wait_sw(status_addr, status_data);
2529ed7b8fbcSLe Tan         status_data = cpu_to_le32(status_data);
2530ba06fe8aSPhilippe Mathieu-Daudé         if (dma_memory_write(&address_space_memory, status_addr,
2531ba06fe8aSPhilippe Mathieu-Daudé                              &status_data, sizeof(status_data),
2532ba06fe8aSPhilippe Mathieu-Daudé                              MEMTXATTRS_UNSPECIFIED)) {
2533bc535e59SPeter Xu             trace_vtd_inv_desc_wait_write_fail(inv_desc->hi, inv_desc->lo);
2534ed7b8fbcSLe Tan             return false;
2535ed7b8fbcSLe Tan         }
2536ed7b8fbcSLe Tan     } else if (inv_desc->lo & VTD_INV_DESC_WAIT_IF) {
2537ed7b8fbcSLe Tan         /* Interrupt flag */
2538ed7b8fbcSLe Tan         vtd_generate_completion_event(s);
2539ed7b8fbcSLe Tan     } else {
2540095955b2SPeter Xu         error_report_once("%s: invalid wait desc: hi=%"PRIx64", lo=%"PRIx64
2541095955b2SPeter Xu                           " (unknown type)", __func__, inv_desc->hi,
2542095955b2SPeter Xu                           inv_desc->lo);
2543ed7b8fbcSLe Tan         return false;
2544ed7b8fbcSLe Tan     }
2545ed7b8fbcSLe Tan     return true;
2546ed7b8fbcSLe Tan }
2547ed7b8fbcSLe Tan 
2548d92fa2dcSLe Tan static bool vtd_process_context_cache_desc(IntelIOMMUState *s,
2549d92fa2dcSLe Tan                                            VTDInvDesc *inv_desc)
2550d92fa2dcSLe Tan {
2551bc535e59SPeter Xu     uint16_t sid, fmask;
2552bc535e59SPeter Xu 
2553d92fa2dcSLe Tan     if ((inv_desc->lo & VTD_INV_DESC_CC_RSVD) || inv_desc->hi) {
2554095955b2SPeter Xu         error_report_once("%s: invalid cc inv desc: hi=%"PRIx64", lo=%"PRIx64
2555095955b2SPeter Xu                           " (reserved nonzero)", __func__, inv_desc->hi,
2556095955b2SPeter Xu                           inv_desc->lo);
2557d92fa2dcSLe Tan         return false;
2558d92fa2dcSLe Tan     }
2559d92fa2dcSLe Tan     switch (inv_desc->lo & VTD_INV_DESC_CC_G) {
2560d92fa2dcSLe Tan     case VTD_INV_DESC_CC_DOMAIN:
2561bc535e59SPeter Xu         trace_vtd_inv_desc_cc_domain(
2562d92fa2dcSLe Tan             (uint16_t)VTD_INV_DESC_CC_DID(inv_desc->lo));
2563d92fa2dcSLe Tan         /* Fall through */
2564d92fa2dcSLe Tan     case VTD_INV_DESC_CC_GLOBAL:
2565d92fa2dcSLe Tan         vtd_context_global_invalidate(s);
2566d92fa2dcSLe Tan         break;
2567d92fa2dcSLe Tan 
2568d92fa2dcSLe Tan     case VTD_INV_DESC_CC_DEVICE:
2569bc535e59SPeter Xu         sid = VTD_INV_DESC_CC_SID(inv_desc->lo);
2570bc535e59SPeter Xu         fmask = VTD_INV_DESC_CC_FM(inv_desc->lo);
2571bc535e59SPeter Xu         vtd_context_device_invalidate(s, sid, fmask);
2572d92fa2dcSLe Tan         break;
2573d92fa2dcSLe Tan 
2574d92fa2dcSLe Tan     default:
2575095955b2SPeter Xu         error_report_once("%s: invalid cc inv desc: hi=%"PRIx64", lo=%"PRIx64
2576095955b2SPeter Xu                           " (invalid type)", __func__, inv_desc->hi,
2577095955b2SPeter Xu                           inv_desc->lo);
2578d92fa2dcSLe Tan         return false;
2579d92fa2dcSLe Tan     }
2580d92fa2dcSLe Tan     return true;
2581d92fa2dcSLe Tan }
2582d92fa2dcSLe Tan 
2583b5a280c0SLe Tan static bool vtd_process_iotlb_desc(IntelIOMMUState *s, VTDInvDesc *inv_desc)
2584b5a280c0SLe Tan {
2585b5a280c0SLe Tan     uint16_t domain_id;
2586b5a280c0SLe Tan     uint8_t am;
2587b5a280c0SLe Tan     hwaddr addr;
2588b5a280c0SLe Tan 
2589b5a280c0SLe Tan     if ((inv_desc->lo & VTD_INV_DESC_IOTLB_RSVD_LO) ||
2590b5a280c0SLe Tan         (inv_desc->hi & VTD_INV_DESC_IOTLB_RSVD_HI)) {
2591095955b2SPeter Xu         error_report_once("%s: invalid iotlb inv desc: hi=0x%"PRIx64
2592ff5b5d5bSMarkus Armbruster                           ", lo=0x%"PRIx64" (reserved bits unzero)",
2593095955b2SPeter Xu                           __func__, inv_desc->hi, inv_desc->lo);
2594b5a280c0SLe Tan         return false;
2595b5a280c0SLe Tan     }
2596b5a280c0SLe Tan 
2597b5a280c0SLe Tan     switch (inv_desc->lo & VTD_INV_DESC_IOTLB_G) {
2598b5a280c0SLe Tan     case VTD_INV_DESC_IOTLB_GLOBAL:
2599b5a280c0SLe Tan         vtd_iotlb_global_invalidate(s);
2600b5a280c0SLe Tan         break;
2601b5a280c0SLe Tan 
2602b5a280c0SLe Tan     case VTD_INV_DESC_IOTLB_DOMAIN:
2603b5a280c0SLe Tan         domain_id = VTD_INV_DESC_IOTLB_DID(inv_desc->lo);
2604b5a280c0SLe Tan         vtd_iotlb_domain_invalidate(s, domain_id);
2605b5a280c0SLe Tan         break;
2606b5a280c0SLe Tan 
2607b5a280c0SLe Tan     case VTD_INV_DESC_IOTLB_PAGE:
2608b5a280c0SLe Tan         domain_id = VTD_INV_DESC_IOTLB_DID(inv_desc->lo);
2609b5a280c0SLe Tan         addr = VTD_INV_DESC_IOTLB_ADDR(inv_desc->hi);
2610b5a280c0SLe Tan         am = VTD_INV_DESC_IOTLB_AM(inv_desc->hi);
2611b5a280c0SLe Tan         if (am > VTD_MAMV) {
2612095955b2SPeter Xu             error_report_once("%s: invalid iotlb inv desc: hi=0x%"PRIx64
2613ff5b5d5bSMarkus Armbruster                               ", lo=0x%"PRIx64" (am=%u > VTD_MAMV=%u)",
2614095955b2SPeter Xu                               __func__, inv_desc->hi, inv_desc->lo,
2615095955b2SPeter Xu                               am, (unsigned)VTD_MAMV);
2616b5a280c0SLe Tan             return false;
2617b5a280c0SLe Tan         }
2618b5a280c0SLe Tan         vtd_iotlb_page_invalidate(s, domain_id, addr, am);
2619b5a280c0SLe Tan         break;
2620b5a280c0SLe Tan 
2621b5a280c0SLe Tan     default:
2622095955b2SPeter Xu         error_report_once("%s: invalid iotlb inv desc: hi=0x%"PRIx64
2623ff5b5d5bSMarkus Armbruster                           ", lo=0x%"PRIx64" (type mismatch: 0x%llx)",
2624095955b2SPeter Xu                           __func__, inv_desc->hi, inv_desc->lo,
2625095955b2SPeter Xu                           inv_desc->lo & VTD_INV_DESC_IOTLB_G);
2626b5a280c0SLe Tan         return false;
2627b5a280c0SLe Tan     }
2628b5a280c0SLe Tan     return true;
2629b5a280c0SLe Tan }
2630b5a280c0SLe Tan 
263102a2cbc8SPeter Xu static bool vtd_process_inv_iec_desc(IntelIOMMUState *s,
263202a2cbc8SPeter Xu                                      VTDInvDesc *inv_desc)
263302a2cbc8SPeter Xu {
26347feb51b7SPeter Xu     trace_vtd_inv_desc_iec(inv_desc->iec.granularity,
263502a2cbc8SPeter Xu                            inv_desc->iec.index,
263602a2cbc8SPeter Xu                            inv_desc->iec.index_mask);
263702a2cbc8SPeter Xu 
263802a2cbc8SPeter Xu     vtd_iec_notify_all(s, !inv_desc->iec.granularity,
263902a2cbc8SPeter Xu                        inv_desc->iec.index,
264002a2cbc8SPeter Xu                        inv_desc->iec.index_mask);
2641554f5e16SJason Wang     return true;
2642554f5e16SJason Wang }
264302a2cbc8SPeter Xu 
2644554f5e16SJason Wang static bool vtd_process_device_iotlb_desc(IntelIOMMUState *s,
2645554f5e16SJason Wang                                           VTDInvDesc *inv_desc)
2646554f5e16SJason Wang {
2647554f5e16SJason Wang     VTDAddressSpace *vtd_dev_as;
26485039caf3SEugenio Pérez     IOMMUTLBEvent event;
2649554f5e16SJason Wang     hwaddr addr;
2650554f5e16SJason Wang     uint64_t sz;
2651554f5e16SJason Wang     uint16_t sid;
2652554f5e16SJason Wang     bool size;
2653554f5e16SJason Wang 
2654554f5e16SJason Wang     addr = VTD_INV_DESC_DEVICE_IOTLB_ADDR(inv_desc->hi);
2655554f5e16SJason Wang     sid = VTD_INV_DESC_DEVICE_IOTLB_SID(inv_desc->lo);
2656554f5e16SJason Wang     size = VTD_INV_DESC_DEVICE_IOTLB_SIZE(inv_desc->hi);
2657554f5e16SJason Wang 
2658554f5e16SJason Wang     if ((inv_desc->lo & VTD_INV_DESC_DEVICE_IOTLB_RSVD_LO) ||
2659554f5e16SJason Wang         (inv_desc->hi & VTD_INV_DESC_DEVICE_IOTLB_RSVD_HI)) {
2660095955b2SPeter Xu         error_report_once("%s: invalid dev-iotlb inv desc: hi=%"PRIx64
2661095955b2SPeter Xu                           ", lo=%"PRIx64" (reserved nonzero)", __func__,
2662095955b2SPeter Xu                           inv_desc->hi, inv_desc->lo);
2663554f5e16SJason Wang         return false;
2664554f5e16SJason Wang     }
2665554f5e16SJason Wang 
2666da8d439cSJason Wang     /*
2667da8d439cSJason Wang      * Using sid is OK since the guest should have finished the
2668da8d439cSJason Wang      * initialization of both the bus and device.
2669da8d439cSJason Wang      */
2670da8d439cSJason Wang     vtd_dev_as = vtd_get_as_by_sid(s, sid);
2671554f5e16SJason Wang     if (!vtd_dev_as) {
2672554f5e16SJason Wang         goto done;
2673554f5e16SJason Wang     }
2674554f5e16SJason Wang 
267504eb6247SJason Wang     /* According to ATS spec table 2.4:
267604eb6247SJason Wang      * S = 0, bits 15:12 = xxxx     range size: 4K
267704eb6247SJason Wang      * S = 1, bits 15:12 = xxx0     range size: 8K
267804eb6247SJason Wang      * S = 1, bits 15:12 = xx01     range size: 16K
267904eb6247SJason Wang      * S = 1, bits 15:12 = x011     range size: 32K
268004eb6247SJason Wang      * S = 1, bits 15:12 = 0111     range size: 64K
268104eb6247SJason Wang      * ...
268204eb6247SJason Wang      */
2683554f5e16SJason Wang     if (size) {
268404eb6247SJason Wang         sz = (VTD_PAGE_SIZE * 2) << cto64(addr >> VTD_PAGE_SHIFT);
2685554f5e16SJason Wang         addr &= ~(sz - 1);
2686554f5e16SJason Wang     } else {
2687554f5e16SJason Wang         sz = VTD_PAGE_SIZE;
2688554f5e16SJason Wang     }
2689554f5e16SJason Wang 
2690b68ba1caSEugenio Pérez     event.type = IOMMU_NOTIFIER_DEVIOTLB_UNMAP;
26915039caf3SEugenio Pérez     event.entry.target_as = &vtd_dev_as->as;
26925039caf3SEugenio Pérez     event.entry.addr_mask = sz - 1;
26935039caf3SEugenio Pérez     event.entry.iova = addr;
26945039caf3SEugenio Pérez     event.entry.perm = IOMMU_NONE;
26955039caf3SEugenio Pérez     event.entry.translated_addr = 0;
26965039caf3SEugenio Pérez     memory_region_notify_iommu(&vtd_dev_as->iommu, 0, event);
2697554f5e16SJason Wang 
2698554f5e16SJason Wang done:
269902a2cbc8SPeter Xu     return true;
270002a2cbc8SPeter Xu }
270102a2cbc8SPeter Xu 
2702ed7b8fbcSLe Tan static bool vtd_process_inv_desc(IntelIOMMUState *s)
2703ed7b8fbcSLe Tan {
2704ed7b8fbcSLe Tan     VTDInvDesc inv_desc;
2705ed7b8fbcSLe Tan     uint8_t desc_type;
2706ed7b8fbcSLe Tan 
27077feb51b7SPeter Xu     trace_vtd_inv_qi_head(s->iq_head);
2708c0c1d351SLiu, Yi L     if (!vtd_get_inv_desc(s, &inv_desc)) {
2709ed7b8fbcSLe Tan         s->iq_last_desc_type = VTD_INV_DESC_NONE;
2710ed7b8fbcSLe Tan         return false;
2711ed7b8fbcSLe Tan     }
2712c0c1d351SLiu, Yi L 
2713ed7b8fbcSLe Tan     desc_type = inv_desc.lo & VTD_INV_DESC_TYPE;
2714ed7b8fbcSLe Tan     /* FIXME: should update at first or at last? */
2715ed7b8fbcSLe Tan     s->iq_last_desc_type = desc_type;
2716ed7b8fbcSLe Tan 
2717ed7b8fbcSLe Tan     switch (desc_type) {
2718ed7b8fbcSLe Tan     case VTD_INV_DESC_CC:
2719bc535e59SPeter Xu         trace_vtd_inv_desc("context-cache", inv_desc.hi, inv_desc.lo);
2720d92fa2dcSLe Tan         if (!vtd_process_context_cache_desc(s, &inv_desc)) {
2721d92fa2dcSLe Tan             return false;
2722d92fa2dcSLe Tan         }
2723ed7b8fbcSLe Tan         break;
2724ed7b8fbcSLe Tan 
2725ed7b8fbcSLe Tan     case VTD_INV_DESC_IOTLB:
2726bc535e59SPeter Xu         trace_vtd_inv_desc("iotlb", inv_desc.hi, inv_desc.lo);
2727b5a280c0SLe Tan         if (!vtd_process_iotlb_desc(s, &inv_desc)) {
2728b5a280c0SLe Tan             return false;
2729b5a280c0SLe Tan         }
2730ed7b8fbcSLe Tan         break;
2731ed7b8fbcSLe Tan 
27324a4f219eSYi Sun     /*
27334a4f219eSYi Sun      * TODO: the entity of below two cases will be implemented in future series.
27344a4f219eSYi Sun      * To make guest (which integrates scalable mode support patch set in
27354a4f219eSYi Sun      * iommu driver) work, just return true is enough so far.
27364a4f219eSYi Sun      */
27374a4f219eSYi Sun     case VTD_INV_DESC_PC:
27384a4f219eSYi Sun         break;
27394a4f219eSYi Sun 
27404a4f219eSYi Sun     case VTD_INV_DESC_PIOTLB:
27414a4f219eSYi Sun         break;
27424a4f219eSYi Sun 
2743ed7b8fbcSLe Tan     case VTD_INV_DESC_WAIT:
2744bc535e59SPeter Xu         trace_vtd_inv_desc("wait", inv_desc.hi, inv_desc.lo);
2745ed7b8fbcSLe Tan         if (!vtd_process_wait_desc(s, &inv_desc)) {
2746ed7b8fbcSLe Tan             return false;
2747ed7b8fbcSLe Tan         }
2748ed7b8fbcSLe Tan         break;
2749ed7b8fbcSLe Tan 
2750b7910472SPeter Xu     case VTD_INV_DESC_IEC:
2751bc535e59SPeter Xu         trace_vtd_inv_desc("iec", inv_desc.hi, inv_desc.lo);
275202a2cbc8SPeter Xu         if (!vtd_process_inv_iec_desc(s, &inv_desc)) {
275302a2cbc8SPeter Xu             return false;
275402a2cbc8SPeter Xu         }
2755b7910472SPeter Xu         break;
2756b7910472SPeter Xu 
2757554f5e16SJason Wang     case VTD_INV_DESC_DEVICE:
27587feb51b7SPeter Xu         trace_vtd_inv_desc("device", inv_desc.hi, inv_desc.lo);
2759554f5e16SJason Wang         if (!vtd_process_device_iotlb_desc(s, &inv_desc)) {
2760554f5e16SJason Wang             return false;
2761554f5e16SJason Wang         }
2762554f5e16SJason Wang         break;
2763554f5e16SJason Wang 
2764ed7b8fbcSLe Tan     default:
2765095955b2SPeter Xu         error_report_once("%s: invalid inv desc: hi=%"PRIx64", lo=%"PRIx64
2766095955b2SPeter Xu                           " (unknown type)", __func__, inv_desc.hi,
2767095955b2SPeter Xu                           inv_desc.lo);
2768ed7b8fbcSLe Tan         return false;
2769ed7b8fbcSLe Tan     }
2770ed7b8fbcSLe Tan     s->iq_head++;
2771ed7b8fbcSLe Tan     if (s->iq_head == s->iq_size) {
2772ed7b8fbcSLe Tan         s->iq_head = 0;
2773ed7b8fbcSLe Tan     }
2774ed7b8fbcSLe Tan     return true;
2775ed7b8fbcSLe Tan }
2776ed7b8fbcSLe Tan 
2777ed7b8fbcSLe Tan /* Try to fetch and process more Invalidation Descriptors */
2778ed7b8fbcSLe Tan static void vtd_fetch_inv_desc(IntelIOMMUState *s)
2779ed7b8fbcSLe Tan {
2780a4544c45SLiu Yi L     int qi_shift;
2781a4544c45SLiu Yi L 
2782a4544c45SLiu Yi L     /* Refer to 10.4.23 of VT-d spec 3.0 */
2783a4544c45SLiu Yi L     qi_shift = s->iq_dw ? VTD_IQH_QH_SHIFT_5 : VTD_IQH_QH_SHIFT_4;
2784a4544c45SLiu Yi L 
27857feb51b7SPeter Xu     trace_vtd_inv_qi_fetch();
27867feb51b7SPeter Xu 
2787ed7b8fbcSLe Tan     if (s->iq_tail >= s->iq_size) {
2788ed7b8fbcSLe Tan         /* Detects an invalid Tail pointer */
27894e4abd11SPeter Xu         error_report_once("%s: detected invalid QI tail "
27904e4abd11SPeter Xu                           "(tail=0x%x, size=0x%x)",
27914e4abd11SPeter Xu                           __func__, s->iq_tail, s->iq_size);
2792ed7b8fbcSLe Tan         vtd_handle_inv_queue_error(s);
2793ed7b8fbcSLe Tan         return;
2794ed7b8fbcSLe Tan     }
2795ed7b8fbcSLe Tan     while (s->iq_head != s->iq_tail) {
2796ed7b8fbcSLe Tan         if (!vtd_process_inv_desc(s)) {
2797ed7b8fbcSLe Tan             /* Invalidation Queue Errors */
2798ed7b8fbcSLe Tan             vtd_handle_inv_queue_error(s);
2799ed7b8fbcSLe Tan             break;
2800ed7b8fbcSLe Tan         }
2801ed7b8fbcSLe Tan         /* Must update the IQH_REG in time */
2802ed7b8fbcSLe Tan         vtd_set_quad_raw(s, DMAR_IQH_REG,
2803a4544c45SLiu Yi L                          (((uint64_t)(s->iq_head)) << qi_shift) &
2804ed7b8fbcSLe Tan                          VTD_IQH_QH_MASK);
2805ed7b8fbcSLe Tan     }
2806ed7b8fbcSLe Tan }
2807ed7b8fbcSLe Tan 
2808ed7b8fbcSLe Tan /* Handle write to Invalidation Queue Tail Register */
2809ed7b8fbcSLe Tan static void vtd_handle_iqt_write(IntelIOMMUState *s)
2810ed7b8fbcSLe Tan {
2811ed7b8fbcSLe Tan     uint64_t val = vtd_get_quad_raw(s, DMAR_IQT_REG);
2812ed7b8fbcSLe Tan 
2813c0c1d351SLiu, Yi L     if (s->iq_dw && (val & VTD_IQT_QT_256_RSV_BIT)) {
2814c0c1d351SLiu, Yi L         error_report_once("%s: RSV bit is set: val=0x%"PRIx64,
2815c0c1d351SLiu, Yi L                           __func__, val);
2816c0c1d351SLiu, Yi L         return;
2817c0c1d351SLiu, Yi L     }
2818c0c1d351SLiu, Yi L     s->iq_tail = VTD_IQT_QT(s->iq_dw, val);
28197feb51b7SPeter Xu     trace_vtd_inv_qi_tail(s->iq_tail);
28207feb51b7SPeter Xu 
2821ed7b8fbcSLe Tan     if (s->qi_enabled && !(vtd_get_long_raw(s, DMAR_FSTS_REG) & VTD_FSTS_IQE)) {
2822ed7b8fbcSLe Tan         /* Process Invalidation Queue here */
2823ed7b8fbcSLe Tan         vtd_fetch_inv_desc(s);
2824ed7b8fbcSLe Tan     }
2825ed7b8fbcSLe Tan }
2826ed7b8fbcSLe Tan 
28271da12ec4SLe Tan static void vtd_handle_fsts_write(IntelIOMMUState *s)
28281da12ec4SLe Tan {
28291da12ec4SLe Tan     uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
28301da12ec4SLe Tan     uint32_t fectl_reg = vtd_get_long_raw(s, DMAR_FECTL_REG);
28311da12ec4SLe Tan     uint32_t status_fields = VTD_FSTS_PFO | VTD_FSTS_PPF | VTD_FSTS_IQE;
28321da12ec4SLe Tan 
28331da12ec4SLe Tan     if ((fectl_reg & VTD_FECTL_IP) && !(fsts_reg & status_fields)) {
28341da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
28357feb51b7SPeter Xu         trace_vtd_fsts_clear_ip();
28361da12ec4SLe Tan     }
2837ed7b8fbcSLe Tan     /* FIXME: when IQE is Clear, should we try to fetch some Invalidation
2838ed7b8fbcSLe Tan      * Descriptors if there are any when Queued Invalidation is enabled?
2839ed7b8fbcSLe Tan      */
28401da12ec4SLe Tan }
28411da12ec4SLe Tan 
28421da12ec4SLe Tan static void vtd_handle_fectl_write(IntelIOMMUState *s)
28431da12ec4SLe Tan {
28441da12ec4SLe Tan     uint32_t fectl_reg;
28451da12ec4SLe Tan     /* FIXME: when software clears the IM field, check the IP field. But do we
28461da12ec4SLe Tan      * need to compare the old value and the new value to conclude that
28471da12ec4SLe Tan      * software clears the IM field? Or just check if the IM field is zero?
28481da12ec4SLe Tan      */
28491da12ec4SLe Tan     fectl_reg = vtd_get_long_raw(s, DMAR_FECTL_REG);
28507feb51b7SPeter Xu 
28517feb51b7SPeter Xu     trace_vtd_reg_write_fectl(fectl_reg);
28527feb51b7SPeter Xu 
28531da12ec4SLe Tan     if ((fectl_reg & VTD_FECTL_IP) && !(fectl_reg & VTD_FECTL_IM)) {
28541da12ec4SLe Tan         vtd_generate_interrupt(s, DMAR_FEADDR_REG, DMAR_FEDATA_REG);
28551da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
28561da12ec4SLe Tan     }
28571da12ec4SLe Tan }
28581da12ec4SLe Tan 
2859ed7b8fbcSLe Tan static void vtd_handle_ics_write(IntelIOMMUState *s)
2860ed7b8fbcSLe Tan {
2861ed7b8fbcSLe Tan     uint32_t ics_reg = vtd_get_long_raw(s, DMAR_ICS_REG);
2862ed7b8fbcSLe Tan     uint32_t iectl_reg = vtd_get_long_raw(s, DMAR_IECTL_REG);
2863ed7b8fbcSLe Tan 
2864ed7b8fbcSLe Tan     if ((iectl_reg & VTD_IECTL_IP) && !(ics_reg & VTD_ICS_IWC)) {
28657feb51b7SPeter Xu         trace_vtd_reg_ics_clear_ip();
2866ed7b8fbcSLe Tan         vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
2867ed7b8fbcSLe Tan     }
2868ed7b8fbcSLe Tan }
2869ed7b8fbcSLe Tan 
2870ed7b8fbcSLe Tan static void vtd_handle_iectl_write(IntelIOMMUState *s)
2871ed7b8fbcSLe Tan {
2872ed7b8fbcSLe Tan     uint32_t iectl_reg;
2873ed7b8fbcSLe Tan     /* FIXME: when software clears the IM field, check the IP field. But do we
2874ed7b8fbcSLe Tan      * need to compare the old value and the new value to conclude that
2875ed7b8fbcSLe Tan      * software clears the IM field? Or just check if the IM field is zero?
2876ed7b8fbcSLe Tan      */
2877ed7b8fbcSLe Tan     iectl_reg = vtd_get_long_raw(s, DMAR_IECTL_REG);
28787feb51b7SPeter Xu 
28797feb51b7SPeter Xu     trace_vtd_reg_write_iectl(iectl_reg);
28807feb51b7SPeter Xu 
2881ed7b8fbcSLe Tan     if ((iectl_reg & VTD_IECTL_IP) && !(iectl_reg & VTD_IECTL_IM)) {
2882ed7b8fbcSLe Tan         vtd_generate_interrupt(s, DMAR_IEADDR_REG, DMAR_IEDATA_REG);
2883ed7b8fbcSLe Tan         vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
2884ed7b8fbcSLe Tan     }
2885ed7b8fbcSLe Tan }
2886ed7b8fbcSLe Tan 
28871da12ec4SLe Tan static uint64_t vtd_mem_read(void *opaque, hwaddr addr, unsigned size)
28881da12ec4SLe Tan {
28891da12ec4SLe Tan     IntelIOMMUState *s = opaque;
28901da12ec4SLe Tan     uint64_t val;
28911da12ec4SLe Tan 
28927feb51b7SPeter Xu     trace_vtd_reg_read(addr, size);
28937feb51b7SPeter Xu 
28941da12ec4SLe Tan     if (addr + size > DMAR_REG_SIZE) {
28951376211fSPeter Xu         error_report_once("%s: MMIO over range: addr=0x%" PRIx64
289673beb01eSPeter Xu                           " size=0x%x", __func__, addr, size);
28971da12ec4SLe Tan         return (uint64_t)-1;
28981da12ec4SLe Tan     }
28991da12ec4SLe Tan 
29001da12ec4SLe Tan     switch (addr) {
29011da12ec4SLe Tan     /* Root Table Address Register, 64-bit */
29021da12ec4SLe Tan     case DMAR_RTADDR_REG:
29038fdee711SYi Sun         val = vtd_get_quad_raw(s, DMAR_RTADDR_REG);
29041da12ec4SLe Tan         if (size == 4) {
29058fdee711SYi Sun             val = val & ((1ULL << 32) - 1);
29061da12ec4SLe Tan         }
29071da12ec4SLe Tan         break;
29081da12ec4SLe Tan 
29091da12ec4SLe Tan     case DMAR_RTADDR_REG_HI:
29101da12ec4SLe Tan         assert(size == 4);
29118fdee711SYi Sun         val = vtd_get_quad_raw(s, DMAR_RTADDR_REG) >> 32;
29121da12ec4SLe Tan         break;
29131da12ec4SLe Tan 
2914ed7b8fbcSLe Tan     /* Invalidation Queue Address Register, 64-bit */
2915ed7b8fbcSLe Tan     case DMAR_IQA_REG:
2916ed7b8fbcSLe Tan         val = s->iq | (vtd_get_quad(s, DMAR_IQA_REG) & VTD_IQA_QS);
2917ed7b8fbcSLe Tan         if (size == 4) {
2918ed7b8fbcSLe Tan             val = val & ((1ULL << 32) - 1);
2919ed7b8fbcSLe Tan         }
2920ed7b8fbcSLe Tan         break;
2921ed7b8fbcSLe Tan 
2922ed7b8fbcSLe Tan     case DMAR_IQA_REG_HI:
2923ed7b8fbcSLe Tan         assert(size == 4);
2924ed7b8fbcSLe Tan         val = s->iq >> 32;
2925ed7b8fbcSLe Tan         break;
2926ed7b8fbcSLe Tan 
29271da12ec4SLe Tan     default:
29281da12ec4SLe Tan         if (size == 4) {
29291da12ec4SLe Tan             val = vtd_get_long(s, addr);
29301da12ec4SLe Tan         } else {
29311da12ec4SLe Tan             val = vtd_get_quad(s, addr);
29321da12ec4SLe Tan         }
29331da12ec4SLe Tan     }
29347feb51b7SPeter Xu 
29351da12ec4SLe Tan     return val;
29361da12ec4SLe Tan }
29371da12ec4SLe Tan 
29381da12ec4SLe Tan static void vtd_mem_write(void *opaque, hwaddr addr,
29391da12ec4SLe Tan                           uint64_t val, unsigned size)
29401da12ec4SLe Tan {
29411da12ec4SLe Tan     IntelIOMMUState *s = opaque;
29421da12ec4SLe Tan 
29437feb51b7SPeter Xu     trace_vtd_reg_write(addr, size, val);
29447feb51b7SPeter Xu 
29451da12ec4SLe Tan     if (addr + size > DMAR_REG_SIZE) {
29461376211fSPeter Xu         error_report_once("%s: MMIO over range: addr=0x%" PRIx64
294773beb01eSPeter Xu                           " size=0x%x", __func__, addr, size);
29481da12ec4SLe Tan         return;
29491da12ec4SLe Tan     }
29501da12ec4SLe Tan 
29511da12ec4SLe Tan     switch (addr) {
29521da12ec4SLe Tan     /* Global Command Register, 32-bit */
29531da12ec4SLe Tan     case DMAR_GCMD_REG:
29541da12ec4SLe Tan         vtd_set_long(s, addr, val);
29551da12ec4SLe Tan         vtd_handle_gcmd_write(s);
29561da12ec4SLe Tan         break;
29571da12ec4SLe Tan 
29581da12ec4SLe Tan     /* Context Command Register, 64-bit */
29591da12ec4SLe Tan     case DMAR_CCMD_REG:
29601da12ec4SLe Tan         if (size == 4) {
29611da12ec4SLe Tan             vtd_set_long(s, addr, val);
29621da12ec4SLe Tan         } else {
29631da12ec4SLe Tan             vtd_set_quad(s, addr, val);
29641da12ec4SLe Tan             vtd_handle_ccmd_write(s);
29651da12ec4SLe Tan         }
29661da12ec4SLe Tan         break;
29671da12ec4SLe Tan 
29681da12ec4SLe Tan     case DMAR_CCMD_REG_HI:
29691da12ec4SLe Tan         assert(size == 4);
29701da12ec4SLe Tan         vtd_set_long(s, addr, val);
29711da12ec4SLe Tan         vtd_handle_ccmd_write(s);
29721da12ec4SLe Tan         break;
29731da12ec4SLe Tan 
29741da12ec4SLe Tan     /* IOTLB Invalidation Register, 64-bit */
29751da12ec4SLe Tan     case DMAR_IOTLB_REG:
29761da12ec4SLe Tan         if (size == 4) {
29771da12ec4SLe Tan             vtd_set_long(s, addr, val);
29781da12ec4SLe Tan         } else {
29791da12ec4SLe Tan             vtd_set_quad(s, addr, val);
29801da12ec4SLe Tan             vtd_handle_iotlb_write(s);
29811da12ec4SLe Tan         }
29821da12ec4SLe Tan         break;
29831da12ec4SLe Tan 
29841da12ec4SLe Tan     case DMAR_IOTLB_REG_HI:
29851da12ec4SLe Tan         assert(size == 4);
29861da12ec4SLe Tan         vtd_set_long(s, addr, val);
29871da12ec4SLe Tan         vtd_handle_iotlb_write(s);
29881da12ec4SLe Tan         break;
29891da12ec4SLe Tan 
2990b5a280c0SLe Tan     /* Invalidate Address Register, 64-bit */
2991b5a280c0SLe Tan     case DMAR_IVA_REG:
2992b5a280c0SLe Tan         if (size == 4) {
2993b5a280c0SLe Tan             vtd_set_long(s, addr, val);
2994b5a280c0SLe Tan         } else {
2995b5a280c0SLe Tan             vtd_set_quad(s, addr, val);
2996b5a280c0SLe Tan         }
2997b5a280c0SLe Tan         break;
2998b5a280c0SLe Tan 
2999b5a280c0SLe Tan     case DMAR_IVA_REG_HI:
3000b5a280c0SLe Tan         assert(size == 4);
3001b5a280c0SLe Tan         vtd_set_long(s, addr, val);
3002b5a280c0SLe Tan         break;
3003b5a280c0SLe Tan 
30041da12ec4SLe Tan     /* Fault Status Register, 32-bit */
30051da12ec4SLe Tan     case DMAR_FSTS_REG:
30061da12ec4SLe Tan         assert(size == 4);
30071da12ec4SLe Tan         vtd_set_long(s, addr, val);
30081da12ec4SLe Tan         vtd_handle_fsts_write(s);
30091da12ec4SLe Tan         break;
30101da12ec4SLe Tan 
30111da12ec4SLe Tan     /* Fault Event Control Register, 32-bit */
30121da12ec4SLe Tan     case DMAR_FECTL_REG:
30131da12ec4SLe Tan         assert(size == 4);
30141da12ec4SLe Tan         vtd_set_long(s, addr, val);
30151da12ec4SLe Tan         vtd_handle_fectl_write(s);
30161da12ec4SLe Tan         break;
30171da12ec4SLe Tan 
30181da12ec4SLe Tan     /* Fault Event Data Register, 32-bit */
30191da12ec4SLe Tan     case DMAR_FEDATA_REG:
30201da12ec4SLe Tan         assert(size == 4);
30211da12ec4SLe Tan         vtd_set_long(s, addr, val);
30221da12ec4SLe Tan         break;
30231da12ec4SLe Tan 
30241da12ec4SLe Tan     /* Fault Event Address Register, 32-bit */
30251da12ec4SLe Tan     case DMAR_FEADDR_REG:
3026b7a7bb35SJan Kiszka         if (size == 4) {
30271da12ec4SLe Tan             vtd_set_long(s, addr, val);
3028b7a7bb35SJan Kiszka         } else {
3029b7a7bb35SJan Kiszka             /*
3030b7a7bb35SJan Kiszka              * While the register is 32-bit only, some guests (Xen...) write to
3031b7a7bb35SJan Kiszka              * it with 64-bit.
3032b7a7bb35SJan Kiszka              */
3033b7a7bb35SJan Kiszka             vtd_set_quad(s, addr, val);
3034b7a7bb35SJan Kiszka         }
30351da12ec4SLe Tan         break;
30361da12ec4SLe Tan 
30371da12ec4SLe Tan     /* Fault Event Upper Address Register, 32-bit */
30381da12ec4SLe Tan     case DMAR_FEUADDR_REG:
30391da12ec4SLe Tan         assert(size == 4);
30401da12ec4SLe Tan         vtd_set_long(s, addr, val);
30411da12ec4SLe Tan         break;
30421da12ec4SLe Tan 
30431da12ec4SLe Tan     /* Protected Memory Enable Register, 32-bit */
30441da12ec4SLe Tan     case DMAR_PMEN_REG:
30451da12ec4SLe Tan         assert(size == 4);
30461da12ec4SLe Tan         vtd_set_long(s, addr, val);
30471da12ec4SLe Tan         break;
30481da12ec4SLe Tan 
30491da12ec4SLe Tan     /* Root Table Address Register, 64-bit */
30501da12ec4SLe Tan     case DMAR_RTADDR_REG:
30511da12ec4SLe Tan         if (size == 4) {
30521da12ec4SLe Tan             vtd_set_long(s, addr, val);
30531da12ec4SLe Tan         } else {
30541da12ec4SLe Tan             vtd_set_quad(s, addr, val);
30551da12ec4SLe Tan         }
30561da12ec4SLe Tan         break;
30571da12ec4SLe Tan 
30581da12ec4SLe Tan     case DMAR_RTADDR_REG_HI:
30591da12ec4SLe Tan         assert(size == 4);
30601da12ec4SLe Tan         vtd_set_long(s, addr, val);
30611da12ec4SLe Tan         break;
30621da12ec4SLe Tan 
3063ed7b8fbcSLe Tan     /* Invalidation Queue Tail Register, 64-bit */
3064ed7b8fbcSLe Tan     case DMAR_IQT_REG:
3065ed7b8fbcSLe Tan         if (size == 4) {
3066ed7b8fbcSLe Tan             vtd_set_long(s, addr, val);
3067ed7b8fbcSLe Tan         } else {
3068ed7b8fbcSLe Tan             vtd_set_quad(s, addr, val);
3069ed7b8fbcSLe Tan         }
3070ed7b8fbcSLe Tan         vtd_handle_iqt_write(s);
3071ed7b8fbcSLe Tan         break;
3072ed7b8fbcSLe Tan 
3073ed7b8fbcSLe Tan     case DMAR_IQT_REG_HI:
3074ed7b8fbcSLe Tan         assert(size == 4);
3075ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3076ed7b8fbcSLe Tan         /* 19:63 of IQT_REG is RsvdZ, do nothing here */
3077ed7b8fbcSLe Tan         break;
3078ed7b8fbcSLe Tan 
3079ed7b8fbcSLe Tan     /* Invalidation Queue Address Register, 64-bit */
3080ed7b8fbcSLe Tan     case DMAR_IQA_REG:
3081ed7b8fbcSLe Tan         if (size == 4) {
3082ed7b8fbcSLe Tan             vtd_set_long(s, addr, val);
3083ed7b8fbcSLe Tan         } else {
3084ed7b8fbcSLe Tan             vtd_set_quad(s, addr, val);
3085ed7b8fbcSLe Tan         }
3086147a372eSJason Wang         vtd_update_iq_dw(s);
3087ed7b8fbcSLe Tan         break;
3088ed7b8fbcSLe Tan 
3089ed7b8fbcSLe Tan     case DMAR_IQA_REG_HI:
3090ed7b8fbcSLe Tan         assert(size == 4);
3091ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3092ed7b8fbcSLe Tan         break;
3093ed7b8fbcSLe Tan 
3094ed7b8fbcSLe Tan     /* Invalidation Completion Status Register, 32-bit */
3095ed7b8fbcSLe Tan     case DMAR_ICS_REG:
3096ed7b8fbcSLe Tan         assert(size == 4);
3097ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3098ed7b8fbcSLe Tan         vtd_handle_ics_write(s);
3099ed7b8fbcSLe Tan         break;
3100ed7b8fbcSLe Tan 
3101ed7b8fbcSLe Tan     /* Invalidation Event Control Register, 32-bit */
3102ed7b8fbcSLe Tan     case DMAR_IECTL_REG:
3103ed7b8fbcSLe Tan         assert(size == 4);
3104ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3105ed7b8fbcSLe Tan         vtd_handle_iectl_write(s);
3106ed7b8fbcSLe Tan         break;
3107ed7b8fbcSLe Tan 
3108ed7b8fbcSLe Tan     /* Invalidation Event Data Register, 32-bit */
3109ed7b8fbcSLe Tan     case DMAR_IEDATA_REG:
3110ed7b8fbcSLe Tan         assert(size == 4);
3111ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3112ed7b8fbcSLe Tan         break;
3113ed7b8fbcSLe Tan 
3114ed7b8fbcSLe Tan     /* Invalidation Event Address Register, 32-bit */
3115ed7b8fbcSLe Tan     case DMAR_IEADDR_REG:
3116ed7b8fbcSLe Tan         assert(size == 4);
3117ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3118ed7b8fbcSLe Tan         break;
3119ed7b8fbcSLe Tan 
3120ed7b8fbcSLe Tan     /* Invalidation Event Upper Address Register, 32-bit */
3121ed7b8fbcSLe Tan     case DMAR_IEUADDR_REG:
3122ed7b8fbcSLe Tan         assert(size == 4);
3123ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3124ed7b8fbcSLe Tan         break;
3125ed7b8fbcSLe Tan 
31261da12ec4SLe Tan     /* Fault Recording Registers, 128-bit */
31271da12ec4SLe Tan     case DMAR_FRCD_REG_0_0:
31281da12ec4SLe Tan         if (size == 4) {
31291da12ec4SLe Tan             vtd_set_long(s, addr, val);
31301da12ec4SLe Tan         } else {
31311da12ec4SLe Tan             vtd_set_quad(s, addr, val);
31321da12ec4SLe Tan         }
31331da12ec4SLe Tan         break;
31341da12ec4SLe Tan 
31351da12ec4SLe Tan     case DMAR_FRCD_REG_0_1:
31361da12ec4SLe Tan         assert(size == 4);
31371da12ec4SLe Tan         vtd_set_long(s, addr, val);
31381da12ec4SLe Tan         break;
31391da12ec4SLe Tan 
31401da12ec4SLe Tan     case DMAR_FRCD_REG_0_2:
31411da12ec4SLe Tan         if (size == 4) {
31421da12ec4SLe Tan             vtd_set_long(s, addr, val);
31431da12ec4SLe Tan         } else {
31441da12ec4SLe Tan             vtd_set_quad(s, addr, val);
31451da12ec4SLe Tan             /* May clear bit 127 (Fault), update PPF */
31461da12ec4SLe Tan             vtd_update_fsts_ppf(s);
31471da12ec4SLe Tan         }
31481da12ec4SLe Tan         break;
31491da12ec4SLe Tan 
31501da12ec4SLe Tan     case DMAR_FRCD_REG_0_3:
31511da12ec4SLe Tan         assert(size == 4);
31521da12ec4SLe Tan         vtd_set_long(s, addr, val);
31531da12ec4SLe Tan         /* May clear bit 127 (Fault), update PPF */
31541da12ec4SLe Tan         vtd_update_fsts_ppf(s);
31551da12ec4SLe Tan         break;
31561da12ec4SLe Tan 
3157a5861439SPeter Xu     case DMAR_IRTA_REG:
3158a5861439SPeter Xu         if (size == 4) {
3159a5861439SPeter Xu             vtd_set_long(s, addr, val);
3160a5861439SPeter Xu         } else {
3161a5861439SPeter Xu             vtd_set_quad(s, addr, val);
3162a5861439SPeter Xu         }
3163a5861439SPeter Xu         break;
3164a5861439SPeter Xu 
3165a5861439SPeter Xu     case DMAR_IRTA_REG_HI:
3166a5861439SPeter Xu         assert(size == 4);
3167a5861439SPeter Xu         vtd_set_long(s, addr, val);
3168a5861439SPeter Xu         break;
3169a5861439SPeter Xu 
31701da12ec4SLe Tan     default:
31711da12ec4SLe Tan         if (size == 4) {
31721da12ec4SLe Tan             vtd_set_long(s, addr, val);
31731da12ec4SLe Tan         } else {
31741da12ec4SLe Tan             vtd_set_quad(s, addr, val);
31751da12ec4SLe Tan         }
31761da12ec4SLe Tan     }
31771da12ec4SLe Tan }
31781da12ec4SLe Tan 
31793df9d748SAlexey Kardashevskiy static IOMMUTLBEntry vtd_iommu_translate(IOMMUMemoryRegion *iommu, hwaddr addr,
31802c91bcf2SPeter Maydell                                          IOMMUAccessFlags flag, int iommu_idx)
31811da12ec4SLe Tan {
31821da12ec4SLe Tan     VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu);
31831da12ec4SLe Tan     IntelIOMMUState *s = vtd_as->iommu_state;
3184b9313021SPeter Xu     IOMMUTLBEntry iotlb = {
3185b9313021SPeter Xu         /* We'll fill in the rest later. */
31861da12ec4SLe Tan         .target_as = &address_space_memory,
31871da12ec4SLe Tan     };
3188b9313021SPeter Xu     bool success;
31891da12ec4SLe Tan 
3190b9313021SPeter Xu     if (likely(s->dmar_enabled)) {
3191b9313021SPeter Xu         success = vtd_do_iommu_translate(vtd_as, vtd_as->bus, vtd_as->devfn,
3192b9313021SPeter Xu                                          addr, flag & IOMMU_WO, &iotlb);
3193b9313021SPeter Xu     } else {
31941da12ec4SLe Tan         /* DMAR disabled, passthrough, use 4k-page*/
3195b9313021SPeter Xu         iotlb.iova = addr & VTD_PAGE_MASK_4K;
3196b9313021SPeter Xu         iotlb.translated_addr = addr & VTD_PAGE_MASK_4K;
3197b9313021SPeter Xu         iotlb.addr_mask = ~VTD_PAGE_MASK_4K;
3198b9313021SPeter Xu         iotlb.perm = IOMMU_RW;
3199b9313021SPeter Xu         success = true;
32001da12ec4SLe Tan     }
32011da12ec4SLe Tan 
3202b9313021SPeter Xu     if (likely(success)) {
32037feb51b7SPeter Xu         trace_vtd_dmar_translate(pci_bus_num(vtd_as->bus),
32047feb51b7SPeter Xu                                  VTD_PCI_SLOT(vtd_as->devfn),
32057feb51b7SPeter Xu                                  VTD_PCI_FUNC(vtd_as->devfn),
3206b9313021SPeter Xu                                  iotlb.iova, iotlb.translated_addr,
3207b9313021SPeter Xu                                  iotlb.addr_mask);
3208b9313021SPeter Xu     } else {
32094e4abd11SPeter Xu         error_report_once("%s: detected translation failure "
32104e4abd11SPeter Xu                           "(dev=%02x:%02x:%02x, iova=0x%" PRIx64 ")",
32114e4abd11SPeter Xu                           __func__, pci_bus_num(vtd_as->bus),
3212b9313021SPeter Xu                           VTD_PCI_SLOT(vtd_as->devfn),
3213b9313021SPeter Xu                           VTD_PCI_FUNC(vtd_as->devfn),
3214662b4b69SPeter Xu                           addr);
3215b9313021SPeter Xu     }
32167feb51b7SPeter Xu 
3217b9313021SPeter Xu     return iotlb;
32181da12ec4SLe Tan }
32191da12ec4SLe Tan 
3220549d4005SEric Auger static int vtd_iommu_notify_flag_changed(IOMMUMemoryRegion *iommu,
32215bf3d319SPeter Xu                                          IOMMUNotifierFlag old,
3222549d4005SEric Auger                                          IOMMUNotifierFlag new,
3223549d4005SEric Auger                                          Error **errp)
32243cb3b154SAlex Williamson {
32253cb3b154SAlex Williamson     VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu);
3226dd4d607eSPeter Xu     IntelIOMMUState *s = vtd_as->iommu_state;
322709adb0e0SJason Wang     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
32283cb3b154SAlex Williamson 
3229b8ffd7d6SJason Wang     /* TODO: add support for VFIO and vhost users */
3230b8ffd7d6SJason Wang     if (s->snoop_control) {
3231250227f4SJason Wang         error_setg_errno(errp, ENOTSUP,
3232b8ffd7d6SJason Wang                          "Snoop Control with vhost or VFIO is not supported");
3233b8ffd7d6SJason Wang         return -ENOTSUP;
3234b8ffd7d6SJason Wang     }
3235b8d78277SJason Wang     if (!s->caching_mode && (new & IOMMU_NOTIFIER_MAP)) {
3236b8d78277SJason Wang         error_setg_errno(errp, ENOTSUP,
3237b8d78277SJason Wang                          "device %02x.%02x.%x requires caching mode",
3238b8d78277SJason Wang                          pci_bus_num(vtd_as->bus), PCI_SLOT(vtd_as->devfn),
3239b8d78277SJason Wang                          PCI_FUNC(vtd_as->devfn));
3240b8d78277SJason Wang         return -ENOTSUP;
3241b8d78277SJason Wang     }
324209adb0e0SJason Wang     if (!x86_iommu->dt_supported && (new & IOMMU_NOTIFIER_DEVIOTLB_UNMAP)) {
324309adb0e0SJason Wang         error_setg_errno(errp, ENOTSUP,
324409adb0e0SJason Wang                          "device %02x.%02x.%x requires device IOTLB mode",
324509adb0e0SJason Wang                          pci_bus_num(vtd_as->bus), PCI_SLOT(vtd_as->devfn),
324609adb0e0SJason Wang                          PCI_FUNC(vtd_as->devfn));
324709adb0e0SJason Wang         return -ENOTSUP;
324809adb0e0SJason Wang     }
3249b8ffd7d6SJason Wang 
32504f8a62a9SPeter Xu     /* Update per-address-space notifier flags */
32514f8a62a9SPeter Xu     vtd_as->notifier_flags = new;
32524f8a62a9SPeter Xu 
3253dd4d607eSPeter Xu     if (old == IOMMU_NOTIFIER_NONE) {
3254b4a4ba0dSPeter Xu         QLIST_INSERT_HEAD(&s->vtd_as_with_notifiers, vtd_as, next);
3255b4a4ba0dSPeter Xu     } else if (new == IOMMU_NOTIFIER_NONE) {
3256b4a4ba0dSPeter Xu         QLIST_REMOVE(vtd_as, next);
3257dd4d607eSPeter Xu     }
3258549d4005SEric Auger     return 0;
32593cb3b154SAlex Williamson }
32603cb3b154SAlex Williamson 
3261552a1e01SPeter Xu static int vtd_post_load(void *opaque, int version_id)
3262552a1e01SPeter Xu {
3263552a1e01SPeter Xu     IntelIOMMUState *iommu = opaque;
3264552a1e01SPeter Xu 
3265552a1e01SPeter Xu     /*
32662811af3bSPeter Xu      * We don't need to migrate the root_scalable because we can
32672811af3bSPeter Xu      * simply do the calculation after the loading is complete.  We
32682811af3bSPeter Xu      * can actually do similar things with root, dmar_enabled, etc.
32692811af3bSPeter Xu      * however since we've had them already so we'd better keep them
32702811af3bSPeter Xu      * for compatibility of migration.
32712811af3bSPeter Xu      */
32722811af3bSPeter Xu     vtd_update_scalable_state(iommu);
32732811af3bSPeter Xu 
3274147a372eSJason Wang     vtd_update_iq_dw(iommu);
3275147a372eSJason Wang 
3276ceb05895SJason Wang     /*
3277ceb05895SJason Wang      * Memory regions are dynamically turned on/off depending on
3278ceb05895SJason Wang      * context entry configurations from the guest. After migration,
3279ceb05895SJason Wang      * we need to make sure the memory regions are still correct.
3280ceb05895SJason Wang      */
3281ceb05895SJason Wang     vtd_switch_address_space_all(iommu);
3282ceb05895SJason Wang 
3283552a1e01SPeter Xu     return 0;
3284552a1e01SPeter Xu }
3285552a1e01SPeter Xu 
32861da12ec4SLe Tan static const VMStateDescription vtd_vmstate = {
32871da12ec4SLe Tan     .name = "iommu-intel",
32888cdcf3c1SPeter Xu     .version_id = 1,
32898cdcf3c1SPeter Xu     .minimum_version_id = 1,
32908cdcf3c1SPeter Xu     .priority = MIG_PRI_IOMMU,
3291552a1e01SPeter Xu     .post_load = vtd_post_load,
32929231a017SRichard Henderson     .fields = (const VMStateField[]) {
32938cdcf3c1SPeter Xu         VMSTATE_UINT64(root, IntelIOMMUState),
32948cdcf3c1SPeter Xu         VMSTATE_UINT64(intr_root, IntelIOMMUState),
32958cdcf3c1SPeter Xu         VMSTATE_UINT64(iq, IntelIOMMUState),
32968cdcf3c1SPeter Xu         VMSTATE_UINT32(intr_size, IntelIOMMUState),
32978cdcf3c1SPeter Xu         VMSTATE_UINT16(iq_head, IntelIOMMUState),
32988cdcf3c1SPeter Xu         VMSTATE_UINT16(iq_tail, IntelIOMMUState),
32998cdcf3c1SPeter Xu         VMSTATE_UINT16(iq_size, IntelIOMMUState),
33008cdcf3c1SPeter Xu         VMSTATE_UINT16(next_frcd_reg, IntelIOMMUState),
33018cdcf3c1SPeter Xu         VMSTATE_UINT8_ARRAY(csr, IntelIOMMUState, DMAR_REG_SIZE),
33028cdcf3c1SPeter Xu         VMSTATE_UINT8(iq_last_desc_type, IntelIOMMUState),
330381fb1e64SPeter Xu         VMSTATE_UNUSED(1),      /* bool root_extended is obsolete by VT-d */
33048cdcf3c1SPeter Xu         VMSTATE_BOOL(dmar_enabled, IntelIOMMUState),
33058cdcf3c1SPeter Xu         VMSTATE_BOOL(qi_enabled, IntelIOMMUState),
33068cdcf3c1SPeter Xu         VMSTATE_BOOL(intr_enabled, IntelIOMMUState),
33078cdcf3c1SPeter Xu         VMSTATE_BOOL(intr_eime, IntelIOMMUState),
33088cdcf3c1SPeter Xu         VMSTATE_END_OF_LIST()
33098cdcf3c1SPeter Xu     }
33101da12ec4SLe Tan };
33111da12ec4SLe Tan 
33121da12ec4SLe Tan static const MemoryRegionOps vtd_mem_ops = {
33131da12ec4SLe Tan     .read = vtd_mem_read,
33141da12ec4SLe Tan     .write = vtd_mem_write,
33151da12ec4SLe Tan     .endianness = DEVICE_LITTLE_ENDIAN,
33161da12ec4SLe Tan     .impl = {
33171da12ec4SLe Tan         .min_access_size = 4,
33181da12ec4SLe Tan         .max_access_size = 8,
33191da12ec4SLe Tan     },
33201da12ec4SLe Tan     .valid = {
33211da12ec4SLe Tan         .min_access_size = 4,
33221da12ec4SLe Tan         .max_access_size = 8,
33231da12ec4SLe Tan     },
33241da12ec4SLe Tan };
33251da12ec4SLe Tan 
33261da12ec4SLe Tan static Property vtd_properties[] = {
33271da12ec4SLe Tan     DEFINE_PROP_UINT32("version", IntelIOMMUState, version, 0),
3328e6b6af05SRadim Krčmář     DEFINE_PROP_ON_OFF_AUTO("eim", IntelIOMMUState, intr_eim,
3329e6b6af05SRadim Krčmář                             ON_OFF_AUTO_AUTO),
3330fb506e70SRadim Krčmář     DEFINE_PROP_BOOL("x-buggy-eim", IntelIOMMUState, buggy_eim, false),
33314b49b586SPeter Xu     DEFINE_PROP_UINT8("aw-bits", IntelIOMMUState, aw_bits,
333237f51384SPrasad Singamsetty                       VTD_HOST_ADDRESS_WIDTH),
33333b40f0e5SAviv Ben-David     DEFINE_PROP_BOOL("caching-mode", IntelIOMMUState, caching_mode, FALSE),
33344a4f219eSYi Sun     DEFINE_PROP_BOOL("x-scalable-mode", IntelIOMMUState, scalable_mode, FALSE),
3335b8ffd7d6SJason Wang     DEFINE_PROP_BOOL("snoop-control", IntelIOMMUState, snoop_control, false),
33361b2b1237SJason Wang     DEFINE_PROP_BOOL("x-pasid-mode", IntelIOMMUState, pasid, false),
3337ccc23bb0SPeter Xu     DEFINE_PROP_BOOL("dma-drain", IntelIOMMUState, dma_drain, true),
33388646d9c7SDavid Woodhouse     DEFINE_PROP_BOOL("dma-translation", IntelIOMMUState, dma_translation, true),
33391da12ec4SLe Tan     DEFINE_PROP_END_OF_LIST(),
33401da12ec4SLe Tan };
33411da12ec4SLe Tan 
3342651e4cefSPeter Xu /* Read IRTE entry with specific index */
3343c7016bf7SDavid Woodhouse static bool vtd_irte_get(IntelIOMMUState *iommu, uint16_t index,
3344c7016bf7SDavid Woodhouse                          VTD_IR_TableEntry *entry, uint16_t sid,
3345c7016bf7SDavid Woodhouse                          bool do_fault)
3346651e4cefSPeter Xu {
3347ede9c94aSPeter Xu     static const uint16_t vtd_svt_mask[VTD_SQ_MAX] = \
3348ede9c94aSPeter Xu         {0xffff, 0xfffb, 0xfff9, 0xfff8};
3349651e4cefSPeter Xu     dma_addr_t addr = 0x00;
3350ede9c94aSPeter Xu     uint16_t mask, source_id;
3351ede9c94aSPeter Xu     uint8_t bus, bus_max, bus_min;
3352651e4cefSPeter Xu 
33533c507c26SJan Kiszka     if (index >= iommu->intr_size) {
33543c507c26SJan Kiszka         error_report_once("%s: index too large: ind=0x%x",
33553c507c26SJan Kiszka                           __func__, index);
3356c7016bf7SDavid Woodhouse         if (do_fault) {
3357c7016bf7SDavid Woodhouse             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_INDEX_OVER, index);
3358c7016bf7SDavid Woodhouse         }
3359c7016bf7SDavid Woodhouse         return false;
33603c507c26SJan Kiszka     }
33613c507c26SJan Kiszka 
3362651e4cefSPeter Xu     addr = iommu->intr_root + index * sizeof(*entry);
3363ba06fe8aSPhilippe Mathieu-Daudé     if (dma_memory_read(&address_space_memory, addr,
3364ba06fe8aSPhilippe Mathieu-Daudé                         entry, sizeof(*entry), MEMTXATTRS_UNSPECIFIED)) {
33651376211fSPeter Xu         error_report_once("%s: read failed: ind=0x%x addr=0x%" PRIx64,
33661376211fSPeter Xu                           __func__, index, addr);
3367c7016bf7SDavid Woodhouse         if (do_fault) {
3368c7016bf7SDavid Woodhouse             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_ROOT_INVAL, index);
3369c7016bf7SDavid Woodhouse         }
3370c7016bf7SDavid Woodhouse         return false;
3371651e4cefSPeter Xu     }
3372651e4cefSPeter Xu 
3373642ba896SThomas Huth     entry->data[0] = le64_to_cpu(entry->data[0]);
3374642ba896SThomas Huth     entry->data[1] = le64_to_cpu(entry->data[1]);
3375642ba896SThomas Huth 
3376642ba896SThomas Huth     trace_vtd_ir_irte_get(index, entry->data[1], entry->data[0]);
33777feb51b7SPeter Xu 
3378c7016bf7SDavid Woodhouse     /*
3379c7016bf7SDavid Woodhouse      * The remaining potential fault conditions are "qualified" by the
3380c7016bf7SDavid Woodhouse      * Fault Processing Disable bit in the IRTE. Even "not present".
3381c7016bf7SDavid Woodhouse      * So just clear the do_fault flag if PFD is set, which will
3382c7016bf7SDavid Woodhouse      * prevent faults being raised.
3383c7016bf7SDavid Woodhouse      */
3384c7016bf7SDavid Woodhouse     if (entry->irte.fault_disable) {
3385c7016bf7SDavid Woodhouse         do_fault = false;
3386c7016bf7SDavid Woodhouse     }
3387c7016bf7SDavid Woodhouse 
3388bc38ee10SMichael S. Tsirkin     if (!entry->irte.present) {
33894e4abd11SPeter Xu         error_report_once("%s: detected non-present IRTE "
33904e4abd11SPeter Xu                           "(index=%u, high=0x%" PRIx64 ", low=0x%" PRIx64 ")",
3391642ba896SThomas Huth                           __func__, index, entry->data[1], entry->data[0]);
3392c7016bf7SDavid Woodhouse         if (do_fault) {
3393c7016bf7SDavid Woodhouse             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_ENTRY_P, index);
3394c7016bf7SDavid Woodhouse         }
3395c7016bf7SDavid Woodhouse         return false;
3396651e4cefSPeter Xu     }
3397651e4cefSPeter Xu 
3398bc38ee10SMichael S. Tsirkin     if (entry->irte.__reserved_0 || entry->irte.__reserved_1 ||
3399bc38ee10SMichael S. Tsirkin         entry->irte.__reserved_2) {
34004e4abd11SPeter Xu         error_report_once("%s: detected non-zero reserved IRTE "
34014e4abd11SPeter Xu                           "(index=%u, high=0x%" PRIx64 ", low=0x%" PRIx64 ")",
3402642ba896SThomas Huth                           __func__, index, entry->data[1], entry->data[0]);
3403c7016bf7SDavid Woodhouse         if (do_fault) {
3404c7016bf7SDavid Woodhouse             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_IRTE_RSVD, index);
3405c7016bf7SDavid Woodhouse         }
3406c7016bf7SDavid Woodhouse         return false;
3407651e4cefSPeter Xu     }
3408651e4cefSPeter Xu 
3409ede9c94aSPeter Xu     if (sid != X86_IOMMU_SID_INVALID) {
3410ede9c94aSPeter Xu         /* Validate IRTE SID */
3411642ba896SThomas Huth         source_id = entry->irte.source_id;
3412bc38ee10SMichael S. Tsirkin         switch (entry->irte.sid_vtype) {
3413ede9c94aSPeter Xu         case VTD_SVT_NONE:
3414ede9c94aSPeter Xu             break;
3415ede9c94aSPeter Xu 
3416ede9c94aSPeter Xu         case VTD_SVT_ALL:
3417bc38ee10SMichael S. Tsirkin             mask = vtd_svt_mask[entry->irte.sid_q];
3418ede9c94aSPeter Xu             if ((source_id & mask) != (sid & mask)) {
34194e4abd11SPeter Xu                 error_report_once("%s: invalid IRTE SID "
34204e4abd11SPeter Xu                                   "(index=%u, sid=%u, source_id=%u)",
34214e4abd11SPeter Xu                                   __func__, index, sid, source_id);
3422c7016bf7SDavid Woodhouse                 if (do_fault) {
3423c7016bf7SDavid Woodhouse                     vtd_report_ir_fault(iommu, sid, VTD_FR_IR_SID_ERR, index);
3424c7016bf7SDavid Woodhouse                 }
3425c7016bf7SDavid Woodhouse                 return false;
3426ede9c94aSPeter Xu             }
3427ede9c94aSPeter Xu             break;
3428ede9c94aSPeter Xu 
3429ede9c94aSPeter Xu         case VTD_SVT_BUS:
3430ede9c94aSPeter Xu             bus_max = source_id >> 8;
3431ede9c94aSPeter Xu             bus_min = source_id & 0xff;
3432ede9c94aSPeter Xu             bus = sid >> 8;
3433ede9c94aSPeter Xu             if (bus > bus_max || bus < bus_min) {
34344e4abd11SPeter Xu                 error_report_once("%s: invalid SVT_BUS "
34354e4abd11SPeter Xu                                   "(index=%u, bus=%u, min=%u, max=%u)",
34364e4abd11SPeter Xu                                   __func__, index, bus, bus_min, bus_max);
3437c7016bf7SDavid Woodhouse                 if (do_fault) {
3438c7016bf7SDavid Woodhouse                     vtd_report_ir_fault(iommu, sid, VTD_FR_IR_SID_ERR, index);
3439c7016bf7SDavid Woodhouse                 }
3440c7016bf7SDavid Woodhouse                 return false;
3441ede9c94aSPeter Xu             }
3442ede9c94aSPeter Xu             break;
3443ede9c94aSPeter Xu 
3444ede9c94aSPeter Xu         default:
34454e4abd11SPeter Xu             error_report_once("%s: detected invalid IRTE SVT "
34464e4abd11SPeter Xu                               "(index=%u, type=%d)", __func__,
34474e4abd11SPeter Xu                               index, entry->irte.sid_vtype);
3448ede9c94aSPeter Xu             /* Take this as verification failure. */
3449c7016bf7SDavid Woodhouse             if (do_fault) {
3450c7016bf7SDavid Woodhouse                 vtd_report_ir_fault(iommu, sid, VTD_FR_IR_SID_ERR, index);
3451c7016bf7SDavid Woodhouse             }
3452c7016bf7SDavid Woodhouse             return false;
3453ede9c94aSPeter Xu         }
3454ede9c94aSPeter Xu     }
3455651e4cefSPeter Xu 
3456c7016bf7SDavid Woodhouse     return true;
3457651e4cefSPeter Xu }
3458651e4cefSPeter Xu 
3459651e4cefSPeter Xu /* Fetch IRQ information of specific IR index */
3460c7016bf7SDavid Woodhouse static bool vtd_remap_irq_get(IntelIOMMUState *iommu, uint16_t index,
3461c7016bf7SDavid Woodhouse                               X86IOMMUIrq *irq, uint16_t sid, bool do_fault)
3462651e4cefSPeter Xu {
3463bc38ee10SMichael S. Tsirkin     VTD_IR_TableEntry irte = {};
3464651e4cefSPeter Xu 
3465c7016bf7SDavid Woodhouse     if (!vtd_irte_get(iommu, index, &irte, sid, do_fault)) {
3466c7016bf7SDavid Woodhouse         return false;
3467651e4cefSPeter Xu     }
3468651e4cefSPeter Xu 
3469bc38ee10SMichael S. Tsirkin     irq->trigger_mode = irte.irte.trigger_mode;
3470bc38ee10SMichael S. Tsirkin     irq->vector = irte.irte.vector;
3471bc38ee10SMichael S. Tsirkin     irq->delivery_mode = irte.irte.delivery_mode;
3472642ba896SThomas Huth     irq->dest = irte.irte.dest_id;
347328589311SJan Kiszka     if (!iommu->intr_eime) {
3474651e4cefSPeter Xu #define  VTD_IR_APIC_DEST_MASK         (0xff00ULL)
3475651e4cefSPeter Xu #define  VTD_IR_APIC_DEST_SHIFT        (8)
347628589311SJan Kiszka         irq->dest = (irq->dest & VTD_IR_APIC_DEST_MASK) >>
3477651e4cefSPeter Xu             VTD_IR_APIC_DEST_SHIFT;
347828589311SJan Kiszka     }
3479bc38ee10SMichael S. Tsirkin     irq->dest_mode = irte.irte.dest_mode;
3480bc38ee10SMichael S. Tsirkin     irq->redir_hint = irte.irte.redir_hint;
3481651e4cefSPeter Xu 
34827feb51b7SPeter Xu     trace_vtd_ir_remap(index, irq->trigger_mode, irq->vector,
34837feb51b7SPeter Xu                        irq->delivery_mode, irq->dest, irq->dest_mode);
3484651e4cefSPeter Xu 
3485c7016bf7SDavid Woodhouse     return true;
3486651e4cefSPeter Xu }
3487651e4cefSPeter Xu 
3488651e4cefSPeter Xu /* Interrupt remapping for MSI/MSI-X entry */
3489651e4cefSPeter Xu static int vtd_interrupt_remap_msi(IntelIOMMUState *iommu,
3490651e4cefSPeter Xu                                    MSIMessage *origin,
3491ede9c94aSPeter Xu                                    MSIMessage *translated,
3492c7016bf7SDavid Woodhouse                                    uint16_t sid, bool do_fault)
3493651e4cefSPeter Xu {
3494651e4cefSPeter Xu     VTD_IR_MSIAddress addr;
3495651e4cefSPeter Xu     uint16_t index;
349635c24501SSingh, Brijesh     X86IOMMUIrq irq = {};
3497651e4cefSPeter Xu 
3498651e4cefSPeter Xu     assert(origin && translated);
3499651e4cefSPeter Xu 
35007feb51b7SPeter Xu     trace_vtd_ir_remap_msi_req(origin->address, origin->data);
35017feb51b7SPeter Xu 
3502651e4cefSPeter Xu     if (!iommu || !iommu->intr_enabled) {
3503e7a3b91fSPeter Xu         memcpy(translated, origin, sizeof(*origin));
3504e7a3b91fSPeter Xu         goto out;
3505651e4cefSPeter Xu     }
3506651e4cefSPeter Xu 
3507651e4cefSPeter Xu     if (origin->address & VTD_MSI_ADDR_HI_MASK) {
35081376211fSPeter Xu         error_report_once("%s: MSI address high 32 bits non-zero detected: "
35091376211fSPeter Xu                           "address=0x%" PRIx64, __func__, origin->address);
3510c7016bf7SDavid Woodhouse         if (do_fault) {
3511c7016bf7SDavid Woodhouse             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_REQ_RSVD, 0);
3512c7016bf7SDavid Woodhouse         }
3513c7016bf7SDavid Woodhouse         return -EINVAL;
3514651e4cefSPeter Xu     }
3515651e4cefSPeter Xu 
3516651e4cefSPeter Xu     addr.data = origin->address & VTD_MSI_ADDR_LO_MASK;
35171a43713bSPeter Xu     if (addr.addr.__head != 0xfee) {
35181376211fSPeter Xu         error_report_once("%s: MSI address low 32 bit invalid: 0x%" PRIx32,
35191376211fSPeter Xu                           __func__, addr.data);
3520c7016bf7SDavid Woodhouse         if (do_fault) {
3521c7016bf7SDavid Woodhouse             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_REQ_RSVD, 0);
3522c7016bf7SDavid Woodhouse         }
3523c7016bf7SDavid Woodhouse         return -EINVAL;
3524651e4cefSPeter Xu     }
3525651e4cefSPeter Xu 
3526651e4cefSPeter Xu     /* This is compatible mode. */
3527bc38ee10SMichael S. Tsirkin     if (addr.addr.int_mode != VTD_IR_INT_FORMAT_REMAP) {
3528e7a3b91fSPeter Xu         memcpy(translated, origin, sizeof(*origin));
3529e7a3b91fSPeter Xu         goto out;
3530651e4cefSPeter Xu     }
3531651e4cefSPeter Xu 
3532fcd80274SThomas Huth     index = addr.addr.index_h << 15 | addr.addr.index_l;
3533651e4cefSPeter Xu 
3534651e4cefSPeter Xu #define  VTD_IR_MSI_DATA_SUBHANDLE       (0x0000ffff)
3535651e4cefSPeter Xu #define  VTD_IR_MSI_DATA_RESERVED        (0xffff0000)
3536651e4cefSPeter Xu 
3537bc38ee10SMichael S. Tsirkin     if (addr.addr.sub_valid) {
3538651e4cefSPeter Xu         /* See VT-d spec 5.1.2.2 and 5.1.3 on subhandle */
3539651e4cefSPeter Xu         index += origin->data & VTD_IR_MSI_DATA_SUBHANDLE;
3540651e4cefSPeter Xu     }
3541651e4cefSPeter Xu 
3542c7016bf7SDavid Woodhouse     if (!vtd_remap_irq_get(iommu, index, &irq, sid, do_fault)) {
3543c7016bf7SDavid Woodhouse         return -EINVAL;
3544651e4cefSPeter Xu     }
3545651e4cefSPeter Xu 
3546bc38ee10SMichael S. Tsirkin     if (addr.addr.sub_valid) {
35477feb51b7SPeter Xu         trace_vtd_ir_remap_type("MSI");
3548651e4cefSPeter Xu         if (origin->data & VTD_IR_MSI_DATA_RESERVED) {
35494e4abd11SPeter Xu             error_report_once("%s: invalid IR MSI "
35504e4abd11SPeter Xu                               "(sid=%u, address=0x%" PRIx64
35514e4abd11SPeter Xu                               ", data=0x%" PRIx32 ")",
35524e4abd11SPeter Xu                               __func__, sid, origin->address, origin->data);
3553c7016bf7SDavid Woodhouse             if (do_fault) {
3554c7016bf7SDavid Woodhouse                 vtd_report_ir_fault(iommu, sid, VTD_FR_IR_REQ_RSVD, 0);
3555c7016bf7SDavid Woodhouse             }
3556c7016bf7SDavid Woodhouse             return -EINVAL;
3557651e4cefSPeter Xu         }
3558651e4cefSPeter Xu     } else {
3559651e4cefSPeter Xu         uint8_t vector = origin->data & 0xff;
3560dea651a9SFeng Wu         uint8_t trigger_mode = (origin->data >> MSI_DATA_TRIGGER_SHIFT) & 0x1;
3561dea651a9SFeng Wu 
35627feb51b7SPeter Xu         trace_vtd_ir_remap_type("IOAPIC");
3563651e4cefSPeter Xu         /* IOAPIC entry vector should be aligned with IRTE vector
3564651e4cefSPeter Xu          * (see vt-d spec 5.1.5.1). */
3565651e4cefSPeter Xu         if (vector != irq.vector) {
35667feb51b7SPeter Xu             trace_vtd_warn_ir_vector(sid, index, vector, irq.vector);
3567651e4cefSPeter Xu         }
3568dea651a9SFeng Wu 
3569dea651a9SFeng Wu         /* The Trigger Mode field must match the Trigger Mode in the IRTE.
3570dea651a9SFeng Wu          * (see vt-d spec 5.1.5.1). */
3571dea651a9SFeng Wu         if (trigger_mode != irq.trigger_mode) {
35727feb51b7SPeter Xu             trace_vtd_warn_ir_trigger(sid, index, trigger_mode,
35737feb51b7SPeter Xu                                       irq.trigger_mode);
3574dea651a9SFeng Wu         }
3575651e4cefSPeter Xu     }
3576651e4cefSPeter Xu 
3577651e4cefSPeter Xu     /*
3578651e4cefSPeter Xu      * We'd better keep the last two bits, assuming that guest OS
3579651e4cefSPeter Xu      * might modify it. Keep it does not hurt after all.
3580651e4cefSPeter Xu      */
3581bc38ee10SMichael S. Tsirkin     irq.msi_addr_last_bits = addr.addr.__not_care;
3582651e4cefSPeter Xu 
358335c24501SSingh, Brijesh     /* Translate X86IOMMUIrq to MSI message */
358435c24501SSingh, Brijesh     x86_iommu_irq_to_msi_message(&irq, translated);
3585651e4cefSPeter Xu 
3586e7a3b91fSPeter Xu out:
35877feb51b7SPeter Xu     trace_vtd_ir_remap_msi(origin->address, origin->data,
3588651e4cefSPeter Xu                            translated->address, translated->data);
3589651e4cefSPeter Xu     return 0;
3590651e4cefSPeter Xu }
3591651e4cefSPeter Xu 
35928b5ed7dfSPeter Xu static int vtd_int_remap(X86IOMMUState *iommu, MSIMessage *src,
35938b5ed7dfSPeter Xu                          MSIMessage *dst, uint16_t sid)
35948b5ed7dfSPeter Xu {
3595ede9c94aSPeter Xu     return vtd_interrupt_remap_msi(INTEL_IOMMU_DEVICE(iommu),
3596c7016bf7SDavid Woodhouse                                    src, dst, sid, false);
35978b5ed7dfSPeter Xu }
35988b5ed7dfSPeter Xu 
3599651e4cefSPeter Xu static MemTxResult vtd_mem_ir_read(void *opaque, hwaddr addr,
3600651e4cefSPeter Xu                                    uint64_t *data, unsigned size,
3601651e4cefSPeter Xu                                    MemTxAttrs attrs)
3602651e4cefSPeter Xu {
3603651e4cefSPeter Xu     return MEMTX_OK;
3604651e4cefSPeter Xu }
3605651e4cefSPeter Xu 
3606651e4cefSPeter Xu static MemTxResult vtd_mem_ir_write(void *opaque, hwaddr addr,
3607651e4cefSPeter Xu                                     uint64_t value, unsigned size,
3608651e4cefSPeter Xu                                     MemTxAttrs attrs)
3609651e4cefSPeter Xu {
3610651e4cefSPeter Xu     int ret = 0;
361109cd058aSMichael S. Tsirkin     MSIMessage from = {}, to = {};
3612ede9c94aSPeter Xu     uint16_t sid = X86_IOMMU_SID_INVALID;
3613651e4cefSPeter Xu 
3614651e4cefSPeter Xu     from.address = (uint64_t) addr + VTD_INTERRUPT_ADDR_FIRST;
3615651e4cefSPeter Xu     from.data = (uint32_t) value;
3616651e4cefSPeter Xu 
3617ede9c94aSPeter Xu     if (!attrs.unspecified) {
3618ede9c94aSPeter Xu         /* We have explicit Source ID */
3619ede9c94aSPeter Xu         sid = attrs.requester_id;
3620ede9c94aSPeter Xu     }
3621ede9c94aSPeter Xu 
3622c7016bf7SDavid Woodhouse     ret = vtd_interrupt_remap_msi(opaque, &from, &to, sid, true);
3623651e4cefSPeter Xu     if (ret) {
3624651e4cefSPeter Xu         /* Drop this interrupt */
3625651e4cefSPeter Xu         return MEMTX_ERROR;
3626651e4cefSPeter Xu     }
3627651e4cefSPeter Xu 
3628eaaaf8abSPaolo Bonzini     apic_get_class(NULL)->send_msi(&to);
3629651e4cefSPeter Xu 
3630651e4cefSPeter Xu     return MEMTX_OK;
3631651e4cefSPeter Xu }
3632651e4cefSPeter Xu 
3633651e4cefSPeter Xu static const MemoryRegionOps vtd_mem_ir_ops = {
3634651e4cefSPeter Xu     .read_with_attrs = vtd_mem_ir_read,
3635651e4cefSPeter Xu     .write_with_attrs = vtd_mem_ir_write,
3636651e4cefSPeter Xu     .endianness = DEVICE_LITTLE_ENDIAN,
3637651e4cefSPeter Xu     .impl = {
3638651e4cefSPeter Xu         .min_access_size = 4,
3639651e4cefSPeter Xu         .max_access_size = 4,
3640651e4cefSPeter Xu     },
3641651e4cefSPeter Xu     .valid = {
3642651e4cefSPeter Xu         .min_access_size = 4,
3643651e4cefSPeter Xu         .max_access_size = 4,
3644651e4cefSPeter Xu     },
3645651e4cefSPeter Xu };
36467df953bdSKnut Omang 
36471b2b1237SJason Wang static void vtd_report_ir_illegal_access(VTDAddressSpace *vtd_as,
36481b2b1237SJason Wang                                          hwaddr addr, bool is_write)
36491b2b1237SJason Wang {
36501b2b1237SJason Wang     IntelIOMMUState *s = vtd_as->iommu_state;
36511b2b1237SJason Wang     uint8_t bus_n = pci_bus_num(vtd_as->bus);
36521b2b1237SJason Wang     uint16_t sid = PCI_BUILD_BDF(bus_n, vtd_as->devfn);
36531b2b1237SJason Wang     bool is_fpd_set = false;
36541b2b1237SJason Wang     VTDContextEntry ce;
36551b2b1237SJason Wang 
36561b2b1237SJason Wang     assert(vtd_as->pasid != PCI_NO_PASID);
36571b2b1237SJason Wang 
36581b2b1237SJason Wang     /* Try out best to fetch FPD, we can't do anything more */
36591b2b1237SJason Wang     if (vtd_dev_to_context_entry(s, bus_n, vtd_as->devfn, &ce) == 0) {
36601b2b1237SJason Wang         is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;
36611b2b1237SJason Wang         if (!is_fpd_set && s->root_scalable) {
36621b2b1237SJason Wang             vtd_ce_get_pasid_fpd(s, &ce, &is_fpd_set, vtd_as->pasid);
36631b2b1237SJason Wang         }
36641b2b1237SJason Wang     }
36651b2b1237SJason Wang 
36661b2b1237SJason Wang     vtd_report_fault(s, VTD_FR_SM_INTERRUPT_ADDR,
36671b2b1237SJason Wang                      is_fpd_set, sid, addr, is_write,
36681b2b1237SJason Wang                      true, vtd_as->pasid);
36691b2b1237SJason Wang }
36701b2b1237SJason Wang 
36711b2b1237SJason Wang static MemTxResult vtd_mem_ir_fault_read(void *opaque, hwaddr addr,
36721b2b1237SJason Wang                                          uint64_t *data, unsigned size,
36731b2b1237SJason Wang                                          MemTxAttrs attrs)
36741b2b1237SJason Wang {
36751b2b1237SJason Wang     vtd_report_ir_illegal_access(opaque, addr, false);
36761b2b1237SJason Wang 
36771b2b1237SJason Wang     return MEMTX_ERROR;
36781b2b1237SJason Wang }
36791b2b1237SJason Wang 
36801b2b1237SJason Wang static MemTxResult vtd_mem_ir_fault_write(void *opaque, hwaddr addr,
36811b2b1237SJason Wang                                           uint64_t value, unsigned size,
36821b2b1237SJason Wang                                           MemTxAttrs attrs)
36831b2b1237SJason Wang {
36841b2b1237SJason Wang     vtd_report_ir_illegal_access(opaque, addr, true);
36851b2b1237SJason Wang 
36861b2b1237SJason Wang     return MEMTX_ERROR;
36871b2b1237SJason Wang }
36881b2b1237SJason Wang 
36891b2b1237SJason Wang static const MemoryRegionOps vtd_mem_ir_fault_ops = {
36901b2b1237SJason Wang     .read_with_attrs = vtd_mem_ir_fault_read,
36911b2b1237SJason Wang     .write_with_attrs = vtd_mem_ir_fault_write,
36921b2b1237SJason Wang     .endianness = DEVICE_LITTLE_ENDIAN,
36931b2b1237SJason Wang     .impl = {
36941b2b1237SJason Wang         .min_access_size = 1,
36951b2b1237SJason Wang         .max_access_size = 8,
36961b2b1237SJason Wang     },
36971b2b1237SJason Wang     .valid = {
36981b2b1237SJason Wang         .min_access_size = 1,
36991b2b1237SJason Wang         .max_access_size = 8,
37001b2b1237SJason Wang     },
37011b2b1237SJason Wang };
37021b2b1237SJason Wang 
37031b2b1237SJason Wang VTDAddressSpace *vtd_find_add_as(IntelIOMMUState *s, PCIBus *bus,
37041b2b1237SJason Wang                                  int devfn, unsigned int pasid)
37057df953bdSKnut Omang {
3706da8d439cSJason Wang     /*
3707da8d439cSJason Wang      * We can't simply use sid here since the bus number might not be
3708da8d439cSJason Wang      * initialized by the guest.
3709da8d439cSJason Wang      */
3710da8d439cSJason Wang     struct vtd_as_key key = {
3711da8d439cSJason Wang         .bus = bus,
3712da8d439cSJason Wang         .devfn = devfn,
37131b2b1237SJason Wang         .pasid = pasid,
3714da8d439cSJason Wang     };
37157df953bdSKnut Omang     VTDAddressSpace *vtd_dev_as;
3716e0a3c8ccSJason Wang     char name[128];
37177df953bdSKnut Omang 
3718da8d439cSJason Wang     vtd_dev_as = g_hash_table_lookup(s->vtd_address_spaces, &key);
37197df953bdSKnut Omang     if (!vtd_dev_as) {
3720da8d439cSJason Wang         struct vtd_as_key *new_key = g_malloc(sizeof(*new_key));
3721da8d439cSJason Wang 
3722da8d439cSJason Wang         new_key->bus = bus;
3723da8d439cSJason Wang         new_key->devfn = devfn;
37241b2b1237SJason Wang         new_key->pasid = pasid;
3725da8d439cSJason Wang 
37261b2b1237SJason Wang         if (pasid == PCI_NO_PASID) {
37274b519ef1SPeter Xu             snprintf(name, sizeof(name), "vtd-%02x.%x", PCI_SLOT(devfn),
37284b519ef1SPeter Xu                      PCI_FUNC(devfn));
37291b2b1237SJason Wang         } else {
37301b2b1237SJason Wang             snprintf(name, sizeof(name), "vtd-%02x.%x-pasid-%x", PCI_SLOT(devfn),
37311b2b1237SJason Wang                      PCI_FUNC(devfn), pasid);
37321b2b1237SJason Wang         }
37331b2b1237SJason Wang 
3734da8d439cSJason Wang         vtd_dev_as = g_new0(VTDAddressSpace, 1);
37357df953bdSKnut Omang 
37367df953bdSKnut Omang         vtd_dev_as->bus = bus;
37377df953bdSKnut Omang         vtd_dev_as->devfn = (uint8_t)devfn;
37381b2b1237SJason Wang         vtd_dev_as->pasid = pasid;
37397df953bdSKnut Omang         vtd_dev_as->iommu_state = s;
37407df953bdSKnut Omang         vtd_dev_as->context_cache_entry.context_cache_gen = 0;
374163b88968SPeter Xu         vtd_dev_as->iova_tree = iova_tree_new();
3742558e0024SPeter Xu 
37434b519ef1SPeter Xu         memory_region_init(&vtd_dev_as->root, OBJECT(s), name, UINT64_MAX);
37444b519ef1SPeter Xu         address_space_init(&vtd_dev_as->as, &vtd_dev_as->root, "vtd-root");
37454b519ef1SPeter Xu 
3746558e0024SPeter Xu         /*
37474b519ef1SPeter Xu          * Build the DMAR-disabled container with aliases to the
37484b519ef1SPeter Xu          * shared MRs.  Note that aliasing to a shared memory region
37494b519ef1SPeter Xu          * could help the memory API to detect same FlatViews so we
37504b519ef1SPeter Xu          * can have devices to share the same FlatView when DMAR is
37514b519ef1SPeter Xu          * disabled (either by not providing "intel_iommu=on" or with
37524b519ef1SPeter Xu          * "iommu=pt").  It will greatly reduce the total number of
37534b519ef1SPeter Xu          * FlatViews of the system hence VM runs faster.
3754558e0024SPeter Xu          */
37554b519ef1SPeter Xu         memory_region_init_alias(&vtd_dev_as->nodmar, OBJECT(s),
37564b519ef1SPeter Xu                                  "vtd-nodmar", &s->mr_nodmar, 0,
37574b519ef1SPeter Xu                                  memory_region_size(&s->mr_nodmar));
37584b519ef1SPeter Xu 
37594b519ef1SPeter Xu         /*
37604b519ef1SPeter Xu          * Build the per-device DMAR-enabled container.
37614b519ef1SPeter Xu          *
37624b519ef1SPeter Xu          * TODO: currently we have per-device IOMMU memory region only
37634b519ef1SPeter Xu          * because we have per-device IOMMU notifiers for devices.  If
37644b519ef1SPeter Xu          * one day we can abstract the IOMMU notifiers out of the
37654b519ef1SPeter Xu          * memory regions then we can also share the same memory
37664b519ef1SPeter Xu          * region here just like what we've done above with the nodmar
37674b519ef1SPeter Xu          * region.
37684b519ef1SPeter Xu          */
37694b519ef1SPeter Xu         strcat(name, "-dmar");
37701221a474SAlexey Kardashevskiy         memory_region_init_iommu(&vtd_dev_as->iommu, sizeof(vtd_dev_as->iommu),
37711221a474SAlexey Kardashevskiy                                  TYPE_INTEL_IOMMU_MEMORY_REGION, OBJECT(s),
37724b519ef1SPeter Xu                                  name, UINT64_MAX);
37734b519ef1SPeter Xu         memory_region_init_alias(&vtd_dev_as->iommu_ir, OBJECT(s), "vtd-ir",
37744b519ef1SPeter Xu                                  &s->mr_ir, 0, memory_region_size(&s->mr_ir));
37754b519ef1SPeter Xu         memory_region_add_subregion_overlap(MEMORY_REGION(&vtd_dev_as->iommu),
3776558e0024SPeter Xu                                             VTD_INTERRUPT_ADDR_FIRST,
37774b519ef1SPeter Xu                                             &vtd_dev_as->iommu_ir, 1);
37784b519ef1SPeter Xu 
37794b519ef1SPeter Xu         /*
37801b2b1237SJason Wang          * This region is used for catching fault to access interrupt
37811b2b1237SJason Wang          * range via passthrough + PASID. See also
37821b2b1237SJason Wang          * vtd_switch_address_space(). We can't use alias since we
37831b2b1237SJason Wang          * need to know the sid which is valid for MSI who uses
37841b2b1237SJason Wang          * bus_master_as (see msi_send_message()).
37851b2b1237SJason Wang          */
37861b2b1237SJason Wang         memory_region_init_io(&vtd_dev_as->iommu_ir_fault, OBJECT(s),
37871b2b1237SJason Wang                               &vtd_mem_ir_fault_ops, vtd_dev_as, "vtd-no-ir",
37881b2b1237SJason Wang                               VTD_INTERRUPT_ADDR_SIZE);
37891b2b1237SJason Wang         /*
37901b2b1237SJason Wang          * Hook to root since when PT is enabled vtd_dev_as->iommu
37911b2b1237SJason Wang          * will be disabled.
37921b2b1237SJason Wang          */
37931b2b1237SJason Wang         memory_region_add_subregion_overlap(MEMORY_REGION(&vtd_dev_as->root),
37941b2b1237SJason Wang                                             VTD_INTERRUPT_ADDR_FIRST,
37951b2b1237SJason Wang                                             &vtd_dev_as->iommu_ir_fault, 2);
37961b2b1237SJason Wang 
37971b2b1237SJason Wang         /*
37984b519ef1SPeter Xu          * Hook both the containers under the root container, we
37994b519ef1SPeter Xu          * switch between DMAR & noDMAR by enable/disable
38004b519ef1SPeter Xu          * corresponding sub-containers
38014b519ef1SPeter Xu          */
3802558e0024SPeter Xu         memory_region_add_subregion_overlap(&vtd_dev_as->root, 0,
38033df9d748SAlexey Kardashevskiy                                             MEMORY_REGION(&vtd_dev_as->iommu),
38044b519ef1SPeter Xu                                             0);
38054b519ef1SPeter Xu         memory_region_add_subregion_overlap(&vtd_dev_as->root, 0,
38064b519ef1SPeter Xu                                             &vtd_dev_as->nodmar, 0);
38074b519ef1SPeter Xu 
3808558e0024SPeter Xu         vtd_switch_address_space(vtd_dev_as);
3809da8d439cSJason Wang 
3810da8d439cSJason Wang         g_hash_table_insert(s->vtd_address_spaces, new_key, vtd_dev_as);
38117df953bdSKnut Omang     }
38127df953bdSKnut Omang     return vtd_dev_as;
38137df953bdSKnut Omang }
38147df953bdSKnut Omang 
3815dd4d607eSPeter Xu /* Unmap the whole range in the notifier's scope. */
3816dd4d607eSPeter Xu static void vtd_address_space_unmap(VTDAddressSpace *as, IOMMUNotifier *n)
3817dd4d607eSPeter Xu {
3818a082739eSPeter Xu     hwaddr total, remain;
3819dd4d607eSPeter Xu     hwaddr start = n->start;
3820dd4d607eSPeter Xu     hwaddr end = n->end;
382137f51384SPrasad Singamsetty     IntelIOMMUState *s = as->iommu_state;
382263b88968SPeter Xu     DMAMap map;
3823dd4d607eSPeter Xu 
3824dd4d607eSPeter Xu     /*
3825dd4d607eSPeter Xu      * Note: all the codes in this function has a assumption that IOVA
3826dd4d607eSPeter Xu      * bits are no more than VTD_MGAW bits (which is restricted by
3827dd4d607eSPeter Xu      * VT-d spec), otherwise we need to consider overflow of 64 bits.
3828dd4d607eSPeter Xu      */
3829dd4d607eSPeter Xu 
3830d6d10793SYan Zhao     if (end > VTD_ADDRESS_SIZE(s->aw_bits) - 1) {
3831dd4d607eSPeter Xu         /*
3832dd4d607eSPeter Xu          * Don't need to unmap regions that is bigger than the whole
3833dd4d607eSPeter Xu          * VT-d supported address space size
3834dd4d607eSPeter Xu          */
3835d6d10793SYan Zhao         end = VTD_ADDRESS_SIZE(s->aw_bits) - 1;
3836dd4d607eSPeter Xu     }
3837dd4d607eSPeter Xu 
3838dd4d607eSPeter Xu     assert(start <= end);
3839a082739eSPeter Xu     total = remain = end - start + 1;
3840dd4d607eSPeter Xu 
38419a4bb839SPeter Xu     while (remain >= VTD_PAGE_SIZE) {
38425039caf3SEugenio Pérez         IOMMUTLBEvent event;
3843f14fb6c2SEric Auger         uint64_t mask = dma_aligned_pow2_mask(start, end, s->aw_bits);
3844f14fb6c2SEric Auger         uint64_t size = mask + 1;
3845dd4d607eSPeter Xu 
3846f14fb6c2SEric Auger         assert(size);
38479a4bb839SPeter Xu 
38485039caf3SEugenio Pérez         event.type = IOMMU_NOTIFIER_UNMAP;
38495039caf3SEugenio Pérez         event.entry.iova = start;
3850f14fb6c2SEric Auger         event.entry.addr_mask = mask;
38515039caf3SEugenio Pérez         event.entry.target_as = &address_space_memory;
38525039caf3SEugenio Pérez         event.entry.perm = IOMMU_NONE;
3853dd4d607eSPeter Xu         /* This field is meaningless for unmap */
38545039caf3SEugenio Pérez         event.entry.translated_addr = 0;
38559a4bb839SPeter Xu 
38565039caf3SEugenio Pérez         memory_region_notify_iommu_one(n, &event);
38579a4bb839SPeter Xu 
3858f14fb6c2SEric Auger         start += size;
3859f14fb6c2SEric Auger         remain -= size;
38609a4bb839SPeter Xu     }
38619a4bb839SPeter Xu 
38629a4bb839SPeter Xu     assert(!remain);
3863dd4d607eSPeter Xu 
3864dd4d607eSPeter Xu     trace_vtd_as_unmap_whole(pci_bus_num(as->bus),
3865dd4d607eSPeter Xu                              VTD_PCI_SLOT(as->devfn),
3866dd4d607eSPeter Xu                              VTD_PCI_FUNC(as->devfn),
3867a082739eSPeter Xu                              n->start, total);
3868dd4d607eSPeter Xu 
38699a4bb839SPeter Xu     map.iova = n->start;
3870a082739eSPeter Xu     map.size = total - 1; /* Inclusive */
387169292a8eSEugenio Pérez     iova_tree_remove(as->iova_tree, map);
3872dd4d607eSPeter Xu }
3873dd4d607eSPeter Xu 
3874dd4d607eSPeter Xu static void vtd_address_space_unmap_all(IntelIOMMUState *s)
3875dd4d607eSPeter Xu {
3876dd4d607eSPeter Xu     VTDAddressSpace *vtd_as;
3877dd4d607eSPeter Xu     IOMMUNotifier *n;
3878dd4d607eSPeter Xu 
3879b4a4ba0dSPeter Xu     QLIST_FOREACH(vtd_as, &s->vtd_as_with_notifiers, next) {
3880dd4d607eSPeter Xu         IOMMU_NOTIFIER_FOREACH(n, &vtd_as->iommu) {
3881dd4d607eSPeter Xu             vtd_address_space_unmap(vtd_as, n);
3882dd4d607eSPeter Xu         }
3883dd4d607eSPeter Xu     }
3884dd4d607eSPeter Xu }
3885dd4d607eSPeter Xu 
38862cc9ddccSPeter Xu static void vtd_address_space_refresh_all(IntelIOMMUState *s)
38872cc9ddccSPeter Xu {
38882cc9ddccSPeter Xu     vtd_address_space_unmap_all(s);
38892cc9ddccSPeter Xu     vtd_switch_address_space_all(s);
38902cc9ddccSPeter Xu }
38912cc9ddccSPeter Xu 
38925039caf3SEugenio Pérez static int vtd_replay_hook(IOMMUTLBEvent *event, void *private)
3893f06a696dSPeter Xu {
38945039caf3SEugenio Pérez     memory_region_notify_iommu_one(private, event);
3895f06a696dSPeter Xu     return 0;
3896f06a696dSPeter Xu }
3897f06a696dSPeter Xu 
38983df9d748SAlexey Kardashevskiy static void vtd_iommu_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n)
3899f06a696dSPeter Xu {
39003df9d748SAlexey Kardashevskiy     VTDAddressSpace *vtd_as = container_of(iommu_mr, VTDAddressSpace, iommu);
3901f06a696dSPeter Xu     IntelIOMMUState *s = vtd_as->iommu_state;
3902f06a696dSPeter Xu     uint8_t bus_n = pci_bus_num(vtd_as->bus);
3903f06a696dSPeter Xu     VTDContextEntry ce;
3904e80c1e4cSZhenzhong Duan     DMAMap map = { .iova = 0, .size = HWADDR_MAX };
3905f06a696dSPeter Xu 
3906e80c1e4cSZhenzhong Duan     /* replay is protected by BQL, page walk will re-setup it safely */
3907e80c1e4cSZhenzhong Duan     iova_tree_remove(vtd_as->iova_tree, map);
3908dd4d607eSPeter Xu 
3909dd4d607eSPeter Xu     if (vtd_dev_to_context_entry(s, bus_n, vtd_as->devfn, &ce) == 0) {
3910fb43cf73SLiu, Yi L         trace_vtd_replay_ce_valid(s->root_scalable ? "scalable mode" :
3911fb43cf73SLiu, Yi L                                   "legacy mode",
3912fb43cf73SLiu, Yi L                                   bus_n, PCI_SLOT(vtd_as->devfn),
3913f06a696dSPeter Xu                                   PCI_FUNC(vtd_as->devfn),
39141b2b1237SJason Wang                                   vtd_get_domain_id(s, &ce, vtd_as->pasid),
3915f06a696dSPeter Xu                                   ce.hi, ce.lo);
3916ce735ff0SZhenzhong Duan         if (n->notifier_flags & IOMMU_NOTIFIER_MAP) {
39174f8a62a9SPeter Xu             /* This is required only for MAP typed notifiers */
3918fe215b0cSPeter Xu             vtd_page_walk_info info = {
3919fe215b0cSPeter Xu                 .hook_fn = vtd_replay_hook,
3920fe215b0cSPeter Xu                 .private = (void *)n,
3921fe215b0cSPeter Xu                 .notify_unmap = false,
3922fe215b0cSPeter Xu                 .aw = s->aw_bits,
39232f764fa8SPeter Xu                 .as = vtd_as,
39241b2b1237SJason Wang                 .domain_id = vtd_get_domain_id(s, &ce, vtd_as->pasid),
3925fe215b0cSPeter Xu             };
3926fe215b0cSPeter Xu 
3927b1ab8f9cSPeter Maydell             vtd_page_walk(s, &ce, 0, ~0ULL, &info, vtd_as->pasid);
39284f8a62a9SPeter Xu         }
3929f06a696dSPeter Xu     } else {
3930f06a696dSPeter Xu         trace_vtd_replay_ce_invalid(bus_n, PCI_SLOT(vtd_as->devfn),
3931f06a696dSPeter Xu                                     PCI_FUNC(vtd_as->devfn));
3932f06a696dSPeter Xu     }
3933f06a696dSPeter Xu 
3934f06a696dSPeter Xu     return;
3935f06a696dSPeter Xu }
3936f06a696dSPeter Xu 
39371da12ec4SLe Tan /* Do the initialization. It will also be called when reset, so pay
39381da12ec4SLe Tan  * attention when adding new initialization stuff.
39391da12ec4SLe Tan  */
39401da12ec4SLe Tan static void vtd_init(IntelIOMMUState *s)
39411da12ec4SLe Tan {
3942d54bd7f8SPeter Xu     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
3943d54bd7f8SPeter Xu 
39441da12ec4SLe Tan     memset(s->csr, 0, DMAR_REG_SIZE);
39451da12ec4SLe Tan     memset(s->wmask, 0, DMAR_REG_SIZE);
39461da12ec4SLe Tan     memset(s->w1cmask, 0, DMAR_REG_SIZE);
39471da12ec4SLe Tan     memset(s->womask, 0, DMAR_REG_SIZE);
39481da12ec4SLe Tan 
39491da12ec4SLe Tan     s->root = 0;
3950fb43cf73SLiu, Yi L     s->root_scalable = false;
39511da12ec4SLe Tan     s->dmar_enabled = false;
3952d7bb469aSPeter Xu     s->intr_enabled = false;
39531da12ec4SLe Tan     s->iq_head = 0;
39541da12ec4SLe Tan     s->iq_tail = 0;
39551da12ec4SLe Tan     s->iq = 0;
39561da12ec4SLe Tan     s->iq_size = 0;
39571da12ec4SLe Tan     s->qi_enabled = false;
39581da12ec4SLe Tan     s->iq_last_desc_type = VTD_INV_DESC_NONE;
3959c0c1d351SLiu, Yi L     s->iq_dw = false;
39601da12ec4SLe Tan     s->next_frcd_reg = 0;
396192e5d85eSPrasad Singamsetty     s->cap = VTD_CAP_FRO | VTD_CAP_NFR | VTD_CAP_ND |
396292e5d85eSPrasad Singamsetty              VTD_CAP_MAMV | VTD_CAP_PSI | VTD_CAP_SLLPS |
39638646d9c7SDavid Woodhouse              VTD_CAP_MGAW(s->aw_bits);
3964ccc23bb0SPeter Xu     if (s->dma_drain) {
3965ccc23bb0SPeter Xu         s->cap |= VTD_CAP_DRAIN;
3966ccc23bb0SPeter Xu     }
39678646d9c7SDavid Woodhouse     if (s->dma_translation) {
39688646d9c7SDavid Woodhouse             if (s->aw_bits >= VTD_HOST_AW_39BIT) {
39698646d9c7SDavid Woodhouse                     s->cap |= VTD_CAP_SAGAW_39bit;
39708646d9c7SDavid Woodhouse             }
39718646d9c7SDavid Woodhouse             if (s->aw_bits >= VTD_HOST_AW_48BIT) {
397237f51384SPrasad Singamsetty                     s->cap |= VTD_CAP_SAGAW_48bit;
397337f51384SPrasad Singamsetty             }
39748646d9c7SDavid Woodhouse     }
3975ed7b8fbcSLe Tan     s->ecap = VTD_ECAP_QI | VTD_ECAP_IRO;
39761da12ec4SLe Tan 
397792e5d85eSPrasad Singamsetty     /*
397892e5d85eSPrasad Singamsetty      * Rsvd field masks for spte
397992e5d85eSPrasad Singamsetty      */
3980ce586f3bSQi, Yadong     vtd_spte_rsvd[0] = ~0ULL;
3981e48929c7SQi, Yadong     vtd_spte_rsvd[1] = VTD_SPTE_PAGE_L1_RSVD_MASK(s->aw_bits,
3982e48929c7SQi, Yadong                                                   x86_iommu->dt_supported);
3983ce586f3bSQi, Yadong     vtd_spte_rsvd[2] = VTD_SPTE_PAGE_L2_RSVD_MASK(s->aw_bits);
3984ce586f3bSQi, Yadong     vtd_spte_rsvd[3] = VTD_SPTE_PAGE_L3_RSVD_MASK(s->aw_bits);
3985ce586f3bSQi, Yadong     vtd_spte_rsvd[4] = VTD_SPTE_PAGE_L4_RSVD_MASK(s->aw_bits);
3986ce586f3bSQi, Yadong 
3987e48929c7SQi, Yadong     vtd_spte_rsvd_large[2] = VTD_SPTE_LPAGE_L2_RSVD_MASK(s->aw_bits,
3988e48929c7SQi, Yadong                                                          x86_iommu->dt_supported);
3989e48929c7SQi, Yadong     vtd_spte_rsvd_large[3] = VTD_SPTE_LPAGE_L3_RSVD_MASK(s->aw_bits,
3990e48929c7SQi, Yadong                                                          x86_iommu->dt_supported);
399192e5d85eSPrasad Singamsetty 
3992b8ffd7d6SJason Wang     if (s->scalable_mode || s->snoop_control) {
39930192d667SJason Wang         vtd_spte_rsvd[1] &= ~VTD_SPTE_SNP;
39940192d667SJason Wang         vtd_spte_rsvd_large[2] &= ~VTD_SPTE_SNP;
39950192d667SJason Wang         vtd_spte_rsvd_large[3] &= ~VTD_SPTE_SNP;
39960192d667SJason Wang     }
39970192d667SJason Wang 
3998a924b3d8SPeter Xu     if (x86_iommu_ir_supported(x86_iommu)) {
3999e6b6af05SRadim Krčmář         s->ecap |= VTD_ECAP_IR | VTD_ECAP_MHMV;
4000e6b6af05SRadim Krčmář         if (s->intr_eim == ON_OFF_AUTO_ON) {
4001e6b6af05SRadim Krčmář             s->ecap |= VTD_ECAP_EIM;
4002e6b6af05SRadim Krčmář         }
4003e6b6af05SRadim Krčmář         assert(s->intr_eim != ON_OFF_AUTO_AUTO);
4004d54bd7f8SPeter Xu     }
4005d54bd7f8SPeter Xu 
4006554f5e16SJason Wang     if (x86_iommu->dt_supported) {
4007554f5e16SJason Wang         s->ecap |= VTD_ECAP_DT;
4008554f5e16SJason Wang     }
4009554f5e16SJason Wang 
4010dbaabb25SPeter Xu     if (x86_iommu->pt_supported) {
4011dbaabb25SPeter Xu         s->ecap |= VTD_ECAP_PT;
4012dbaabb25SPeter Xu     }
4013dbaabb25SPeter Xu 
40143b40f0e5SAviv Ben-David     if (s->caching_mode) {
40153b40f0e5SAviv Ben-David         s->cap |= VTD_CAP_CM;
40163b40f0e5SAviv Ben-David     }
40173b40f0e5SAviv Ben-David 
40184a4f219eSYi Sun     /* TODO: read cap/ecap from host to decide which cap to be exposed. */
40194a4f219eSYi Sun     if (s->scalable_mode) {
40204a4f219eSYi Sun         s->ecap |= VTD_ECAP_SMTS | VTD_ECAP_SRS | VTD_ECAP_SLTS;
40214a4f219eSYi Sun     }
40224a4f219eSYi Sun 
4023b8ffd7d6SJason Wang     if (s->snoop_control) {
4024b8ffd7d6SJason Wang         s->ecap |= VTD_ECAP_SC;
4025b8ffd7d6SJason Wang     }
4026b8ffd7d6SJason Wang 
40271b2b1237SJason Wang     if (s->pasid) {
40281b2b1237SJason Wang         s->ecap |= VTD_ECAP_PASID;
40291b2b1237SJason Wang     }
40301b2b1237SJason Wang 
403106aba4caSPeter Xu     vtd_reset_caches(s);
4032d92fa2dcSLe Tan 
40331da12ec4SLe Tan     /* Define registers with default values and bit semantics */
40341da12ec4SLe Tan     vtd_define_long(s, DMAR_VER_REG, 0x10UL, 0, 0);
40351da12ec4SLe Tan     vtd_define_quad(s, DMAR_CAP_REG, s->cap, 0, 0);
40361da12ec4SLe Tan     vtd_define_quad(s, DMAR_ECAP_REG, s->ecap, 0, 0);
40371da12ec4SLe Tan     vtd_define_long(s, DMAR_GCMD_REG, 0, 0xff800000UL, 0);
40381da12ec4SLe Tan     vtd_define_long_wo(s, DMAR_GCMD_REG, 0xff800000UL);
40391da12ec4SLe Tan     vtd_define_long(s, DMAR_GSTS_REG, 0, 0, 0);
4040fb43cf73SLiu, Yi L     vtd_define_quad(s, DMAR_RTADDR_REG, 0, 0xfffffffffffffc00ULL, 0);
40411da12ec4SLe Tan     vtd_define_quad(s, DMAR_CCMD_REG, 0, 0xe0000003ffffffffULL, 0);
40421da12ec4SLe Tan     vtd_define_quad_wo(s, DMAR_CCMD_REG, 0x3ffff0000ULL);
40431da12ec4SLe Tan 
40441da12ec4SLe Tan     /* Advanced Fault Logging not supported */
40451da12ec4SLe Tan     vtd_define_long(s, DMAR_FSTS_REG, 0, 0, 0x11UL);
40461da12ec4SLe Tan     vtd_define_long(s, DMAR_FECTL_REG, 0x80000000UL, 0x80000000UL, 0);
40471da12ec4SLe Tan     vtd_define_long(s, DMAR_FEDATA_REG, 0, 0x0000ffffUL, 0);
40481da12ec4SLe Tan     vtd_define_long(s, DMAR_FEADDR_REG, 0, 0xfffffffcUL, 0);
40491da12ec4SLe Tan 
40501da12ec4SLe Tan     /* Treated as RsvdZ when EIM in ECAP_REG is not supported
40511da12ec4SLe Tan      * vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0xffffffffUL, 0);
40521da12ec4SLe Tan      */
40531da12ec4SLe Tan     vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0, 0);
40541da12ec4SLe Tan 
40551da12ec4SLe Tan     /* Treated as RO for implementations that PLMR and PHMR fields reported
40561da12ec4SLe Tan      * as Clear in the CAP_REG.
40571da12ec4SLe Tan      * vtd_define_long(s, DMAR_PMEN_REG, 0, 0x80000000UL, 0);
40581da12ec4SLe Tan      */
40591da12ec4SLe Tan     vtd_define_long(s, DMAR_PMEN_REG, 0, 0, 0);
40601da12ec4SLe Tan 
4061ed7b8fbcSLe Tan     vtd_define_quad(s, DMAR_IQH_REG, 0, 0, 0);
4062ed7b8fbcSLe Tan     vtd_define_quad(s, DMAR_IQT_REG, 0, 0x7fff0ULL, 0);
4063c0c1d351SLiu, Yi L     vtd_define_quad(s, DMAR_IQA_REG, 0, 0xfffffffffffff807ULL, 0);
4064ed7b8fbcSLe Tan     vtd_define_long(s, DMAR_ICS_REG, 0, 0, 0x1UL);
4065ed7b8fbcSLe Tan     vtd_define_long(s, DMAR_IECTL_REG, 0x80000000UL, 0x80000000UL, 0);
4066ed7b8fbcSLe Tan     vtd_define_long(s, DMAR_IEDATA_REG, 0, 0xffffffffUL, 0);
4067ed7b8fbcSLe Tan     vtd_define_long(s, DMAR_IEADDR_REG, 0, 0xfffffffcUL, 0);
4068ed7b8fbcSLe Tan     /* Treadted as RsvdZ when EIM in ECAP_REG is not supported */
4069ed7b8fbcSLe Tan     vtd_define_long(s, DMAR_IEUADDR_REG, 0, 0, 0);
4070ed7b8fbcSLe Tan 
40711da12ec4SLe Tan     /* IOTLB registers */
40721da12ec4SLe Tan     vtd_define_quad(s, DMAR_IOTLB_REG, 0, 0Xb003ffff00000000ULL, 0);
40731da12ec4SLe Tan     vtd_define_quad(s, DMAR_IVA_REG, 0, 0xfffffffffffff07fULL, 0);
40741da12ec4SLe Tan     vtd_define_quad_wo(s, DMAR_IVA_REG, 0xfffffffffffff07fULL);
40751da12ec4SLe Tan 
40761da12ec4SLe Tan     /* Fault Recording Registers, 128-bit */
40771da12ec4SLe Tan     vtd_define_quad(s, DMAR_FRCD_REG_0_0, 0, 0, 0);
40781da12ec4SLe Tan     vtd_define_quad(s, DMAR_FRCD_REG_0_2, 0, 0, 0x8000000000000000ULL);
4079a5861439SPeter Xu 
4080a5861439SPeter Xu     /*
408128589311SJan Kiszka      * Interrupt remapping registers.
4082a5861439SPeter Xu      */
408328589311SJan Kiszka     vtd_define_quad(s, DMAR_IRTA_REG, 0, 0xfffffffffffff80fULL, 0);
40841da12ec4SLe Tan }
40851da12ec4SLe Tan 
40861da12ec4SLe Tan /* Should not reset address_spaces when reset because devices will still use
40871da12ec4SLe Tan  * the address space they got at first (won't ask the bus again).
40881da12ec4SLe Tan  */
40891da12ec4SLe Tan static void vtd_reset(DeviceState *dev)
40901da12ec4SLe Tan {
40911da12ec4SLe Tan     IntelIOMMUState *s = INTEL_IOMMU_DEVICE(dev);
40921da12ec4SLe Tan 
40931da12ec4SLe Tan     vtd_init(s);
40942cc9ddccSPeter Xu     vtd_address_space_refresh_all(s);
40951da12ec4SLe Tan }
40961da12ec4SLe Tan 
4097621d983aSMarcel Apfelbaum static AddressSpace *vtd_host_dma_iommu(PCIBus *bus, void *opaque, int devfn)
4098621d983aSMarcel Apfelbaum {
4099621d983aSMarcel Apfelbaum     IntelIOMMUState *s = opaque;
4100621d983aSMarcel Apfelbaum     VTDAddressSpace *vtd_as;
4101621d983aSMarcel Apfelbaum 
4102bf33cc75SPeter Xu     assert(0 <= devfn && devfn < PCI_DEVFN_MAX);
4103621d983aSMarcel Apfelbaum 
41041b2b1237SJason Wang     vtd_as = vtd_find_add_as(s, bus, devfn, PCI_NO_PASID);
4105621d983aSMarcel Apfelbaum     return &vtd_as->as;
4106621d983aSMarcel Apfelbaum }
4107621d983aSMarcel Apfelbaum 
4108ba7d12ebSYi Liu static PCIIOMMUOps vtd_iommu_ops = {
4109ba7d12ebSYi Liu     .get_address_space = vtd_host_dma_iommu,
4110ba7d12ebSYi Liu };
4111ba7d12ebSYi Liu 
4112e6b6af05SRadim Krčmář static bool vtd_decide_config(IntelIOMMUState *s, Error **errp)
41136333e93cSRadim Krčmář {
4114e6b6af05SRadim Krčmář     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
4115e6b6af05SRadim Krčmář 
4116a924b3d8SPeter Xu     if (s->intr_eim == ON_OFF_AUTO_ON && !x86_iommu_ir_supported(x86_iommu)) {
4117e6b6af05SRadim Krčmář         error_setg(errp, "eim=on cannot be selected without intremap=on");
4118e6b6af05SRadim Krčmář         return false;
4119e6b6af05SRadim Krčmář     }
4120e6b6af05SRadim Krčmář 
4121e6b6af05SRadim Krčmář     if (s->intr_eim == ON_OFF_AUTO_AUTO) {
4122fb506e70SRadim Krčmář         s->intr_eim = (kvm_irqchip_in_kernel() || s->buggy_eim)
4123a924b3d8SPeter Xu                       && x86_iommu_ir_supported(x86_iommu) ?
4124e6b6af05SRadim Krčmář                                               ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
4125e6b6af05SRadim Krčmář     }
4126fb506e70SRadim Krčmář     if (s->intr_eim == ON_OFF_AUTO_ON && !s->buggy_eim) {
41272cf16205SBui Quang Minh         if (kvm_irqchip_is_split() && !kvm_enable_x2apic()) {
412820ca4742SPeter Xu             error_setg(errp, "eim=on requires support on the KVM side"
412920ca4742SPeter Xu                              "(X2APIC_API, first shipped in v4.7)");
413020ca4742SPeter Xu             return false;
413120ca4742SPeter Xu         }
4132fb506e70SRadim Krčmář     }
4133e6b6af05SRadim Krčmář 
413437f51384SPrasad Singamsetty     /* Currently only address widths supported are 39 and 48 bits */
413537f51384SPrasad Singamsetty     if ((s->aw_bits != VTD_HOST_AW_39BIT) &&
413637f51384SPrasad Singamsetty         (s->aw_bits != VTD_HOST_AW_48BIT)) {
41372a345149SMenno Lageman         error_setg(errp, "Supported values for aw-bits are: %d, %d",
413837f51384SPrasad Singamsetty                    VTD_HOST_AW_39BIT, VTD_HOST_AW_48BIT);
413937f51384SPrasad Singamsetty         return false;
414037f51384SPrasad Singamsetty     }
414137f51384SPrasad Singamsetty 
41424a4f219eSYi Sun     if (s->scalable_mode && !s->dma_drain) {
41434a4f219eSYi Sun         error_setg(errp, "Need to set dma_drain for scalable mode");
41444a4f219eSYi Sun         return false;
41454a4f219eSYi Sun     }
41464a4f219eSYi Sun 
41471b2b1237SJason Wang     if (s->pasid && !s->scalable_mode) {
41481b2b1237SJason Wang         error_setg(errp, "Need to set scalable mode for PASID");
41491b2b1237SJason Wang         return false;
41501b2b1237SJason Wang     }
41511b2b1237SJason Wang 
41526333e93cSRadim Krčmář     return true;
41536333e93cSRadim Krčmář }
41546333e93cSRadim Krčmář 
415528cf553aSPeter Xu static int vtd_machine_done_notify_one(Object *child, void *unused)
415628cf553aSPeter Xu {
415728cf553aSPeter Xu     IntelIOMMUState *iommu = INTEL_IOMMU_DEVICE(x86_iommu_get_default());
415828cf553aSPeter Xu 
415928cf553aSPeter Xu     /*
416028cf553aSPeter Xu      * We hard-coded here because vfio-pci is the only special case
416128cf553aSPeter Xu      * here.  Let's be more elegant in the future when we can, but so
416228cf553aSPeter Xu      * far there seems to be no better way.
416328cf553aSPeter Xu      */
416428cf553aSPeter Xu     if (object_dynamic_cast(child, "vfio-pci") && !iommu->caching_mode) {
416528cf553aSPeter Xu         vtd_panic_require_caching_mode();
416628cf553aSPeter Xu     }
416728cf553aSPeter Xu 
416828cf553aSPeter Xu     return 0;
416928cf553aSPeter Xu }
417028cf553aSPeter Xu 
417128cf553aSPeter Xu static void vtd_machine_done_hook(Notifier *notifier, void *unused)
417228cf553aSPeter Xu {
417328cf553aSPeter Xu     object_child_foreach_recursive(object_get_root(),
417428cf553aSPeter Xu                                    vtd_machine_done_notify_one, NULL);
417528cf553aSPeter Xu }
417628cf553aSPeter Xu 
417728cf553aSPeter Xu static Notifier vtd_machine_done_notify = {
417828cf553aSPeter Xu     .notify = vtd_machine_done_hook,
417928cf553aSPeter Xu };
418028cf553aSPeter Xu 
41811da12ec4SLe Tan static void vtd_realize(DeviceState *dev, Error **errp)
41821da12ec4SLe Tan {
4183ef0e8fc7SEduardo Habkost     MachineState *ms = MACHINE(qdev_get_machine());
418429396ed9SMohammed Gamal     PCMachineState *pcms = PC_MACHINE(ms);
4185f0bb276bSPaolo Bonzini     X86MachineState *x86ms = X86_MACHINE(ms);
4186*b54a9d46SBernhard Beschow     PCIBus *bus = pcms->pcibus;
41871da12ec4SLe Tan     IntelIOMMUState *s = INTEL_IOMMU_DEVICE(dev);
41881b2b1237SJason Wang     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
41891b2b1237SJason Wang 
41901b2b1237SJason Wang     if (s->pasid && x86_iommu->dt_supported) {
41911b2b1237SJason Wang         /*
41921b2b1237SJason Wang          * PASID-based-Device-TLB Invalidate Descriptor is not
41931b2b1237SJason Wang          * implemented and it requires support from vhost layer which
41941b2b1237SJason Wang          * needs to be implemented in the future.
41951b2b1237SJason Wang          */
41961b2b1237SJason Wang         error_setg(errp, "PASID based device IOTLB is not supported");
41971b2b1237SJason Wang         return;
41981b2b1237SJason Wang     }
41996333e93cSRadim Krčmář 
4200e6b6af05SRadim Krčmář     if (!vtd_decide_config(s, errp)) {
42016333e93cSRadim Krčmář         return;
42026333e93cSRadim Krčmář     }
42036333e93cSRadim Krčmář 
4204b4a4ba0dSPeter Xu     QLIST_INIT(&s->vtd_as_with_notifiers);
42051d9efa73SPeter Xu     qemu_mutex_init(&s->iommu_lock);
42061da12ec4SLe Tan     memory_region_init_io(&s->csrmem, OBJECT(s), &vtd_mem_ops, s,
42071da12ec4SLe Tan                           "intel_iommu", DMAR_REG_SIZE);
4208a540087fSPhilippe Mathieu-Daudé     memory_region_add_subregion(get_system_memory(),
4209a540087fSPhilippe Mathieu-Daudé                                 Q35_HOST_BRIDGE_IOMMU_ADDR, &s->csrmem);
42104b519ef1SPeter Xu 
42114b519ef1SPeter Xu     /* Create the shared memory regions by all devices */
42124b519ef1SPeter Xu     memory_region_init(&s->mr_nodmar, OBJECT(s), "vtd-nodmar",
42134b519ef1SPeter Xu                        UINT64_MAX);
42144b519ef1SPeter Xu     memory_region_init_io(&s->mr_ir, OBJECT(s), &vtd_mem_ir_ops,
42154b519ef1SPeter Xu                           s, "vtd-ir", VTD_INTERRUPT_ADDR_SIZE);
42164b519ef1SPeter Xu     memory_region_init_alias(&s->mr_sys_alias, OBJECT(s),
42174b519ef1SPeter Xu                              "vtd-sys-alias", get_system_memory(), 0,
42184b519ef1SPeter Xu                              memory_region_size(get_system_memory()));
42194b519ef1SPeter Xu     memory_region_add_subregion_overlap(&s->mr_nodmar, 0,
42204b519ef1SPeter Xu                                         &s->mr_sys_alias, 0);
42214b519ef1SPeter Xu     memory_region_add_subregion_overlap(&s->mr_nodmar,
42224b519ef1SPeter Xu                                         VTD_INTERRUPT_ADDR_FIRST,
42234b519ef1SPeter Xu                                         &s->mr_ir, 1);
4224b5a280c0SLe Tan     /* No corresponding destroy */
42251b2b1237SJason Wang     s->iotlb = g_hash_table_new_full(vtd_iotlb_hash, vtd_iotlb_equal,
4226b5a280c0SLe Tan                                      g_free, g_free);
4227da8d439cSJason Wang     s->vtd_address_spaces = g_hash_table_new_full(vtd_as_hash, vtd_as_equal,
42287df953bdSKnut Omang                                       g_free, g_free);
42291da12ec4SLe Tan     vtd_init(s);
4230ba7d12ebSYi Liu     pci_setup_iommu(bus, &vtd_iommu_ops, dev);
4231cb135f59SPeter Xu     /* Pseudo address space under root PCI bus. */
4232f0bb276bSPaolo Bonzini     x86ms->ioapic_as = vtd_host_dma_iommu(bus, s, Q35_PSEUDO_DEVFN_IOAPIC);
423328cf553aSPeter Xu     qemu_add_machine_init_done_notifier(&vtd_machine_done_notify);
42341da12ec4SLe Tan }
42351da12ec4SLe Tan 
42361da12ec4SLe Tan static void vtd_class_init(ObjectClass *klass, void *data)
42371da12ec4SLe Tan {
42381da12ec4SLe Tan     DeviceClass *dc = DEVICE_CLASS(klass);
423930c60f77SEduardo Habkost     X86IOMMUClass *x86_class = X86_IOMMU_DEVICE_CLASS(klass);
42401da12ec4SLe Tan 
42411da12ec4SLe Tan     dc->reset = vtd_reset;
42421da12ec4SLe Tan     dc->vmsd = &vtd_vmstate;
42434f67d30bSMarc-André Lureau     device_class_set_props(dc, vtd_properties);
4244621d983aSMarcel Apfelbaum     dc->hotpluggable = false;
42451c7955c4SPeter Xu     x86_class->realize = vtd_realize;
42468b5ed7dfSPeter Xu     x86_class->int_remap = vtd_int_remap;
42478ab5700cSEduardo Habkost     /* Supported by the pc-q35-* machine types */
4248e4f4fb1eSEduardo Habkost     dc->user_creatable = true;
42491ec202c9SErnest Esene     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
42501ec202c9SErnest Esene     dc->desc = "Intel IOMMU (VT-d) DMA Remapping device";
42511da12ec4SLe Tan }
42521da12ec4SLe Tan 
42531da12ec4SLe Tan static const TypeInfo vtd_info = {
42541da12ec4SLe Tan     .name          = TYPE_INTEL_IOMMU_DEVICE,
42551c7955c4SPeter Xu     .parent        = TYPE_X86_IOMMU_DEVICE,
42561da12ec4SLe Tan     .instance_size = sizeof(IntelIOMMUState),
42571da12ec4SLe Tan     .class_init    = vtd_class_init,
42581da12ec4SLe Tan };
42591da12ec4SLe Tan 
42601221a474SAlexey Kardashevskiy static void vtd_iommu_memory_region_class_init(ObjectClass *klass,
42611221a474SAlexey Kardashevskiy                                                      void *data)
42621221a474SAlexey Kardashevskiy {
42631221a474SAlexey Kardashevskiy     IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_CLASS(klass);
42641221a474SAlexey Kardashevskiy 
42651221a474SAlexey Kardashevskiy     imrc->translate = vtd_iommu_translate;
42661221a474SAlexey Kardashevskiy     imrc->notify_flag_changed = vtd_iommu_notify_flag_changed;
42671221a474SAlexey Kardashevskiy     imrc->replay = vtd_iommu_replay;
42681221a474SAlexey Kardashevskiy }
42691221a474SAlexey Kardashevskiy 
42701221a474SAlexey Kardashevskiy static const TypeInfo vtd_iommu_memory_region_info = {
42711221a474SAlexey Kardashevskiy     .parent = TYPE_IOMMU_MEMORY_REGION,
42721221a474SAlexey Kardashevskiy     .name = TYPE_INTEL_IOMMU_MEMORY_REGION,
42731221a474SAlexey Kardashevskiy     .class_init = vtd_iommu_memory_region_class_init,
42741221a474SAlexey Kardashevskiy };
42751221a474SAlexey Kardashevskiy 
42761da12ec4SLe Tan static void vtd_register_types(void)
42771da12ec4SLe Tan {
42781da12ec4SLe Tan     type_register_static(&vtd_info);
42791221a474SAlexey Kardashevskiy     type_register_static(&vtd_iommu_memory_region_info);
42801da12ec4SLe Tan }
42811da12ec4SLe Tan 
42821da12ec4SLe Tan type_init(vtd_register_types)
4283