xref: /openbmc/qemu/hw/i386/intel_iommu.c (revision 9eb9350c0e519be97716f6b27f664bd0a3c41a36)
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 
64a20910caSYi Liu /* bus/devfn is PCI device's real BDF not the aliased one */
65a20910caSYi Liu struct vtd_hiod_key {
66a20910caSYi Liu     PCIBus *bus;
67a20910caSYi Liu     uint8_t devfn;
68a20910caSYi Liu };
69a20910caSYi Liu 
701b2b1237SJason Wang struct vtd_iotlb_key {
711b2b1237SJason Wang     uint64_t gfn;
721b2b1237SJason Wang     uint32_t pasid;
731b2b1237SJason Wang     uint16_t sid;
74ec1a78ceSJason Wang     uint8_t level;
75da8d439cSJason Wang };
76da8d439cSJason Wang 
772cc9ddccSPeter Xu static void vtd_address_space_refresh_all(IntelIOMMUState *s);
78c28b535dSPeter Xu static void vtd_address_space_unmap(VTDAddressSpace *as, IOMMUNotifier *n);
792cc9ddccSPeter Xu 
vtd_panic_require_caching_mode(void)8028cf553aSPeter Xu static void vtd_panic_require_caching_mode(void)
8128cf553aSPeter Xu {
8228cf553aSPeter Xu     error_report("We need to set caching-mode=on for intel-iommu to enable "
8328cf553aSPeter Xu                  "device assignment with IOMMU protection.");
8428cf553aSPeter Xu     exit(1);
8528cf553aSPeter Xu }
8628cf553aSPeter Xu 
vtd_define_quad(IntelIOMMUState * s,hwaddr addr,uint64_t val,uint64_t wmask,uint64_t w1cmask)871da12ec4SLe Tan static void vtd_define_quad(IntelIOMMUState *s, hwaddr addr, uint64_t val,
881da12ec4SLe Tan                             uint64_t wmask, uint64_t w1cmask)
891da12ec4SLe Tan {
901da12ec4SLe Tan     stq_le_p(&s->csr[addr], val);
911da12ec4SLe Tan     stq_le_p(&s->wmask[addr], wmask);
921da12ec4SLe Tan     stq_le_p(&s->w1cmask[addr], w1cmask);
931da12ec4SLe Tan }
941da12ec4SLe Tan 
vtd_define_quad_wo(IntelIOMMUState * s,hwaddr addr,uint64_t mask)951da12ec4SLe Tan static void vtd_define_quad_wo(IntelIOMMUState *s, hwaddr addr, uint64_t mask)
961da12ec4SLe Tan {
971da12ec4SLe Tan     stq_le_p(&s->womask[addr], mask);
981da12ec4SLe Tan }
991da12ec4SLe Tan 
vtd_define_long(IntelIOMMUState * s,hwaddr addr,uint32_t val,uint32_t wmask,uint32_t w1cmask)1001da12ec4SLe Tan static void vtd_define_long(IntelIOMMUState *s, hwaddr addr, uint32_t val,
1011da12ec4SLe Tan                             uint32_t wmask, uint32_t w1cmask)
1021da12ec4SLe Tan {
1031da12ec4SLe Tan     stl_le_p(&s->csr[addr], val);
1041da12ec4SLe Tan     stl_le_p(&s->wmask[addr], wmask);
1051da12ec4SLe Tan     stl_le_p(&s->w1cmask[addr], w1cmask);
1061da12ec4SLe Tan }
1071da12ec4SLe Tan 
vtd_define_long_wo(IntelIOMMUState * s,hwaddr addr,uint32_t mask)1081da12ec4SLe Tan static void vtd_define_long_wo(IntelIOMMUState *s, hwaddr addr, uint32_t mask)
1091da12ec4SLe Tan {
1101da12ec4SLe Tan     stl_le_p(&s->womask[addr], mask);
1111da12ec4SLe Tan }
1121da12ec4SLe Tan 
1131da12ec4SLe Tan /* "External" get/set operations */
vtd_set_quad(IntelIOMMUState * s,hwaddr addr,uint64_t val)1141da12ec4SLe Tan static void vtd_set_quad(IntelIOMMUState *s, hwaddr addr, uint64_t val)
1151da12ec4SLe Tan {
1161da12ec4SLe Tan     uint64_t oldval = ldq_le_p(&s->csr[addr]);
1171da12ec4SLe Tan     uint64_t wmask = ldq_le_p(&s->wmask[addr]);
1181da12ec4SLe Tan     uint64_t w1cmask = ldq_le_p(&s->w1cmask[addr]);
1191da12ec4SLe Tan     stq_le_p(&s->csr[addr],
1201da12ec4SLe Tan              ((oldval & ~wmask) | (val & wmask)) & ~(w1cmask & val));
1211da12ec4SLe Tan }
1221da12ec4SLe Tan 
vtd_set_long(IntelIOMMUState * s,hwaddr addr,uint32_t val)1231da12ec4SLe Tan static void vtd_set_long(IntelIOMMUState *s, hwaddr addr, uint32_t val)
1241da12ec4SLe Tan {
1251da12ec4SLe Tan     uint32_t oldval = ldl_le_p(&s->csr[addr]);
1261da12ec4SLe Tan     uint32_t wmask = ldl_le_p(&s->wmask[addr]);
1271da12ec4SLe Tan     uint32_t w1cmask = ldl_le_p(&s->w1cmask[addr]);
1281da12ec4SLe Tan     stl_le_p(&s->csr[addr],
1291da12ec4SLe Tan              ((oldval & ~wmask) | (val & wmask)) & ~(w1cmask & val));
1301da12ec4SLe Tan }
1311da12ec4SLe Tan 
vtd_get_quad(IntelIOMMUState * s,hwaddr addr)1321da12ec4SLe Tan static uint64_t vtd_get_quad(IntelIOMMUState *s, hwaddr addr)
1331da12ec4SLe Tan {
1341da12ec4SLe Tan     uint64_t val = ldq_le_p(&s->csr[addr]);
1351da12ec4SLe Tan     uint64_t womask = ldq_le_p(&s->womask[addr]);
1361da12ec4SLe Tan     return val & ~womask;
1371da12ec4SLe Tan }
1381da12ec4SLe Tan 
vtd_get_long(IntelIOMMUState * s,hwaddr addr)1391da12ec4SLe Tan static uint32_t vtd_get_long(IntelIOMMUState *s, hwaddr addr)
1401da12ec4SLe Tan {
1411da12ec4SLe Tan     uint32_t val = ldl_le_p(&s->csr[addr]);
1421da12ec4SLe Tan     uint32_t womask = ldl_le_p(&s->womask[addr]);
1431da12ec4SLe Tan     return val & ~womask;
1441da12ec4SLe Tan }
1451da12ec4SLe Tan 
1461da12ec4SLe Tan /* "Internal" get/set operations */
vtd_get_quad_raw(IntelIOMMUState * s,hwaddr addr)1471da12ec4SLe Tan static uint64_t vtd_get_quad_raw(IntelIOMMUState *s, hwaddr addr)
1481da12ec4SLe Tan {
1491da12ec4SLe Tan     return ldq_le_p(&s->csr[addr]);
1501da12ec4SLe Tan }
1511da12ec4SLe Tan 
vtd_get_long_raw(IntelIOMMUState * s,hwaddr addr)1521da12ec4SLe Tan static uint32_t vtd_get_long_raw(IntelIOMMUState *s, hwaddr addr)
1531da12ec4SLe Tan {
1541da12ec4SLe Tan     return ldl_le_p(&s->csr[addr]);
1551da12ec4SLe Tan }
1561da12ec4SLe Tan 
vtd_set_quad_raw(IntelIOMMUState * s,hwaddr addr,uint64_t val)1571da12ec4SLe Tan static void vtd_set_quad_raw(IntelIOMMUState *s, hwaddr addr, uint64_t val)
1581da12ec4SLe Tan {
1591da12ec4SLe Tan     stq_le_p(&s->csr[addr], val);
1601da12ec4SLe Tan }
1611da12ec4SLe Tan 
vtd_set_clear_mask_long(IntelIOMMUState * s,hwaddr addr,uint32_t clear,uint32_t mask)1621da12ec4SLe Tan static uint32_t vtd_set_clear_mask_long(IntelIOMMUState *s, hwaddr addr,
1631da12ec4SLe Tan                                         uint32_t clear, uint32_t mask)
1641da12ec4SLe Tan {
1651da12ec4SLe Tan     uint32_t new_val = (ldl_le_p(&s->csr[addr]) & ~clear) | mask;
1661da12ec4SLe Tan     stl_le_p(&s->csr[addr], new_val);
1671da12ec4SLe Tan     return new_val;
1681da12ec4SLe Tan }
1691da12ec4SLe Tan 
vtd_set_clear_mask_quad(IntelIOMMUState * s,hwaddr addr,uint64_t clear,uint64_t mask)1701da12ec4SLe Tan static uint64_t vtd_set_clear_mask_quad(IntelIOMMUState *s, hwaddr addr,
1711da12ec4SLe Tan                                         uint64_t clear, uint64_t mask)
1721da12ec4SLe Tan {
1731da12ec4SLe Tan     uint64_t new_val = (ldq_le_p(&s->csr[addr]) & ~clear) | mask;
1741da12ec4SLe Tan     stq_le_p(&s->csr[addr], new_val);
1751da12ec4SLe Tan     return new_val;
1761da12ec4SLe Tan }
1771da12ec4SLe Tan 
vtd_iommu_lock(IntelIOMMUState * s)1781d9efa73SPeter Xu static inline void vtd_iommu_lock(IntelIOMMUState *s)
1791d9efa73SPeter Xu {
1801d9efa73SPeter Xu     qemu_mutex_lock(&s->iommu_lock);
1811d9efa73SPeter Xu }
1821d9efa73SPeter Xu 
vtd_iommu_unlock(IntelIOMMUState * s)1831d9efa73SPeter Xu static inline void vtd_iommu_unlock(IntelIOMMUState *s)
1841d9efa73SPeter Xu {
1851d9efa73SPeter Xu     qemu_mutex_unlock(&s->iommu_lock);
1861d9efa73SPeter Xu }
1871d9efa73SPeter Xu 
vtd_update_scalable_state(IntelIOMMUState * s)1882811af3bSPeter Xu static void vtd_update_scalable_state(IntelIOMMUState *s)
1892811af3bSPeter Xu {
1902811af3bSPeter Xu     uint64_t val = vtd_get_quad_raw(s, DMAR_RTADDR_REG);
1912811af3bSPeter Xu 
1922811af3bSPeter Xu     if (s->scalable_mode) {
1932811af3bSPeter Xu         s->root_scalable = val & VTD_RTADDR_SMT;
1942811af3bSPeter Xu     }
1952811af3bSPeter Xu }
1962811af3bSPeter Xu 
vtd_update_iq_dw(IntelIOMMUState * s)197147a372eSJason Wang static void vtd_update_iq_dw(IntelIOMMUState *s)
198147a372eSJason Wang {
199147a372eSJason Wang     uint64_t val = vtd_get_quad_raw(s, DMAR_IQA_REG);
200147a372eSJason Wang 
201147a372eSJason Wang     if (s->ecap & VTD_ECAP_SMTS &&
202147a372eSJason Wang         val & VTD_IQA_DW_MASK) {
203147a372eSJason Wang         s->iq_dw = true;
204147a372eSJason Wang     } else {
205147a372eSJason Wang         s->iq_dw = false;
206147a372eSJason Wang     }
207147a372eSJason Wang }
208147a372eSJason Wang 
2094f8a62a9SPeter Xu /* Whether the address space needs to notify new mappings */
vtd_as_has_map_notifier(VTDAddressSpace * as)2104f8a62a9SPeter Xu static inline gboolean vtd_as_has_map_notifier(VTDAddressSpace *as)
2114f8a62a9SPeter Xu {
2124f8a62a9SPeter Xu     return as->notifier_flags & IOMMU_NOTIFIER_MAP;
2134f8a62a9SPeter Xu }
2144f8a62a9SPeter Xu 
215b5a280c0SLe Tan /* GHashTable functions */
vtd_iotlb_equal(gconstpointer v1,gconstpointer v2)2161b2b1237SJason Wang static gboolean vtd_iotlb_equal(gconstpointer v1, gconstpointer v2)
217b5a280c0SLe Tan {
2181b2b1237SJason Wang     const struct vtd_iotlb_key *key1 = v1;
2191b2b1237SJason Wang     const struct vtd_iotlb_key *key2 = v2;
2201b2b1237SJason Wang 
2211b2b1237SJason Wang     return key1->sid == key2->sid &&
2221b2b1237SJason Wang            key1->pasid == key2->pasid &&
2231b2b1237SJason Wang            key1->level == key2->level &&
2241b2b1237SJason Wang            key1->gfn == key2->gfn;
225b5a280c0SLe Tan }
226b5a280c0SLe Tan 
vtd_iotlb_hash(gconstpointer v)2271b2b1237SJason Wang static guint vtd_iotlb_hash(gconstpointer v)
228b5a280c0SLe Tan {
2291b2b1237SJason Wang     const struct vtd_iotlb_key *key = v;
230ec1a78ceSJason Wang     uint64_t hash64 = key->gfn | ((uint64_t)(key->sid) << VTD_IOTLB_SID_SHIFT) |
231ec1a78ceSJason Wang         (uint64_t)(key->level - 1) << VTD_IOTLB_LVL_SHIFT |
232ec1a78ceSJason Wang         (uint64_t)(key->pasid) << VTD_IOTLB_PASID_SHIFT;
2331b2b1237SJason Wang 
234ec1a78ceSJason Wang     return (guint)((hash64 >> 32) ^ (hash64 & 0xffffffffU));
235b5a280c0SLe Tan }
236b5a280c0SLe Tan 
vtd_as_equal(gconstpointer v1,gconstpointer v2)237da8d439cSJason Wang static gboolean vtd_as_equal(gconstpointer v1, gconstpointer v2)
238da8d439cSJason Wang {
239da8d439cSJason Wang     const struct vtd_as_key *key1 = v1;
240da8d439cSJason Wang     const struct vtd_as_key *key2 = v2;
241da8d439cSJason Wang 
2421b2b1237SJason Wang     return (key1->bus == key2->bus) && (key1->devfn == key2->devfn) &&
2431b2b1237SJason Wang            (key1->pasid == key2->pasid);
244da8d439cSJason Wang }
245da8d439cSJason Wang 
246da8d439cSJason Wang /*
247da8d439cSJason Wang  * Note that we use pointer to PCIBus as the key, so hashing/shifting
248da8d439cSJason Wang  * based on the pointer value is intended. Note that we deal with
249da8d439cSJason Wang  * collisions through vtd_as_equal().
250da8d439cSJason Wang  */
vtd_as_hash(gconstpointer v)251da8d439cSJason Wang static guint vtd_as_hash(gconstpointer v)
252da8d439cSJason Wang {
253da8d439cSJason Wang     const struct vtd_as_key *key = v;
254da8d439cSJason Wang     guint value = (guint)(uintptr_t)key->bus;
255da8d439cSJason Wang 
256da8d439cSJason Wang     return (guint)(value << 8 | key->devfn);
257da8d439cSJason Wang }
258da8d439cSJason Wang 
259a20910caSYi Liu /* Same implementation as vtd_as_hash() */
vtd_hiod_hash(gconstpointer v)260a20910caSYi Liu static guint vtd_hiod_hash(gconstpointer v)
261a20910caSYi Liu {
262a20910caSYi Liu     return vtd_as_hash(v);
263a20910caSYi Liu }
264a20910caSYi Liu 
vtd_hiod_equal(gconstpointer v1,gconstpointer v2)265a20910caSYi Liu static gboolean vtd_hiod_equal(gconstpointer v1, gconstpointer v2)
266a20910caSYi Liu {
267a20910caSYi Liu     const struct vtd_hiod_key *key1 = v1;
268a20910caSYi Liu     const struct vtd_hiod_key *key2 = v2;
269a20910caSYi Liu 
270a20910caSYi Liu     return (key1->bus == key2->bus) && (key1->devfn == key2->devfn);
271a20910caSYi Liu }
272a20910caSYi Liu 
vtd_hiod_destroy(gpointer v)273a20910caSYi Liu static void vtd_hiod_destroy(gpointer v)
274a20910caSYi Liu {
275a20910caSYi Liu     object_unref(v);
276a20910caSYi Liu }
277a20910caSYi Liu 
vtd_hash_remove_by_domain(gpointer key,gpointer value,gpointer user_data)278b5a280c0SLe Tan static gboolean vtd_hash_remove_by_domain(gpointer key, gpointer value,
279b5a280c0SLe Tan                                           gpointer user_data)
280b5a280c0SLe Tan {
281b5a280c0SLe Tan     VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value;
282b5a280c0SLe Tan     uint16_t domain_id = *(uint16_t *)user_data;
283b5a280c0SLe Tan     return entry->domain_id == domain_id;
284b5a280c0SLe Tan }
285b5a280c0SLe Tan 
286d66b969bSJason Wang /* The shift of an addr for a certain level of paging structure */
vtd_slpt_level_shift(uint32_t level)287d66b969bSJason Wang static inline uint32_t vtd_slpt_level_shift(uint32_t level)
288d66b969bSJason Wang {
2897e58326aSPeter Xu     assert(level != 0);
290d66b969bSJason Wang     return VTD_PAGE_SHIFT_4K + (level - 1) * VTD_SL_LEVEL_BITS;
291d66b969bSJason Wang }
292d66b969bSJason Wang 
vtd_slpt_level_page_mask(uint32_t level)293d66b969bSJason Wang static inline uint64_t vtd_slpt_level_page_mask(uint32_t level)
294d66b969bSJason Wang {
295d66b969bSJason Wang     return ~((1ULL << vtd_slpt_level_shift(level)) - 1);
296d66b969bSJason Wang }
297d66b969bSJason Wang 
vtd_hash_remove_by_page(gpointer key,gpointer value,gpointer user_data)298b5a280c0SLe Tan static gboolean vtd_hash_remove_by_page(gpointer key, gpointer value,
299b5a280c0SLe Tan                                         gpointer user_data)
300b5a280c0SLe Tan {
301b5a280c0SLe Tan     VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value;
302b5a280c0SLe Tan     VTDIOTLBPageInvInfo *info = (VTDIOTLBPageInvInfo *)user_data;
303d66b969bSJason Wang     uint64_t gfn = (info->addr >> VTD_PAGE_SHIFT_4K) & info->mask;
304d66b969bSJason Wang     uint64_t gfn_tlb = (info->addr & entry->mask) >> VTD_PAGE_SHIFT_4K;
305b5a280c0SLe Tan     return (entry->domain_id == info->domain_id) &&
306d66b969bSJason Wang             (((entry->gfn & info->mask) == gfn) ||
307d66b969bSJason Wang              (entry->gfn == gfn_tlb));
308b5a280c0SLe Tan }
309b5a280c0SLe Tan 
310d92fa2dcSLe Tan /* Reset all the gen of VTDAddressSpace to zero and set the gen of
3111d9efa73SPeter Xu  * IntelIOMMUState to 1.  Must be called with IOMMU lock held.
312d92fa2dcSLe Tan  */
vtd_reset_context_cache_locked(IntelIOMMUState * s)3131d9efa73SPeter Xu static void vtd_reset_context_cache_locked(IntelIOMMUState *s)
314d92fa2dcSLe Tan {
315d92fa2dcSLe Tan     VTDAddressSpace *vtd_as;
316da8d439cSJason Wang     GHashTableIter as_it;
317d92fa2dcSLe Tan 
3187feb51b7SPeter Xu     trace_vtd_context_cache_reset();
3197feb51b7SPeter Xu 
320da8d439cSJason Wang     g_hash_table_iter_init(&as_it, s->vtd_address_spaces);
3217df953bdSKnut Omang 
322da8d439cSJason Wang     while (g_hash_table_iter_next(&as_it, NULL, (void **)&vtd_as)) {
323d92fa2dcSLe Tan         vtd_as->context_cache_entry.context_cache_gen = 0;
324d92fa2dcSLe Tan     }
325d92fa2dcSLe Tan     s->context_cache_gen = 1;
326d92fa2dcSLe Tan }
327d92fa2dcSLe Tan 
3281d9efa73SPeter Xu /* Must be called with IOMMU lock held. */
vtd_reset_iotlb_locked(IntelIOMMUState * s)3291d9efa73SPeter Xu static void vtd_reset_iotlb_locked(IntelIOMMUState *s)
330b5a280c0SLe Tan {
331b5a280c0SLe Tan     assert(s->iotlb);
332b5a280c0SLe Tan     g_hash_table_remove_all(s->iotlb);
333b5a280c0SLe Tan }
334b5a280c0SLe Tan 
vtd_reset_iotlb(IntelIOMMUState * s)3351d9efa73SPeter Xu static void vtd_reset_iotlb(IntelIOMMUState *s)
3361d9efa73SPeter Xu {
3371d9efa73SPeter Xu     vtd_iommu_lock(s);
3381d9efa73SPeter Xu     vtd_reset_iotlb_locked(s);
3391d9efa73SPeter Xu     vtd_iommu_unlock(s);
3401d9efa73SPeter Xu }
3411d9efa73SPeter Xu 
vtd_reset_caches(IntelIOMMUState * s)34206aba4caSPeter Xu static void vtd_reset_caches(IntelIOMMUState *s)
34306aba4caSPeter Xu {
34406aba4caSPeter Xu     vtd_iommu_lock(s);
34506aba4caSPeter Xu     vtd_reset_iotlb_locked(s);
34606aba4caSPeter Xu     vtd_reset_context_cache_locked(s);
34706aba4caSPeter Xu     vtd_iommu_unlock(s);
34806aba4caSPeter Xu }
34906aba4caSPeter Xu 
vtd_get_iotlb_gfn(hwaddr addr,uint32_t level)350d66b969bSJason Wang static uint64_t vtd_get_iotlb_gfn(hwaddr addr, uint32_t level)
351d66b969bSJason Wang {
352d66b969bSJason Wang     return (addr & vtd_slpt_level_page_mask(level)) >> VTD_PAGE_SHIFT_4K;
353d66b969bSJason Wang }
354d66b969bSJason Wang 
3551d9efa73SPeter Xu /* Must be called with IOMMU lock held */
vtd_lookup_iotlb(IntelIOMMUState * s,uint16_t source_id,uint32_t pasid,hwaddr addr)356b5a280c0SLe Tan static VTDIOTLBEntry *vtd_lookup_iotlb(IntelIOMMUState *s, uint16_t source_id,
3571b2b1237SJason Wang                                        uint32_t pasid, hwaddr addr)
358b5a280c0SLe Tan {
3591b2b1237SJason Wang     struct vtd_iotlb_key key;
360d66b969bSJason Wang     VTDIOTLBEntry *entry;
361bb3a23d5SClément Mathieu--Drif     unsigned level;
362b5a280c0SLe Tan 
363d66b969bSJason Wang     for (level = VTD_SL_PT_LEVEL; level < VTD_SL_PML4_LEVEL; level++) {
3641b2b1237SJason Wang         key.gfn = vtd_get_iotlb_gfn(addr, level);
3651b2b1237SJason Wang         key.level = level;
3661b2b1237SJason Wang         key.sid = source_id;
3671b2b1237SJason Wang         key.pasid = pasid;
368d66b969bSJason Wang         entry = g_hash_table_lookup(s->iotlb, &key);
369d66b969bSJason Wang         if (entry) {
370d66b969bSJason Wang             goto out;
371d66b969bSJason Wang         }
372d66b969bSJason Wang     }
373b5a280c0SLe Tan 
374d66b969bSJason Wang out:
375d66b969bSJason Wang     return entry;
376b5a280c0SLe Tan }
377b5a280c0SLe Tan 
3781d9efa73SPeter Xu /* Must be with IOMMU lock held */
vtd_update_iotlb(IntelIOMMUState * s,uint16_t source_id,uint16_t domain_id,hwaddr addr,uint64_t slpte,uint8_t access_flags,uint32_t level,uint32_t pasid)379b5a280c0SLe Tan static void vtd_update_iotlb(IntelIOMMUState *s, uint16_t source_id,
380b5a280c0SLe Tan                              uint16_t domain_id, hwaddr addr, uint64_t slpte,
3811b2b1237SJason Wang                              uint8_t access_flags, uint32_t level,
3821b2b1237SJason Wang                              uint32_t pasid)
383b5a280c0SLe Tan {
384b5a280c0SLe Tan     VTDIOTLBEntry *entry = g_malloc(sizeof(*entry));
3851b2b1237SJason Wang     struct vtd_iotlb_key *key = g_malloc(sizeof(*key));
386d66b969bSJason Wang     uint64_t gfn = vtd_get_iotlb_gfn(addr, level);
387b5a280c0SLe Tan 
3886c441e1dSPeter Xu     trace_vtd_iotlb_page_update(source_id, addr, slpte, domain_id);
389b5a280c0SLe Tan     if (g_hash_table_size(s->iotlb) >= VTD_IOTLB_MAX_SIZE) {
3906c441e1dSPeter Xu         trace_vtd_iotlb_reset("iotlb exceeds size limit");
3911d9efa73SPeter Xu         vtd_reset_iotlb_locked(s);
392b5a280c0SLe Tan     }
393b5a280c0SLe Tan 
394b5a280c0SLe Tan     entry->gfn = gfn;
395b5a280c0SLe Tan     entry->domain_id = domain_id;
396b5a280c0SLe Tan     entry->slpte = slpte;
39707f7b733SPeter Xu     entry->access_flags = access_flags;
398d66b969bSJason Wang     entry->mask = vtd_slpt_level_page_mask(level);
3991b2b1237SJason Wang     entry->pasid = pasid;
4001b2b1237SJason Wang 
4011b2b1237SJason Wang     key->gfn = gfn;
4021b2b1237SJason Wang     key->sid = source_id;
4031b2b1237SJason Wang     key->level = level;
4041b2b1237SJason Wang     key->pasid = pasid;
4051b2b1237SJason Wang 
406b5a280c0SLe Tan     g_hash_table_replace(s->iotlb, key, entry);
407b5a280c0SLe Tan }
408b5a280c0SLe Tan 
4091da12ec4SLe Tan /* Given the reg addr of both the message data and address, generate an
4101da12ec4SLe Tan  * interrupt via MSI.
4111da12ec4SLe Tan  */
vtd_generate_interrupt(IntelIOMMUState * s,hwaddr mesg_addr_reg,hwaddr mesg_data_reg)4121da12ec4SLe Tan static void vtd_generate_interrupt(IntelIOMMUState *s, hwaddr mesg_addr_reg,
4131da12ec4SLe Tan                                    hwaddr mesg_data_reg)
4141da12ec4SLe Tan {
41532946019SRadim Krčmář     MSIMessage msi;
4161da12ec4SLe Tan 
4171da12ec4SLe Tan     assert(mesg_data_reg < DMAR_REG_SIZE);
4181da12ec4SLe Tan     assert(mesg_addr_reg < DMAR_REG_SIZE);
4191da12ec4SLe Tan 
42032946019SRadim Krčmář     msi.address = vtd_get_long_raw(s, mesg_addr_reg);
42132946019SRadim Krčmář     msi.data = vtd_get_long_raw(s, mesg_data_reg);
4221da12ec4SLe Tan 
4237feb51b7SPeter Xu     trace_vtd_irq_generate(msi.address, msi.data);
4247feb51b7SPeter Xu 
425eaaaf8abSPaolo Bonzini     apic_get_class(NULL)->send_msi(&msi);
4261da12ec4SLe Tan }
4271da12ec4SLe Tan 
4281da12ec4SLe Tan /* Generate a fault event to software via MSI if conditions are met.
4291da12ec4SLe Tan  * Notice that the value of FSTS_REG being passed to it should be the one
4301da12ec4SLe Tan  * before any update.
4311da12ec4SLe Tan  */
vtd_generate_fault_event(IntelIOMMUState * s,uint32_t pre_fsts)4321da12ec4SLe Tan static void vtd_generate_fault_event(IntelIOMMUState *s, uint32_t pre_fsts)
4331da12ec4SLe Tan {
4341da12ec4SLe Tan     if (pre_fsts & VTD_FSTS_PPF || pre_fsts & VTD_FSTS_PFO ||
4351da12ec4SLe Tan         pre_fsts & VTD_FSTS_IQE) {
4361376211fSPeter Xu         error_report_once("There are previous interrupt conditions "
4377feb51b7SPeter Xu                           "to be serviced by software, fault event "
4381376211fSPeter Xu                           "is not generated");
4391da12ec4SLe Tan         return;
4401da12ec4SLe Tan     }
4411da12ec4SLe Tan     vtd_set_clear_mask_long(s, DMAR_FECTL_REG, 0, VTD_FECTL_IP);
4421da12ec4SLe Tan     if (vtd_get_long_raw(s, DMAR_FECTL_REG) & VTD_FECTL_IM) {
4431376211fSPeter Xu         error_report_once("Interrupt Mask set, irq is not generated");
4441da12ec4SLe Tan     } else {
4451da12ec4SLe Tan         vtd_generate_interrupt(s, DMAR_FEADDR_REG, DMAR_FEDATA_REG);
4461da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
4471da12ec4SLe Tan     }
4481da12ec4SLe Tan }
4491da12ec4SLe Tan 
4501da12ec4SLe Tan /* Check if the Fault (F) field of the Fault Recording Register referenced by
4511da12ec4SLe Tan  * @index is Set.
4521da12ec4SLe Tan  */
vtd_is_frcd_set(IntelIOMMUState * s,uint16_t index)4531da12ec4SLe Tan static bool vtd_is_frcd_set(IntelIOMMUState *s, uint16_t index)
4541da12ec4SLe Tan {
4551da12ec4SLe Tan     /* Each reg is 128-bit */
4561da12ec4SLe Tan     hwaddr addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
4571da12ec4SLe Tan     addr += 8; /* Access the high 64-bit half */
4581da12ec4SLe Tan 
4591da12ec4SLe Tan     assert(index < DMAR_FRCD_REG_NR);
4601da12ec4SLe Tan 
4611da12ec4SLe Tan     return vtd_get_quad_raw(s, addr) & VTD_FRCD_F;
4621da12ec4SLe Tan }
4631da12ec4SLe Tan 
4641da12ec4SLe Tan /* Update the PPF field of Fault Status Register.
4651da12ec4SLe Tan  * Should be called whenever change the F field of any fault recording
4661da12ec4SLe Tan  * registers.
4671da12ec4SLe Tan  */
vtd_update_fsts_ppf(IntelIOMMUState * s)4681da12ec4SLe Tan static void vtd_update_fsts_ppf(IntelIOMMUState *s)
4691da12ec4SLe Tan {
4701da12ec4SLe Tan     uint32_t i;
4711da12ec4SLe Tan     uint32_t ppf_mask = 0;
4721da12ec4SLe Tan 
4731da12ec4SLe Tan     for (i = 0; i < DMAR_FRCD_REG_NR; i++) {
4741da12ec4SLe Tan         if (vtd_is_frcd_set(s, i)) {
4751da12ec4SLe Tan             ppf_mask = VTD_FSTS_PPF;
4761da12ec4SLe Tan             break;
4771da12ec4SLe Tan         }
4781da12ec4SLe Tan     }
4791da12ec4SLe Tan     vtd_set_clear_mask_long(s, DMAR_FSTS_REG, VTD_FSTS_PPF, ppf_mask);
4807feb51b7SPeter Xu     trace_vtd_fsts_ppf(!!ppf_mask);
4811da12ec4SLe Tan }
4821da12ec4SLe Tan 
vtd_set_frcd_and_update_ppf(IntelIOMMUState * s,uint16_t index)4831da12ec4SLe Tan static void vtd_set_frcd_and_update_ppf(IntelIOMMUState *s, uint16_t index)
4841da12ec4SLe Tan {
4851da12ec4SLe Tan     /* Each reg is 128-bit */
4861da12ec4SLe Tan     hwaddr addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
4871da12ec4SLe Tan     addr += 8; /* Access the high 64-bit half */
4881da12ec4SLe Tan 
4891da12ec4SLe Tan     assert(index < DMAR_FRCD_REG_NR);
4901da12ec4SLe Tan 
4911da12ec4SLe Tan     vtd_set_clear_mask_quad(s, addr, 0, VTD_FRCD_F);
4921da12ec4SLe Tan     vtd_update_fsts_ppf(s);
4931da12ec4SLe Tan }
4941da12ec4SLe Tan 
4951da12ec4SLe Tan /* Must not update F field now, should be done later */
vtd_record_frcd(IntelIOMMUState * s,uint16_t index,uint64_t hi,uint64_t lo)4961da12ec4SLe Tan static void vtd_record_frcd(IntelIOMMUState *s, uint16_t index,
497c7016bf7SDavid Woodhouse                             uint64_t hi, uint64_t lo)
4981da12ec4SLe Tan {
4991da12ec4SLe Tan     hwaddr frcd_reg_addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4);
5001da12ec4SLe Tan 
5011da12ec4SLe Tan     assert(index < DMAR_FRCD_REG_NR);
5021da12ec4SLe Tan 
5031da12ec4SLe Tan     vtd_set_quad_raw(s, frcd_reg_addr, lo);
5041da12ec4SLe Tan     vtd_set_quad_raw(s, frcd_reg_addr + 8, hi);
5057feb51b7SPeter Xu 
5067feb51b7SPeter Xu     trace_vtd_frr_new(index, hi, lo);
5071da12ec4SLe Tan }
5081da12ec4SLe Tan 
5091da12ec4SLe Tan /* Try to collapse multiple pending faults from the same requester */
vtd_try_collapse_fault(IntelIOMMUState * s,uint16_t source_id)5101da12ec4SLe Tan static bool vtd_try_collapse_fault(IntelIOMMUState *s, uint16_t source_id)
5111da12ec4SLe Tan {
5121da12ec4SLe Tan     uint32_t i;
5131da12ec4SLe Tan     uint64_t frcd_reg;
5141da12ec4SLe Tan     hwaddr addr = DMAR_FRCD_REG_OFFSET + 8; /* The high 64-bit half */
5151da12ec4SLe Tan 
5161da12ec4SLe Tan     for (i = 0; i < DMAR_FRCD_REG_NR; i++) {
5171da12ec4SLe Tan         frcd_reg = vtd_get_quad_raw(s, addr);
5181da12ec4SLe Tan         if ((frcd_reg & VTD_FRCD_F) &&
5191da12ec4SLe Tan             ((frcd_reg & VTD_FRCD_SID_MASK) == source_id)) {
5201da12ec4SLe Tan             return true;
5211da12ec4SLe Tan         }
5221da12ec4SLe Tan         addr += 16; /* 128-bit for each */
5231da12ec4SLe Tan     }
5241da12ec4SLe Tan     return false;
5251da12ec4SLe Tan }
5261da12ec4SLe Tan 
5271da12ec4SLe Tan /* Log and report an DMAR (address translation) fault to software */
vtd_report_frcd_fault(IntelIOMMUState * s,uint64_t source_id,uint64_t hi,uint64_t lo)528c7016bf7SDavid Woodhouse static void vtd_report_frcd_fault(IntelIOMMUState *s, uint64_t source_id,
529c7016bf7SDavid Woodhouse                                   uint64_t hi, uint64_t lo)
5301da12ec4SLe Tan {
5311da12ec4SLe Tan     uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
5321da12ec4SLe Tan 
5331da12ec4SLe Tan     if (fsts_reg & VTD_FSTS_PFO) {
5341376211fSPeter Xu         error_report_once("New fault is not recorded due to "
5351376211fSPeter Xu                           "Primary Fault Overflow");
5361da12ec4SLe Tan         return;
5371da12ec4SLe Tan     }
5387feb51b7SPeter Xu 
5391da12ec4SLe Tan     if (vtd_try_collapse_fault(s, source_id)) {
5401376211fSPeter Xu         error_report_once("New fault is not recorded due to "
5411376211fSPeter Xu                           "compression of faults");
5421da12ec4SLe Tan         return;
5431da12ec4SLe Tan     }
5447feb51b7SPeter Xu 
5451da12ec4SLe Tan     if (vtd_is_frcd_set(s, s->next_frcd_reg)) {
5461376211fSPeter Xu         error_report_once("Next Fault Recording Reg is used, "
5471376211fSPeter Xu                           "new fault is not recorded, set PFO field");
5481da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_FSTS_REG, 0, VTD_FSTS_PFO);
5491da12ec4SLe Tan         return;
5501da12ec4SLe Tan     }
5511da12ec4SLe Tan 
552c7016bf7SDavid Woodhouse     vtd_record_frcd(s, s->next_frcd_reg, hi, lo);
5531da12ec4SLe Tan 
5541da12ec4SLe Tan     if (fsts_reg & VTD_FSTS_PPF) {
5551376211fSPeter Xu         error_report_once("There are pending faults already, "
5561376211fSPeter Xu                           "fault event is not generated");
5571da12ec4SLe Tan         vtd_set_frcd_and_update_ppf(s, s->next_frcd_reg);
5581da12ec4SLe Tan         s->next_frcd_reg++;
5591da12ec4SLe Tan         if (s->next_frcd_reg == DMAR_FRCD_REG_NR) {
5601da12ec4SLe Tan             s->next_frcd_reg = 0;
5611da12ec4SLe Tan         }
5621da12ec4SLe Tan     } else {
5631da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_FSTS_REG, VTD_FSTS_FRI_MASK,
5641da12ec4SLe Tan                                 VTD_FSTS_FRI(s->next_frcd_reg));
5651da12ec4SLe Tan         vtd_set_frcd_and_update_ppf(s, s->next_frcd_reg); /* Will set PPF */
5661da12ec4SLe Tan         s->next_frcd_reg++;
5671da12ec4SLe Tan         if (s->next_frcd_reg == DMAR_FRCD_REG_NR) {
5681da12ec4SLe Tan             s->next_frcd_reg = 0;
5691da12ec4SLe Tan         }
5701da12ec4SLe Tan         /* This case actually cause the PPF to be Set.
5711da12ec4SLe Tan          * So generate fault event (interrupt).
5721da12ec4SLe Tan          */
5731da12ec4SLe Tan          vtd_generate_fault_event(s, fsts_reg);
5741da12ec4SLe Tan     }
5751da12ec4SLe Tan }
5761da12ec4SLe Tan 
577c7016bf7SDavid Woodhouse /* Log and report an DMAR (address translation) fault to software */
vtd_report_dmar_fault(IntelIOMMUState * s,uint16_t source_id,hwaddr addr,VTDFaultReason fault,bool is_write,bool is_pasid,uint32_t pasid)578c7016bf7SDavid Woodhouse static void vtd_report_dmar_fault(IntelIOMMUState *s, uint16_t source_id,
579c7016bf7SDavid Woodhouse                                   hwaddr addr, VTDFaultReason fault,
580c7016bf7SDavid Woodhouse                                   bool is_write, bool is_pasid,
581c7016bf7SDavid Woodhouse                                   uint32_t pasid)
582c7016bf7SDavid Woodhouse {
583c7016bf7SDavid Woodhouse     uint64_t hi, lo;
584c7016bf7SDavid Woodhouse 
585c7016bf7SDavid Woodhouse     assert(fault < VTD_FR_MAX);
586c7016bf7SDavid Woodhouse 
587c7016bf7SDavid Woodhouse     trace_vtd_dmar_fault(source_id, fault, addr, is_write);
588c7016bf7SDavid Woodhouse 
589c7016bf7SDavid Woodhouse     lo = VTD_FRCD_FI(addr);
590c7016bf7SDavid Woodhouse     hi = VTD_FRCD_SID(source_id) | VTD_FRCD_FR(fault) |
591c7016bf7SDavid Woodhouse          VTD_FRCD_PV(pasid) | VTD_FRCD_PP(is_pasid);
592c7016bf7SDavid Woodhouse     if (!is_write) {
593c7016bf7SDavid Woodhouse         hi |= VTD_FRCD_T;
594c7016bf7SDavid Woodhouse     }
595c7016bf7SDavid Woodhouse 
596c7016bf7SDavid Woodhouse     vtd_report_frcd_fault(s, source_id, hi, lo);
597c7016bf7SDavid Woodhouse }
598c7016bf7SDavid Woodhouse 
599c7016bf7SDavid Woodhouse 
vtd_report_ir_fault(IntelIOMMUState * s,uint64_t source_id,VTDFaultReason fault,uint16_t index)600c7016bf7SDavid Woodhouse static void vtd_report_ir_fault(IntelIOMMUState *s, uint64_t source_id,
601c7016bf7SDavid Woodhouse                                 VTDFaultReason fault, uint16_t index)
602c7016bf7SDavid Woodhouse {
603c7016bf7SDavid Woodhouse     uint64_t hi, lo;
604c7016bf7SDavid Woodhouse 
605c7016bf7SDavid Woodhouse     lo = VTD_FRCD_IR_IDX(index);
606c7016bf7SDavid Woodhouse     hi = VTD_FRCD_SID(source_id) | VTD_FRCD_FR(fault);
607c7016bf7SDavid Woodhouse 
608c7016bf7SDavid Woodhouse     vtd_report_frcd_fault(s, source_id, hi, lo);
609c7016bf7SDavid Woodhouse }
610c7016bf7SDavid Woodhouse 
611ed7b8fbcSLe Tan /* Handle Invalidation Queue Errors of queued invalidation interface error
612ed7b8fbcSLe Tan  * conditions.
613ed7b8fbcSLe Tan  */
vtd_handle_inv_queue_error(IntelIOMMUState * s)614ed7b8fbcSLe Tan static void vtd_handle_inv_queue_error(IntelIOMMUState *s)
615ed7b8fbcSLe Tan {
616ed7b8fbcSLe Tan     uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
617ed7b8fbcSLe Tan 
618ed7b8fbcSLe Tan     vtd_set_clear_mask_long(s, DMAR_FSTS_REG, 0, VTD_FSTS_IQE);
619ed7b8fbcSLe Tan     vtd_generate_fault_event(s, fsts_reg);
620ed7b8fbcSLe Tan }
621ed7b8fbcSLe Tan 
622ed7b8fbcSLe Tan /* Set the IWC field and try to generate an invalidation completion interrupt */
vtd_generate_completion_event(IntelIOMMUState * s)623ed7b8fbcSLe Tan static void vtd_generate_completion_event(IntelIOMMUState *s)
624ed7b8fbcSLe Tan {
625ed7b8fbcSLe Tan     if (vtd_get_long_raw(s, DMAR_ICS_REG) & VTD_ICS_IWC) {
626bc535e59SPeter Xu         trace_vtd_inv_desc_wait_irq("One pending, skip current");
627ed7b8fbcSLe Tan         return;
628ed7b8fbcSLe Tan     }
629ed7b8fbcSLe Tan     vtd_set_clear_mask_long(s, DMAR_ICS_REG, 0, VTD_ICS_IWC);
630ed7b8fbcSLe Tan     vtd_set_clear_mask_long(s, DMAR_IECTL_REG, 0, VTD_IECTL_IP);
631ed7b8fbcSLe Tan     if (vtd_get_long_raw(s, DMAR_IECTL_REG) & VTD_IECTL_IM) {
632bc535e59SPeter Xu         trace_vtd_inv_desc_wait_irq("IM in IECTL_REG is set, "
633bc535e59SPeter Xu                                     "new event not generated");
634ed7b8fbcSLe Tan         return;
635ed7b8fbcSLe Tan     } else {
636ed7b8fbcSLe Tan         /* Generate the interrupt event */
637bc535e59SPeter Xu         trace_vtd_inv_desc_wait_irq("Generating complete event");
638ed7b8fbcSLe Tan         vtd_generate_interrupt(s, DMAR_IEADDR_REG, DMAR_IEDATA_REG);
639ed7b8fbcSLe Tan         vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
640ed7b8fbcSLe Tan     }
641ed7b8fbcSLe Tan }
642ed7b8fbcSLe Tan 
vtd_root_entry_present(IntelIOMMUState * s,VTDRootEntry * re,uint8_t devfn)643fb43cf73SLiu, Yi L static inline bool vtd_root_entry_present(IntelIOMMUState *s,
644fb43cf73SLiu, Yi L                                           VTDRootEntry *re,
645fb43cf73SLiu, Yi L                                           uint8_t devfn)
6461da12ec4SLe Tan {
647fb43cf73SLiu, Yi L     if (s->root_scalable && devfn > UINT8_MAX / 2) {
648fb43cf73SLiu, Yi L         return re->hi & VTD_ROOT_ENTRY_P;
649fb43cf73SLiu, Yi L     }
650fb43cf73SLiu, Yi L 
651fb43cf73SLiu, Yi L     return re->lo & VTD_ROOT_ENTRY_P;
6521da12ec4SLe Tan }
6531da12ec4SLe Tan 
vtd_get_root_entry(IntelIOMMUState * s,uint8_t index,VTDRootEntry * re)6541da12ec4SLe Tan static int vtd_get_root_entry(IntelIOMMUState *s, uint8_t index,
6551da12ec4SLe Tan                               VTDRootEntry *re)
6561da12ec4SLe Tan {
6571da12ec4SLe Tan     dma_addr_t addr;
6581da12ec4SLe Tan 
6591da12ec4SLe Tan     addr = s->root + index * sizeof(*re);
660ba06fe8aSPhilippe Mathieu-Daudé     if (dma_memory_read(&address_space_memory, addr,
661ba06fe8aSPhilippe Mathieu-Daudé                         re, sizeof(*re), MEMTXATTRS_UNSPECIFIED)) {
662fb43cf73SLiu, Yi L         re->lo = 0;
6631da12ec4SLe Tan         return -VTD_FR_ROOT_TABLE_INV;
6641da12ec4SLe Tan     }
665fb43cf73SLiu, Yi L     re->lo = le64_to_cpu(re->lo);
666fb43cf73SLiu, Yi L     re->hi = le64_to_cpu(re->hi);
6671da12ec4SLe Tan     return 0;
6681da12ec4SLe Tan }
6691da12ec4SLe Tan 
vtd_ce_present(VTDContextEntry * context)6708f7d7161SPeter Xu static inline bool vtd_ce_present(VTDContextEntry *context)
6711da12ec4SLe Tan {
6721da12ec4SLe Tan     return context->lo & VTD_CONTEXT_ENTRY_P;
6731da12ec4SLe Tan }
6741da12ec4SLe Tan 
vtd_get_context_entry_from_root(IntelIOMMUState * s,VTDRootEntry * re,uint8_t index,VTDContextEntry * ce)675fb43cf73SLiu, Yi L static int vtd_get_context_entry_from_root(IntelIOMMUState *s,
676fb43cf73SLiu, Yi L                                            VTDRootEntry *re,
677fb43cf73SLiu, Yi L                                            uint8_t index,
6781da12ec4SLe Tan                                            VTDContextEntry *ce)
6791da12ec4SLe Tan {
680fb43cf73SLiu, Yi L     dma_addr_t addr, ce_size;
6811da12ec4SLe Tan 
6826c441e1dSPeter Xu     /* we have checked that root entry is present */
683fb43cf73SLiu, Yi L     ce_size = s->root_scalable ? VTD_CTX_ENTRY_SCALABLE_SIZE :
684fb43cf73SLiu, Yi L               VTD_CTX_ENTRY_LEGACY_SIZE;
685fb43cf73SLiu, Yi L 
686fb43cf73SLiu, Yi L     if (s->root_scalable && index > UINT8_MAX / 2) {
687fb43cf73SLiu, Yi L         index = index & (~VTD_DEVFN_CHECK_MASK);
688fb43cf73SLiu, Yi L         addr = re->hi & VTD_ROOT_ENTRY_CTP;
689fb43cf73SLiu, Yi L     } else {
690fb43cf73SLiu, Yi L         addr = re->lo & VTD_ROOT_ENTRY_CTP;
691fb43cf73SLiu, Yi L     }
692fb43cf73SLiu, Yi L 
693fb43cf73SLiu, Yi L     addr = addr + index * ce_size;
694ba06fe8aSPhilippe Mathieu-Daudé     if (dma_memory_read(&address_space_memory, addr,
695ba06fe8aSPhilippe Mathieu-Daudé                         ce, ce_size, MEMTXATTRS_UNSPECIFIED)) {
6961da12ec4SLe Tan         return -VTD_FR_CONTEXT_TABLE_INV;
6971da12ec4SLe Tan     }
698fb43cf73SLiu, Yi L 
6991da12ec4SLe Tan     ce->lo = le64_to_cpu(ce->lo);
7001da12ec4SLe Tan     ce->hi = le64_to_cpu(ce->hi);
701fb43cf73SLiu, Yi L     if (ce_size == VTD_CTX_ENTRY_SCALABLE_SIZE) {
702fb43cf73SLiu, Yi L         ce->val[2] = le64_to_cpu(ce->val[2]);
703fb43cf73SLiu, Yi L         ce->val[3] = le64_to_cpu(ce->val[3]);
704fb43cf73SLiu, Yi L     }
7051da12ec4SLe Tan     return 0;
7061da12ec4SLe Tan }
7071da12ec4SLe Tan 
vtd_ce_get_slpt_base(VTDContextEntry * ce)7088f7d7161SPeter Xu static inline dma_addr_t vtd_ce_get_slpt_base(VTDContextEntry *ce)
7091da12ec4SLe Tan {
7101da12ec4SLe Tan     return ce->lo & VTD_CONTEXT_ENTRY_SLPTPTR;
7111da12ec4SLe Tan }
7121da12ec4SLe Tan 
vtd_get_slpte_addr(uint64_t slpte,uint8_t aw)71337f51384SPrasad Singamsetty static inline uint64_t vtd_get_slpte_addr(uint64_t slpte, uint8_t aw)
7141da12ec4SLe Tan {
71537f51384SPrasad Singamsetty     return slpte & VTD_SL_PT_BASE_ADDR_MASK(aw);
7161da12ec4SLe Tan }
7171da12ec4SLe Tan 
7181da12ec4SLe Tan /* Whether the pte indicates the address of the page frame */
vtd_is_last_slpte(uint64_t slpte,uint32_t level)7191da12ec4SLe Tan static inline bool vtd_is_last_slpte(uint64_t slpte, uint32_t level)
7201da12ec4SLe Tan {
7211da12ec4SLe Tan     return level == VTD_SL_PT_LEVEL || (slpte & VTD_SL_PT_PAGE_SIZE_MASK);
7221da12ec4SLe Tan }
7231da12ec4SLe Tan 
7241da12ec4SLe Tan /* Get the content of a spte located in @base_addr[@index] */
vtd_get_slpte(dma_addr_t base_addr,uint32_t index)7251da12ec4SLe Tan static uint64_t vtd_get_slpte(dma_addr_t base_addr, uint32_t index)
7261da12ec4SLe Tan {
7271da12ec4SLe Tan     uint64_t slpte;
7281da12ec4SLe Tan 
7291da12ec4SLe Tan     assert(index < VTD_SL_PT_ENTRY_NR);
7301da12ec4SLe Tan 
7311da12ec4SLe Tan     if (dma_memory_read(&address_space_memory,
732ba06fe8aSPhilippe Mathieu-Daudé                         base_addr + index * sizeof(slpte),
733ba06fe8aSPhilippe Mathieu-Daudé                         &slpte, sizeof(slpte), MEMTXATTRS_UNSPECIFIED)) {
7341da12ec4SLe Tan         slpte = (uint64_t)-1;
7351da12ec4SLe Tan         return slpte;
7361da12ec4SLe Tan     }
7371da12ec4SLe Tan     slpte = le64_to_cpu(slpte);
7381da12ec4SLe Tan     return slpte;
7391da12ec4SLe Tan }
7401da12ec4SLe Tan 
7416e905564SPeter Xu /* Given an iova and the level of paging structure, return the offset
7426e905564SPeter Xu  * of current level.
7431da12ec4SLe Tan  */
vtd_iova_level_offset(uint64_t iova,uint32_t level)7446e905564SPeter Xu static inline uint32_t vtd_iova_level_offset(uint64_t iova, uint32_t level)
7451da12ec4SLe Tan {
7466e905564SPeter Xu     return (iova >> vtd_slpt_level_shift(level)) &
7471da12ec4SLe Tan             ((1ULL << VTD_SL_LEVEL_BITS) - 1);
7481da12ec4SLe Tan }
7491da12ec4SLe Tan 
7501da12ec4SLe Tan /* Check Capability Register to see if the @level of page-table is supported */
vtd_is_level_supported(IntelIOMMUState * s,uint32_t level)7511da12ec4SLe Tan static inline bool vtd_is_level_supported(IntelIOMMUState *s, uint32_t level)
7521da12ec4SLe Tan {
7531da12ec4SLe Tan     return VTD_CAP_SAGAW_MASK & s->cap &
7541da12ec4SLe Tan            (1ULL << (level - 2 + VTD_CAP_SAGAW_SHIFT));
7551da12ec4SLe Tan }
7561da12ec4SLe Tan 
757fb43cf73SLiu, Yi L /* Return true if check passed, otherwise false */
vtd_pe_type_check(X86IOMMUState * x86_iommu,VTDPASIDEntry * pe)758fb43cf73SLiu, Yi L static inline bool vtd_pe_type_check(X86IOMMUState *x86_iommu,
759fb43cf73SLiu, Yi L                                      VTDPASIDEntry *pe)
760fb43cf73SLiu, Yi L {
761fb43cf73SLiu, Yi L     switch (VTD_PE_GET_TYPE(pe)) {
762fb43cf73SLiu, Yi L     case VTD_SM_PASID_ENTRY_FLT:
763fb43cf73SLiu, Yi L     case VTD_SM_PASID_ENTRY_SLT:
764fb43cf73SLiu, Yi L     case VTD_SM_PASID_ENTRY_NESTED:
765fb43cf73SLiu, Yi L         break;
766fb43cf73SLiu, Yi L     case VTD_SM_PASID_ENTRY_PT:
767fb43cf73SLiu, Yi L         if (!x86_iommu->pt_supported) {
768fb43cf73SLiu, Yi L             return false;
769fb43cf73SLiu, Yi L         }
770fb43cf73SLiu, Yi L         break;
771fb43cf73SLiu, Yi L     default:
77237557b09SCai Huoqing         /* Unknown type */
773fb43cf73SLiu, Yi L         return false;
774fb43cf73SLiu, Yi L     }
775fb43cf73SLiu, Yi L     return true;
776fb43cf73SLiu, Yi L }
777fb43cf73SLiu, Yi L 
vtd_pdire_present(VTDPASIDDirEntry * pdire)77856fc1e6aSLiu Yi L static inline bool vtd_pdire_present(VTDPASIDDirEntry *pdire)
77956fc1e6aSLiu Yi L {
78056fc1e6aSLiu Yi L     return pdire->val & 1;
78156fc1e6aSLiu Yi L }
78256fc1e6aSLiu Yi L 
78356fc1e6aSLiu Yi L /**
78456fc1e6aSLiu Yi L  * Caller of this function should check present bit if wants
78537557b09SCai Huoqing  * to use pdir entry for further usage except for fpd bit check.
78656fc1e6aSLiu Yi L  */
vtd_get_pdire_from_pdir_table(dma_addr_t pasid_dir_base,uint32_t pasid,VTDPASIDDirEntry * pdire)78756fc1e6aSLiu Yi L static int vtd_get_pdire_from_pdir_table(dma_addr_t pasid_dir_base,
788fb43cf73SLiu, Yi L                                          uint32_t pasid,
789fb43cf73SLiu, Yi L                                          VTDPASIDDirEntry *pdire)
790fb43cf73SLiu, Yi L {
791fb43cf73SLiu, Yi L     uint32_t index;
792fb43cf73SLiu, Yi L     dma_addr_t addr, entry_size;
793fb43cf73SLiu, Yi L 
794fb43cf73SLiu, Yi L     index = VTD_PASID_DIR_INDEX(pasid);
795fb43cf73SLiu, Yi L     entry_size = VTD_PASID_DIR_ENTRY_SIZE;
796fb43cf73SLiu, Yi L     addr = pasid_dir_base + index * entry_size;
797ba06fe8aSPhilippe Mathieu-Daudé     if (dma_memory_read(&address_space_memory, addr,
798ba06fe8aSPhilippe Mathieu-Daudé                         pdire, entry_size, MEMTXATTRS_UNSPECIFIED)) {
799fb43cf73SLiu, Yi L         return -VTD_FR_PASID_TABLE_INV;
800fb43cf73SLiu, Yi L     }
801fb43cf73SLiu, Yi L 
802cc2a0848SThomas Huth     pdire->val = le64_to_cpu(pdire->val);
803cc2a0848SThomas Huth 
804fb43cf73SLiu, Yi L     return 0;
805fb43cf73SLiu, Yi L }
806fb43cf73SLiu, Yi L 
vtd_pe_present(VTDPASIDEntry * pe)80756fc1e6aSLiu Yi L static inline bool vtd_pe_present(VTDPASIDEntry *pe)
80856fc1e6aSLiu Yi L {
80956fc1e6aSLiu Yi L     return pe->val[0] & VTD_PASID_ENTRY_P;
81056fc1e6aSLiu Yi L }
81156fc1e6aSLiu Yi L 
vtd_get_pe_in_pasid_leaf_table(IntelIOMMUState * s,uint32_t pasid,dma_addr_t addr,VTDPASIDEntry * pe)81256fc1e6aSLiu Yi L static int vtd_get_pe_in_pasid_leaf_table(IntelIOMMUState *s,
813fb43cf73SLiu, Yi L                                           uint32_t pasid,
81456fc1e6aSLiu Yi L                                           dma_addr_t addr,
815fb43cf73SLiu, Yi L                                           VTDPASIDEntry *pe)
816fb43cf73SLiu, Yi L {
817fb43cf73SLiu, Yi L     uint32_t index;
81856fc1e6aSLiu Yi L     dma_addr_t entry_size;
819fb43cf73SLiu, Yi L     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
820fb43cf73SLiu, Yi L 
821fb43cf73SLiu, Yi L     index = VTD_PASID_TABLE_INDEX(pasid);
822fb43cf73SLiu, Yi L     entry_size = VTD_PASID_ENTRY_SIZE;
823fb43cf73SLiu, Yi L     addr = addr + index * entry_size;
824ba06fe8aSPhilippe Mathieu-Daudé     if (dma_memory_read(&address_space_memory, addr,
825ba06fe8aSPhilippe Mathieu-Daudé                         pe, entry_size, MEMTXATTRS_UNSPECIFIED)) {
826fb43cf73SLiu, Yi L         return -VTD_FR_PASID_TABLE_INV;
827fb43cf73SLiu, Yi L     }
828cc2a0848SThomas Huth     for (size_t i = 0; i < ARRAY_SIZE(pe->val); i++) {
829cc2a0848SThomas Huth         pe->val[i] = le64_to_cpu(pe->val[i]);
830cc2a0848SThomas Huth     }
831fb43cf73SLiu, Yi L 
832fb43cf73SLiu, Yi L     /* Do translation type check */
833fb43cf73SLiu, Yi L     if (!vtd_pe_type_check(x86_iommu, pe)) {
834fb43cf73SLiu, Yi L         return -VTD_FR_PASID_TABLE_INV;
835fb43cf73SLiu, Yi L     }
836fb43cf73SLiu, Yi L 
837fb43cf73SLiu, Yi L     if (!vtd_is_level_supported(s, VTD_PE_GET_LEVEL(pe))) {
838fb43cf73SLiu, Yi L         return -VTD_FR_PASID_TABLE_INV;
839fb43cf73SLiu, Yi L     }
840fb43cf73SLiu, Yi L 
841fb43cf73SLiu, Yi L     return 0;
842fb43cf73SLiu, Yi L }
843fb43cf73SLiu, Yi L 
84456fc1e6aSLiu Yi L /**
84556fc1e6aSLiu Yi L  * Caller of this function should check present bit if wants
84637557b09SCai Huoqing  * to use pasid entry for further usage except for fpd bit check.
84756fc1e6aSLiu Yi L  */
vtd_get_pe_from_pdire(IntelIOMMUState * s,uint32_t pasid,VTDPASIDDirEntry * pdire,VTDPASIDEntry * pe)84856fc1e6aSLiu Yi L static int vtd_get_pe_from_pdire(IntelIOMMUState *s,
84956fc1e6aSLiu Yi L                                  uint32_t pasid,
85056fc1e6aSLiu Yi L                                  VTDPASIDDirEntry *pdire,
85156fc1e6aSLiu Yi L                                  VTDPASIDEntry *pe)
85256fc1e6aSLiu Yi L {
85356fc1e6aSLiu Yi L     dma_addr_t addr = pdire->val & VTD_PASID_TABLE_BASE_ADDR_MASK;
85456fc1e6aSLiu Yi L 
85556fc1e6aSLiu Yi L     return vtd_get_pe_in_pasid_leaf_table(s, pasid, addr, pe);
85656fc1e6aSLiu Yi L }
85756fc1e6aSLiu Yi L 
85856fc1e6aSLiu Yi L /**
85956fc1e6aSLiu Yi L  * This function gets a pasid entry from a specified pasid
86056fc1e6aSLiu Yi L  * table (includes dir and leaf table) with a specified pasid.
86156fc1e6aSLiu Yi L  * Sanity check should be done to ensure return a present
86256fc1e6aSLiu Yi L  * pasid entry to caller.
86356fc1e6aSLiu Yi L  */
vtd_get_pe_from_pasid_table(IntelIOMMUState * s,dma_addr_t pasid_dir_base,uint32_t pasid,VTDPASIDEntry * pe)86456fc1e6aSLiu Yi L static int vtd_get_pe_from_pasid_table(IntelIOMMUState *s,
865fb43cf73SLiu, Yi L                                        dma_addr_t pasid_dir_base,
866fb43cf73SLiu, Yi L                                        uint32_t pasid,
867fb43cf73SLiu, Yi L                                        VTDPASIDEntry *pe)
868fb43cf73SLiu, Yi L {
869fb43cf73SLiu, Yi L     int ret;
870fb43cf73SLiu, Yi L     VTDPASIDDirEntry pdire;
871fb43cf73SLiu, Yi L 
87256fc1e6aSLiu Yi L     ret = vtd_get_pdire_from_pdir_table(pasid_dir_base,
87356fc1e6aSLiu Yi L                                         pasid, &pdire);
874fb43cf73SLiu, Yi L     if (ret) {
875fb43cf73SLiu, Yi L         return ret;
876fb43cf73SLiu, Yi L     }
877fb43cf73SLiu, Yi L 
87856fc1e6aSLiu Yi L     if (!vtd_pdire_present(&pdire)) {
87956fc1e6aSLiu Yi L         return -VTD_FR_PASID_TABLE_INV;
88056fc1e6aSLiu Yi L     }
88156fc1e6aSLiu Yi L 
88256fc1e6aSLiu Yi L     ret = vtd_get_pe_from_pdire(s, pasid, &pdire, pe);
883fb43cf73SLiu, Yi L     if (ret) {
884fb43cf73SLiu, Yi L         return ret;
885fb43cf73SLiu, Yi L     }
886fb43cf73SLiu, Yi L 
88756fc1e6aSLiu Yi L     if (!vtd_pe_present(pe)) {
88856fc1e6aSLiu Yi L         return -VTD_FR_PASID_TABLE_INV;
88956fc1e6aSLiu Yi L     }
89056fc1e6aSLiu Yi L 
89156fc1e6aSLiu Yi L     return 0;
892fb43cf73SLiu, Yi L }
893fb43cf73SLiu, Yi L 
vtd_ce_get_rid2pasid_entry(IntelIOMMUState * s,VTDContextEntry * ce,VTDPASIDEntry * pe,uint32_t pasid)894fb43cf73SLiu, Yi L static int vtd_ce_get_rid2pasid_entry(IntelIOMMUState *s,
895fb43cf73SLiu, Yi L                                       VTDContextEntry *ce,
8961b2b1237SJason Wang                                       VTDPASIDEntry *pe,
8971b2b1237SJason Wang                                       uint32_t pasid)
898fb43cf73SLiu, Yi L {
899fb43cf73SLiu, Yi L     dma_addr_t pasid_dir_base;
900fb43cf73SLiu, Yi L     int ret = 0;
901fb43cf73SLiu, Yi L 
9021b2b1237SJason Wang     if (pasid == PCI_NO_PASID) {
903fb43cf73SLiu, Yi L         pasid = VTD_CE_GET_RID2PASID(ce);
9041b2b1237SJason Wang     }
905fb43cf73SLiu, Yi L     pasid_dir_base = VTD_CE_GET_PASID_DIR_TABLE(ce);
90656fc1e6aSLiu Yi L     ret = vtd_get_pe_from_pasid_table(s, pasid_dir_base, pasid, pe);
907fb43cf73SLiu, Yi L 
908fb43cf73SLiu, Yi L     return ret;
909fb43cf73SLiu, Yi L }
910fb43cf73SLiu, Yi L 
vtd_ce_get_pasid_fpd(IntelIOMMUState * s,VTDContextEntry * ce,bool * pe_fpd_set,uint32_t pasid)911fb43cf73SLiu, Yi L static int vtd_ce_get_pasid_fpd(IntelIOMMUState *s,
912fb43cf73SLiu, Yi L                                 VTDContextEntry *ce,
9131b2b1237SJason Wang                                 bool *pe_fpd_set,
9141b2b1237SJason Wang                                 uint32_t pasid)
915fb43cf73SLiu, Yi L {
916fb43cf73SLiu, Yi L     int ret;
917fb43cf73SLiu, Yi L     dma_addr_t pasid_dir_base;
918fb43cf73SLiu, Yi L     VTDPASIDDirEntry pdire;
919fb43cf73SLiu, Yi L     VTDPASIDEntry pe;
920fb43cf73SLiu, Yi L 
9211b2b1237SJason Wang     if (pasid == PCI_NO_PASID) {
922fb43cf73SLiu, Yi L         pasid = VTD_CE_GET_RID2PASID(ce);
9231b2b1237SJason Wang     }
924fb43cf73SLiu, Yi L     pasid_dir_base = VTD_CE_GET_PASID_DIR_TABLE(ce);
925fb43cf73SLiu, Yi L 
92656fc1e6aSLiu Yi L     /*
92756fc1e6aSLiu Yi L      * No present bit check since fpd is meaningful even
92856fc1e6aSLiu Yi L      * if the present bit is clear.
92956fc1e6aSLiu Yi L      */
93056fc1e6aSLiu Yi L     ret = vtd_get_pdire_from_pdir_table(pasid_dir_base, pasid, &pdire);
931fb43cf73SLiu, Yi L     if (ret) {
932fb43cf73SLiu, Yi L         return ret;
933fb43cf73SLiu, Yi L     }
934fb43cf73SLiu, Yi L 
935fb43cf73SLiu, Yi L     if (pdire.val & VTD_PASID_DIR_FPD) {
936fb43cf73SLiu, Yi L         *pe_fpd_set = true;
937fb43cf73SLiu, Yi L         return 0;
938fb43cf73SLiu, Yi L     }
939fb43cf73SLiu, Yi L 
94056fc1e6aSLiu Yi L     if (!vtd_pdire_present(&pdire)) {
94156fc1e6aSLiu Yi L         return -VTD_FR_PASID_TABLE_INV;
94256fc1e6aSLiu Yi L     }
94356fc1e6aSLiu Yi L 
94456fc1e6aSLiu Yi L     /*
94556fc1e6aSLiu Yi L      * No present bit check since fpd is meaningful even
94656fc1e6aSLiu Yi L      * if the present bit is clear.
94756fc1e6aSLiu Yi L      */
94856fc1e6aSLiu Yi L     ret = vtd_get_pe_from_pdire(s, pasid, &pdire, &pe);
949fb43cf73SLiu, Yi L     if (ret) {
950fb43cf73SLiu, Yi L         return ret;
951fb43cf73SLiu, Yi L     }
952fb43cf73SLiu, Yi L 
953fb43cf73SLiu, Yi L     if (pe.val[0] & VTD_PASID_ENTRY_FPD) {
954fb43cf73SLiu, Yi L         *pe_fpd_set = true;
955fb43cf73SLiu, Yi L     }
956fb43cf73SLiu, Yi L 
957fb43cf73SLiu, Yi L     return 0;
958fb43cf73SLiu, Yi L }
959fb43cf73SLiu, Yi L 
9601da12ec4SLe Tan /* Get the page-table level that hardware should use for the second-level
9611da12ec4SLe Tan  * page-table walk from the Address Width field of context-entry.
9621da12ec4SLe Tan  */
vtd_ce_get_level(VTDContextEntry * ce)9638f7d7161SPeter Xu static inline uint32_t vtd_ce_get_level(VTDContextEntry *ce)
9641da12ec4SLe Tan {
9651da12ec4SLe Tan     return 2 + (ce->hi & VTD_CONTEXT_ENTRY_AW);
9661da12ec4SLe Tan }
9671da12ec4SLe Tan 
vtd_get_iova_level(IntelIOMMUState * s,VTDContextEntry * ce,uint32_t pasid)968fb43cf73SLiu, Yi L static uint32_t vtd_get_iova_level(IntelIOMMUState *s,
9691b2b1237SJason Wang                                    VTDContextEntry *ce,
9701b2b1237SJason Wang                                    uint32_t pasid)
971fb43cf73SLiu, Yi L {
972fb43cf73SLiu, Yi L     VTDPASIDEntry pe;
973fb43cf73SLiu, Yi L 
974fb43cf73SLiu, Yi L     if (s->root_scalable) {
9751b2b1237SJason Wang         vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
976fb43cf73SLiu, Yi L         return VTD_PE_GET_LEVEL(&pe);
977fb43cf73SLiu, Yi L     }
978fb43cf73SLiu, Yi L 
979fb43cf73SLiu, Yi L     return vtd_ce_get_level(ce);
980fb43cf73SLiu, Yi L }
981fb43cf73SLiu, Yi L 
vtd_ce_get_agaw(VTDContextEntry * ce)9828f7d7161SPeter Xu static inline uint32_t vtd_ce_get_agaw(VTDContextEntry *ce)
9831da12ec4SLe Tan {
9841da12ec4SLe Tan     return 30 + (ce->hi & VTD_CONTEXT_ENTRY_AW) * 9;
9851da12ec4SLe Tan }
9861da12ec4SLe Tan 
vtd_get_iova_agaw(IntelIOMMUState * s,VTDContextEntry * ce,uint32_t pasid)987fb43cf73SLiu, Yi L static uint32_t vtd_get_iova_agaw(IntelIOMMUState *s,
9881b2b1237SJason Wang                                   VTDContextEntry *ce,
9891b2b1237SJason Wang                                   uint32_t pasid)
990fb43cf73SLiu, Yi L {
991fb43cf73SLiu, Yi L     VTDPASIDEntry pe;
992fb43cf73SLiu, Yi L 
993fb43cf73SLiu, Yi L     if (s->root_scalable) {
9941b2b1237SJason Wang         vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
995fb43cf73SLiu, Yi L         return 30 + ((pe.val[0] >> 2) & VTD_SM_PASID_ENTRY_AW) * 9;
996fb43cf73SLiu, Yi L     }
997fb43cf73SLiu, Yi L 
998fb43cf73SLiu, Yi L     return vtd_ce_get_agaw(ce);
999fb43cf73SLiu, Yi L }
1000fb43cf73SLiu, Yi L 
vtd_ce_get_type(VTDContextEntry * ce)1001127ff5c3SPeter Xu static inline uint32_t vtd_ce_get_type(VTDContextEntry *ce)
1002127ff5c3SPeter Xu {
1003127ff5c3SPeter Xu     return ce->lo & VTD_CONTEXT_ENTRY_TT;
1004127ff5c3SPeter Xu }
1005127ff5c3SPeter Xu 
1006fb43cf73SLiu, Yi L /* Only for Legacy Mode. Return true if check passed, otherwise false */
vtd_ce_type_check(X86IOMMUState * x86_iommu,VTDContextEntry * ce)1007f80c9874SPeter Xu static inline bool vtd_ce_type_check(X86IOMMUState *x86_iommu,
1008f80c9874SPeter Xu                                      VTDContextEntry *ce)
1009f80c9874SPeter Xu {
1010f80c9874SPeter Xu     switch (vtd_ce_get_type(ce)) {
1011f80c9874SPeter Xu     case VTD_CONTEXT_TT_MULTI_LEVEL:
1012f80c9874SPeter Xu         /* Always supported */
1013f80c9874SPeter Xu         break;
1014f80c9874SPeter Xu     case VTD_CONTEXT_TT_DEV_IOTLB:
1015f80c9874SPeter Xu         if (!x86_iommu->dt_supported) {
1016095955b2SPeter Xu             error_report_once("%s: DT specified but not supported", __func__);
1017f80c9874SPeter Xu             return false;
1018f80c9874SPeter Xu         }
1019f80c9874SPeter Xu         break;
1020dbaabb25SPeter Xu     case VTD_CONTEXT_TT_PASS_THROUGH:
1021dbaabb25SPeter Xu         if (!x86_iommu->pt_supported) {
1022095955b2SPeter Xu             error_report_once("%s: PT specified but not supported", __func__);
1023dbaabb25SPeter Xu             return false;
1024dbaabb25SPeter Xu         }
1025dbaabb25SPeter Xu         break;
1026f80c9874SPeter Xu     default:
1027fb43cf73SLiu, Yi L         /* Unknown type */
1028095955b2SPeter Xu         error_report_once("%s: unknown ce type: %"PRIu32, __func__,
1029095955b2SPeter Xu                           vtd_ce_get_type(ce));
1030f80c9874SPeter Xu         return false;
1031f80c9874SPeter Xu     }
1032f80c9874SPeter Xu     return true;
1033f80c9874SPeter Xu }
1034f80c9874SPeter Xu 
vtd_iova_limit(IntelIOMMUState * s,VTDContextEntry * ce,uint8_t aw,uint32_t pasid)1035fb43cf73SLiu, Yi L static inline uint64_t vtd_iova_limit(IntelIOMMUState *s,
10361b2b1237SJason Wang                                       VTDContextEntry *ce, uint8_t aw,
10371b2b1237SJason Wang                                       uint32_t pasid)
1038f06a696dSPeter Xu {
10391b2b1237SJason Wang     uint32_t ce_agaw = vtd_get_iova_agaw(s, ce, pasid);
104037f51384SPrasad Singamsetty     return 1ULL << MIN(ce_agaw, aw);
1041f06a696dSPeter Xu }
1042f06a696dSPeter Xu 
1043f06a696dSPeter Xu /* Return true if IOVA passes range check, otherwise false. */
vtd_iova_range_check(IntelIOMMUState * s,uint64_t iova,VTDContextEntry * ce,uint8_t aw,uint32_t pasid)1044fb43cf73SLiu, Yi L static inline bool vtd_iova_range_check(IntelIOMMUState *s,
1045fb43cf73SLiu, Yi L                                         uint64_t iova, VTDContextEntry *ce,
10461b2b1237SJason Wang                                         uint8_t aw, uint32_t pasid)
1047f06a696dSPeter Xu {
1048f06a696dSPeter Xu     /*
1049f06a696dSPeter Xu      * Check if @iova is above 2^X-1, where X is the minimum of MGAW
1050f06a696dSPeter Xu      * in CAP_REG and AW in context-entry.
1051f06a696dSPeter Xu      */
10521b2b1237SJason Wang     return !(iova & ~(vtd_iova_limit(s, ce, aw, pasid) - 1));
1053fb43cf73SLiu, Yi L }
1054fb43cf73SLiu, Yi L 
vtd_get_iova_pgtbl_base(IntelIOMMUState * s,VTDContextEntry * ce,uint32_t pasid)1055fb43cf73SLiu, Yi L static dma_addr_t vtd_get_iova_pgtbl_base(IntelIOMMUState *s,
10561b2b1237SJason Wang                                           VTDContextEntry *ce,
10571b2b1237SJason Wang                                           uint32_t pasid)
1058fb43cf73SLiu, Yi L {
1059fb43cf73SLiu, Yi L     VTDPASIDEntry pe;
1060fb43cf73SLiu, Yi L 
1061fb43cf73SLiu, Yi L     if (s->root_scalable) {
10621b2b1237SJason Wang         vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
1063fb43cf73SLiu, Yi L         return pe.val[0] & VTD_SM_PASID_ENTRY_SLPTPTR;
1064fb43cf73SLiu, Yi L     }
1065fb43cf73SLiu, Yi L 
1066fb43cf73SLiu, Yi L     return vtd_ce_get_slpt_base(ce);
1067f06a696dSPeter Xu }
1068f06a696dSPeter Xu 
106992e5d85eSPrasad Singamsetty /*
107092e5d85eSPrasad Singamsetty  * Rsvd field masks for spte:
1071ce586f3bSQi, Yadong  *     vtd_spte_rsvd 4k pages
1072ce586f3bSQi, Yadong  *     vtd_spte_rsvd_large large pages
1073212c5fe1SVladimir Sementsov-Ogievskiy  *
1074212c5fe1SVladimir Sementsov-Ogievskiy  * We support only 3-level and 4-level page tables (see vtd_init() which
1075212c5fe1SVladimir Sementsov-Ogievskiy  * sets only VTD_CAP_SAGAW_39bit and maybe VTD_CAP_SAGAW_48bit bits in s->cap).
107692e5d85eSPrasad Singamsetty  */
1077212c5fe1SVladimir Sementsov-Ogievskiy #define VTD_SPTE_RSVD_LEN 5
1078212c5fe1SVladimir Sementsov-Ogievskiy static uint64_t vtd_spte_rsvd[VTD_SPTE_RSVD_LEN];
1079212c5fe1SVladimir Sementsov-Ogievskiy static uint64_t vtd_spte_rsvd_large[VTD_SPTE_RSVD_LEN];
10801da12ec4SLe Tan 
vtd_slpte_nonzero_rsvd(uint64_t slpte,uint32_t level)10811da12ec4SLe Tan static bool vtd_slpte_nonzero_rsvd(uint64_t slpte, uint32_t level)
10821da12ec4SLe Tan {
1083212c5fe1SVladimir Sementsov-Ogievskiy     uint64_t rsvd_mask;
1084212c5fe1SVladimir Sementsov-Ogievskiy 
1085212c5fe1SVladimir Sementsov-Ogievskiy     /*
1086212c5fe1SVladimir Sementsov-Ogievskiy      * We should have caught a guest-mis-programmed level earlier,
1087212c5fe1SVladimir Sementsov-Ogievskiy      * via vtd_is_level_supported.
1088212c5fe1SVladimir Sementsov-Ogievskiy      */
1089212c5fe1SVladimir Sementsov-Ogievskiy     assert(level < VTD_SPTE_RSVD_LEN);
1090212c5fe1SVladimir Sementsov-Ogievskiy     /*
1091212c5fe1SVladimir Sementsov-Ogievskiy      * Zero level doesn't exist. The smallest level is VTD_SL_PT_LEVEL=1 and
1092212c5fe1SVladimir Sementsov-Ogievskiy      * checked by vtd_is_last_slpte().
1093212c5fe1SVladimir Sementsov-Ogievskiy      */
1094212c5fe1SVladimir Sementsov-Ogievskiy     assert(level);
1095ce586f3bSQi, Yadong 
1096ce586f3bSQi, Yadong     if ((level == VTD_SL_PD_LEVEL || level == VTD_SL_PDP_LEVEL) &&
1097ce586f3bSQi, Yadong         (slpte & VTD_SL_PT_PAGE_SIZE_MASK)) {
1098ce586f3bSQi, Yadong         /* large page */
1099ce586f3bSQi, Yadong         rsvd_mask = vtd_spte_rsvd_large[level];
1100212c5fe1SVladimir Sementsov-Ogievskiy     } else {
1101212c5fe1SVladimir Sementsov-Ogievskiy         rsvd_mask = vtd_spte_rsvd[level];
11021da12ec4SLe Tan     }
1103ce586f3bSQi, Yadong 
1104ce586f3bSQi, Yadong     return slpte & rsvd_mask;
11051da12ec4SLe Tan }
11061da12ec4SLe Tan 
11076e905564SPeter Xu /* Given the @iova, get relevant @slptep. @slpte_level will be the last level
11081da12ec4SLe Tan  * of the translation, can be used for deciding the size of large page.
11091da12ec4SLe Tan  */
vtd_iova_to_slpte(IntelIOMMUState * s,VTDContextEntry * ce,uint64_t iova,bool is_write,uint64_t * slptep,uint32_t * slpte_level,bool * reads,bool * writes,uint8_t aw_bits,uint32_t pasid)1110fb43cf73SLiu, Yi L static int vtd_iova_to_slpte(IntelIOMMUState *s, VTDContextEntry *ce,
1111fb43cf73SLiu, Yi L                              uint64_t iova, bool is_write,
11121da12ec4SLe Tan                              uint64_t *slptep, uint32_t *slpte_level,
11131b2b1237SJason Wang                              bool *reads, bool *writes, uint8_t aw_bits,
11141b2b1237SJason Wang                              uint32_t pasid)
11151da12ec4SLe Tan {
11161b2b1237SJason Wang     dma_addr_t addr = vtd_get_iova_pgtbl_base(s, ce, pasid);
11171b2b1237SJason Wang     uint32_t level = vtd_get_iova_level(s, ce, pasid);
11181da12ec4SLe Tan     uint32_t offset;
11191da12ec4SLe Tan     uint64_t slpte;
11201da12ec4SLe Tan     uint64_t access_right_check;
1121ea97a1bdSJason Wang     uint64_t xlat, size;
11221da12ec4SLe Tan 
11231b2b1237SJason Wang     if (!vtd_iova_range_check(s, iova, ce, aw_bits, pasid)) {
11241b2b1237SJason Wang         error_report_once("%s: detected IOVA overflow (iova=0x%" PRIx64 ","
11251b2b1237SJason Wang                           "pasid=0x%" PRIx32 ")", __func__, iova, pasid);
11261da12ec4SLe Tan         return -VTD_FR_ADDR_BEYOND_MGAW;
11271da12ec4SLe Tan     }
11281da12ec4SLe Tan 
11291da12ec4SLe Tan     /* FIXME: what is the Atomics request here? */
11301da12ec4SLe Tan     access_right_check = is_write ? VTD_SL_W : VTD_SL_R;
11311da12ec4SLe Tan 
11321da12ec4SLe Tan     while (true) {
11336e905564SPeter Xu         offset = vtd_iova_level_offset(iova, level);
11341da12ec4SLe Tan         slpte = vtd_get_slpte(addr, offset);
11351da12ec4SLe Tan 
11361da12ec4SLe Tan         if (slpte == (uint64_t)-1) {
11374e4abd11SPeter Xu             error_report_once("%s: detected read error on DMAR slpte "
11381b2b1237SJason Wang                               "(iova=0x%" PRIx64 ", pasid=0x%" PRIx32 ")",
11391b2b1237SJason Wang                               __func__, iova, pasid);
11401b2b1237SJason Wang             if (level == vtd_get_iova_level(s, ce, pasid)) {
11411da12ec4SLe Tan                 /* Invalid programming of context-entry */
11421da12ec4SLe Tan                 return -VTD_FR_CONTEXT_ENTRY_INV;
11431da12ec4SLe Tan             } else {
11441da12ec4SLe Tan                 return -VTD_FR_PAGING_ENTRY_INV;
11451da12ec4SLe Tan             }
11461da12ec4SLe Tan         }
11471da12ec4SLe Tan         *reads = (*reads) && (slpte & VTD_SL_R);
11481da12ec4SLe Tan         *writes = (*writes) && (slpte & VTD_SL_W);
11491da12ec4SLe Tan         if (!(slpte & access_right_check)) {
11504e4abd11SPeter Xu             error_report_once("%s: detected slpte permission error "
11514e4abd11SPeter Xu                               "(iova=0x%" PRIx64 ", level=0x%" PRIx32 ", "
11521b2b1237SJason Wang                               "slpte=0x%" PRIx64 ", write=%d, pasid=0x%"
11531b2b1237SJason Wang                               PRIx32 ")", __func__, iova, level,
11541b2b1237SJason Wang                               slpte, is_write, pasid);
11551da12ec4SLe Tan             return is_write ? -VTD_FR_WRITE : -VTD_FR_READ;
11561da12ec4SLe Tan         }
11571da12ec4SLe Tan         if (vtd_slpte_nonzero_rsvd(slpte, level)) {
11584e4abd11SPeter Xu             error_report_once("%s: detected splte reserve non-zero "
11594e4abd11SPeter Xu                               "iova=0x%" PRIx64 ", level=0x%" PRIx32
11601b2b1237SJason Wang                               "slpte=0x%" PRIx64 ", pasid=0x%" PRIX32 ")",
11611b2b1237SJason Wang                               __func__, iova, level, slpte, pasid);
11621da12ec4SLe Tan             return -VTD_FR_PAGING_ENTRY_RSVD;
11631da12ec4SLe Tan         }
11641da12ec4SLe Tan 
11651da12ec4SLe Tan         if (vtd_is_last_slpte(slpte, level)) {
11661da12ec4SLe Tan             *slptep = slpte;
11671da12ec4SLe Tan             *slpte_level = level;
1168ea97a1bdSJason Wang             break;
11691da12ec4SLe Tan         }
117037f51384SPrasad Singamsetty         addr = vtd_get_slpte_addr(slpte, aw_bits);
11711da12ec4SLe Tan         level--;
11721da12ec4SLe Tan     }
1173ea97a1bdSJason Wang 
1174ea97a1bdSJason Wang     xlat = vtd_get_slpte_addr(*slptep, aw_bits);
1175ea97a1bdSJason Wang     size = ~vtd_slpt_level_page_mask(level) + 1;
1176ea97a1bdSJason Wang 
1177ea97a1bdSJason Wang     /*
1178ea97a1bdSJason Wang      * From VT-d spec 3.14: Untranslated requests and translation
1179ea97a1bdSJason Wang      * requests that result in an address in the interrupt range will be
1180ea97a1bdSJason Wang      * blocked with condition code LGN.4 or SGN.8.
1181ea97a1bdSJason Wang      */
1182ea97a1bdSJason Wang     if ((xlat > VTD_INTERRUPT_ADDR_LAST ||
1183ea97a1bdSJason Wang          xlat + size - 1 < VTD_INTERRUPT_ADDR_FIRST)) {
1184ea97a1bdSJason Wang         return 0;
1185ea97a1bdSJason Wang     } else {
1186ea97a1bdSJason Wang         error_report_once("%s: xlat address is in interrupt range "
1187ea97a1bdSJason Wang                           "(iova=0x%" PRIx64 ", level=0x%" PRIx32 ", "
1188ea97a1bdSJason Wang                           "slpte=0x%" PRIx64 ", write=%d, "
11891b2b1237SJason Wang                           "xlat=0x%" PRIx64 ", size=0x%" PRIx64 ", "
11901b2b1237SJason Wang                           "pasid=0x%" PRIx32 ")",
1191ea97a1bdSJason Wang                           __func__, iova, level, slpte, is_write,
11921b2b1237SJason Wang                           xlat, size, pasid);
1193ea97a1bdSJason Wang         return s->scalable_mode ? -VTD_FR_SM_INTERRUPT_ADDR :
1194ea97a1bdSJason Wang                                   -VTD_FR_INTERRUPT_ADDR;
1195ea97a1bdSJason Wang     }
11961da12ec4SLe Tan }
11971da12ec4SLe Tan 
1198fc9ad5cfSPhilippe Mathieu-Daudé typedef int (*vtd_page_walk_hook)(const IOMMUTLBEvent *event, void *private);
1199f06a696dSPeter Xu 
1200fe215b0cSPeter Xu /**
1201fe215b0cSPeter Xu  * Constant information used during page walking
1202fe215b0cSPeter Xu  *
1203fe215b0cSPeter Xu  * @hook_fn: hook func to be called when detected page
1204fe215b0cSPeter Xu  * @private: private data to be passed into hook func
1205fe215b0cSPeter Xu  * @notify_unmap: whether we should notify invalid entries
12062f764fa8SPeter Xu  * @as: VT-d address space of the device
1207fe215b0cSPeter Xu  * @aw: maximum address width
1208d118c06eSPeter Xu  * @domain: domain ID of the page walk
1209fe215b0cSPeter Xu  */
1210fe215b0cSPeter Xu typedef struct {
12112f764fa8SPeter Xu     VTDAddressSpace *as;
1212fe215b0cSPeter Xu     vtd_page_walk_hook hook_fn;
1213fe215b0cSPeter Xu     void *private;
1214fe215b0cSPeter Xu     bool notify_unmap;
1215fe215b0cSPeter Xu     uint8_t aw;
1216d118c06eSPeter Xu     uint16_t domain_id;
1217fe215b0cSPeter Xu } vtd_page_walk_info;
1218fe215b0cSPeter Xu 
vtd_page_walk_one(IOMMUTLBEvent * event,vtd_page_walk_info * info)12195039caf3SEugenio Pérez static int vtd_page_walk_one(IOMMUTLBEvent *event, vtd_page_walk_info *info)
122036d2d52bSPeter Xu {
122163b88968SPeter Xu     VTDAddressSpace *as = info->as;
1222fe215b0cSPeter Xu     vtd_page_walk_hook hook_fn = info->hook_fn;
1223fe215b0cSPeter Xu     void *private = info->private;
12245039caf3SEugenio Pérez     IOMMUTLBEntry *entry = &event->entry;
122563b88968SPeter Xu     DMAMap target = {
122663b88968SPeter Xu         .iova = entry->iova,
122763b88968SPeter Xu         .size = entry->addr_mask,
122863b88968SPeter Xu         .translated_addr = entry->translated_addr,
122963b88968SPeter Xu         .perm = entry->perm,
123063b88968SPeter Xu     };
1231a89b34beSEugenio Pérez     const DMAMap *mapped = iova_tree_find(as->iova_tree, &target);
123263b88968SPeter Xu 
12335039caf3SEugenio Pérez     if (event->type == IOMMU_NOTIFIER_UNMAP && !info->notify_unmap) {
123463b88968SPeter Xu         trace_vtd_page_walk_one_skip_unmap(entry->iova, entry->addr_mask);
123563b88968SPeter Xu         return 0;
123663b88968SPeter Xu     }
1237fe215b0cSPeter Xu 
123836d2d52bSPeter Xu     assert(hook_fn);
123963b88968SPeter Xu 
124063b88968SPeter Xu     /* Update local IOVA mapped ranges */
12415039caf3SEugenio Pérez     if (event->type == IOMMU_NOTIFIER_MAP) {
124263b88968SPeter Xu         if (mapped) {
124363b88968SPeter Xu             /* If it's exactly the same translation, skip */
124463b88968SPeter Xu             if (!memcmp(mapped, &target, sizeof(target))) {
124563b88968SPeter Xu                 trace_vtd_page_walk_one_skip_map(entry->iova, entry->addr_mask,
124663b88968SPeter Xu                                                  entry->translated_addr);
124763b88968SPeter Xu                 return 0;
124863b88968SPeter Xu             } else {
124963b88968SPeter Xu                 /*
125063b88968SPeter Xu                  * Translation changed.  Normally this should not
125163b88968SPeter Xu                  * happen, but it can happen when with buggy guest
125263b88968SPeter Xu                  * OSes.  Note that there will be a small window that
125363b88968SPeter Xu                  * we don't have map at all.  But that's the best
125463b88968SPeter Xu                  * effort we can do.  The ideal way to emulate this is
125563b88968SPeter Xu                  * atomically modify the PTE to follow what has
125663b88968SPeter Xu                  * changed, but we can't.  One example is that vfio
125763b88968SPeter Xu                  * driver only has VFIO_IOMMU_[UN]MAP_DMA but no
125863b88968SPeter Xu                  * interface to modify a mapping (meanwhile it seems
125963b88968SPeter Xu                  * meaningless to even provide one).  Anyway, let's
126063b88968SPeter Xu                  * mark this as a TODO in case one day we'll have
126163b88968SPeter Xu                  * a better solution.
126263b88968SPeter Xu                  */
126363b88968SPeter Xu                 IOMMUAccessFlags cache_perm = entry->perm;
126463b88968SPeter Xu                 int ret;
126563b88968SPeter Xu 
126663b88968SPeter Xu                 /* Emulate an UNMAP */
12675039caf3SEugenio Pérez                 event->type = IOMMU_NOTIFIER_UNMAP;
126863b88968SPeter Xu                 entry->perm = IOMMU_NONE;
126963b88968SPeter Xu                 trace_vtd_page_walk_one(info->domain_id,
127063b88968SPeter Xu                                         entry->iova,
127163b88968SPeter Xu                                         entry->translated_addr,
127263b88968SPeter Xu                                         entry->addr_mask,
127363b88968SPeter Xu                                         entry->perm);
12745039caf3SEugenio Pérez                 ret = hook_fn(event, private);
127563b88968SPeter Xu                 if (ret) {
127663b88968SPeter Xu                     return ret;
127763b88968SPeter Xu                 }
127863b88968SPeter Xu                 /* Drop any existing mapping */
127969292a8eSEugenio Pérez                 iova_tree_remove(as->iova_tree, target);
12805039caf3SEugenio Pérez                 /* Recover the correct type */
12815039caf3SEugenio Pérez                 event->type = IOMMU_NOTIFIER_MAP;
128263b88968SPeter Xu                 entry->perm = cache_perm;
128363b88968SPeter Xu             }
128463b88968SPeter Xu         }
128563b88968SPeter Xu         iova_tree_insert(as->iova_tree, &target);
128663b88968SPeter Xu     } else {
128763b88968SPeter Xu         if (!mapped) {
128863b88968SPeter Xu             /* Skip since we didn't map this range at all */
128963b88968SPeter Xu             trace_vtd_page_walk_one_skip_unmap(entry->iova, entry->addr_mask);
129063b88968SPeter Xu             return 0;
129163b88968SPeter Xu         }
129269292a8eSEugenio Pérez         iova_tree_remove(as->iova_tree, target);
129363b88968SPeter Xu     }
129463b88968SPeter Xu 
1295d118c06eSPeter Xu     trace_vtd_page_walk_one(info->domain_id, entry->iova,
1296d118c06eSPeter Xu                             entry->translated_addr, entry->addr_mask,
1297d118c06eSPeter Xu                             entry->perm);
12985039caf3SEugenio Pérez     return hook_fn(event, private);
129936d2d52bSPeter Xu }
130036d2d52bSPeter Xu 
1301f06a696dSPeter Xu /**
1302f06a696dSPeter Xu  * vtd_page_walk_level - walk over specific level for IOVA range
1303f06a696dSPeter Xu  *
1304f06a696dSPeter Xu  * @addr: base GPA addr to start the walk
1305f06a696dSPeter Xu  * @start: IOVA range start address
1306f06a696dSPeter Xu  * @end: IOVA range end address (start <= addr < end)
1307f06a696dSPeter Xu  * @read: whether parent level has read permission
1308f06a696dSPeter Xu  * @write: whether parent level has write permission
1309fe215b0cSPeter Xu  * @info: constant information for the page walk
1310f06a696dSPeter Xu  */
vtd_page_walk_level(dma_addr_t addr,uint64_t start,uint64_t end,uint32_t level,bool read,bool write,vtd_page_walk_info * info)1311f06a696dSPeter Xu static int vtd_page_walk_level(dma_addr_t addr, uint64_t start,
1312fe215b0cSPeter Xu                                uint64_t end, uint32_t level, bool read,
1313fe215b0cSPeter Xu                                bool write, vtd_page_walk_info *info)
1314f06a696dSPeter Xu {
1315f06a696dSPeter Xu     bool read_cur, write_cur, entry_valid;
1316f06a696dSPeter Xu     uint32_t offset;
1317f06a696dSPeter Xu     uint64_t slpte;
1318f06a696dSPeter Xu     uint64_t subpage_size, subpage_mask;
13195039caf3SEugenio Pérez     IOMMUTLBEvent event;
1320f06a696dSPeter Xu     uint64_t iova = start;
1321f06a696dSPeter Xu     uint64_t iova_next;
1322f06a696dSPeter Xu     int ret = 0;
1323f06a696dSPeter Xu 
1324f06a696dSPeter Xu     trace_vtd_page_walk_level(addr, level, start, end);
1325f06a696dSPeter Xu 
1326f06a696dSPeter Xu     subpage_size = 1ULL << vtd_slpt_level_shift(level);
1327f06a696dSPeter Xu     subpage_mask = vtd_slpt_level_page_mask(level);
1328f06a696dSPeter Xu 
1329f06a696dSPeter Xu     while (iova < end) {
1330f06a696dSPeter Xu         iova_next = (iova & subpage_mask) + subpage_size;
1331f06a696dSPeter Xu 
1332f06a696dSPeter Xu         offset = vtd_iova_level_offset(iova, level);
1333f06a696dSPeter Xu         slpte = vtd_get_slpte(addr, offset);
1334f06a696dSPeter Xu 
1335f06a696dSPeter Xu         if (slpte == (uint64_t)-1) {
1336f06a696dSPeter Xu             trace_vtd_page_walk_skip_read(iova, iova_next);
1337f06a696dSPeter Xu             goto next;
1338f06a696dSPeter Xu         }
1339f06a696dSPeter Xu 
1340f06a696dSPeter Xu         if (vtd_slpte_nonzero_rsvd(slpte, level)) {
1341f06a696dSPeter Xu             trace_vtd_page_walk_skip_reserve(iova, iova_next);
1342f06a696dSPeter Xu             goto next;
1343f06a696dSPeter Xu         }
1344f06a696dSPeter Xu 
1345f06a696dSPeter Xu         /* Permissions are stacked with parents' */
1346f06a696dSPeter Xu         read_cur = read && (slpte & VTD_SL_R);
1347f06a696dSPeter Xu         write_cur = write && (slpte & VTD_SL_W);
1348f06a696dSPeter Xu 
1349f06a696dSPeter Xu         /*
1350f06a696dSPeter Xu          * As long as we have either read/write permission, this is a
1351f06a696dSPeter Xu          * valid entry. The rule works for both page entries and page
1352f06a696dSPeter Xu          * table entries.
1353f06a696dSPeter Xu          */
1354f06a696dSPeter Xu         entry_valid = read_cur | write_cur;
1355f06a696dSPeter Xu 
135663b88968SPeter Xu         if (!vtd_is_last_slpte(slpte, level) && entry_valid) {
135763b88968SPeter Xu             /*
135863b88968SPeter Xu              * This is a valid PDE (or even bigger than PDE).  We need
135963b88968SPeter Xu              * to walk one further level.
136063b88968SPeter Xu              */
136163b88968SPeter Xu             ret = vtd_page_walk_level(vtd_get_slpte_addr(slpte, info->aw),
136263b88968SPeter Xu                                       iova, MIN(iova_next, end), level - 1,
136363b88968SPeter Xu                                       read_cur, write_cur, info);
136463b88968SPeter Xu         } else {
136563b88968SPeter Xu             /*
136663b88968SPeter Xu              * This means we are either:
136763b88968SPeter Xu              *
136863b88968SPeter Xu              * (1) the real page entry (either 4K page, or huge page)
136963b88968SPeter Xu              * (2) the whole range is invalid
137063b88968SPeter Xu              *
137163b88968SPeter Xu              * In either case, we send an IOTLB notification down.
137263b88968SPeter Xu              */
13735039caf3SEugenio Pérez             event.entry.target_as = &address_space_memory;
13745039caf3SEugenio Pérez             event.entry.iova = iova & subpage_mask;
13755039caf3SEugenio Pérez             event.entry.perm = IOMMU_ACCESS_FLAG(read_cur, write_cur);
13765039caf3SEugenio Pérez             event.entry.addr_mask = ~subpage_mask;
1377f06a696dSPeter Xu             /* NOTE: this is only meaningful if entry_valid == true */
13785039caf3SEugenio Pérez             event.entry.translated_addr = vtd_get_slpte_addr(slpte, info->aw);
13795039caf3SEugenio Pérez             event.type = event.entry.perm ? IOMMU_NOTIFIER_MAP :
13805039caf3SEugenio Pérez                                             IOMMU_NOTIFIER_UNMAP;
13815039caf3SEugenio Pérez             ret = vtd_page_walk_one(&event, info);
138263b88968SPeter Xu         }
138363b88968SPeter Xu 
1384f06a696dSPeter Xu         if (ret < 0) {
1385f06a696dSPeter Xu             return ret;
1386f06a696dSPeter Xu         }
1387f06a696dSPeter Xu 
1388f06a696dSPeter Xu next:
1389f06a696dSPeter Xu         iova = iova_next;
1390f06a696dSPeter Xu     }
1391f06a696dSPeter Xu 
1392f06a696dSPeter Xu     return 0;
1393f06a696dSPeter Xu }
1394f06a696dSPeter Xu 
1395f06a696dSPeter Xu /**
1396f06a696dSPeter Xu  * vtd_page_walk - walk specific IOVA range, and call the hook
1397f06a696dSPeter Xu  *
1398fb43cf73SLiu, Yi L  * @s: intel iommu state
1399f06a696dSPeter Xu  * @ce: context entry to walk upon
1400f06a696dSPeter Xu  * @start: IOVA address to start the walk
1401f06a696dSPeter Xu  * @end: IOVA range end address (start <= addr < end)
1402fe215b0cSPeter Xu  * @info: page walking information struct
1403f06a696dSPeter Xu  */
vtd_page_walk(IntelIOMMUState * s,VTDContextEntry * ce,uint64_t start,uint64_t end,vtd_page_walk_info * info,uint32_t pasid)1404fb43cf73SLiu, Yi L static int vtd_page_walk(IntelIOMMUState *s, VTDContextEntry *ce,
1405fb43cf73SLiu, Yi L                          uint64_t start, uint64_t end,
14061b2b1237SJason Wang                          vtd_page_walk_info *info,
14071b2b1237SJason Wang                          uint32_t pasid)
1408f06a696dSPeter Xu {
14091b2b1237SJason Wang     dma_addr_t addr = vtd_get_iova_pgtbl_base(s, ce, pasid);
14101b2b1237SJason Wang     uint32_t level = vtd_get_iova_level(s, ce, pasid);
1411f06a696dSPeter Xu 
14121b2b1237SJason Wang     if (!vtd_iova_range_check(s, start, ce, info->aw, pasid)) {
1413f06a696dSPeter Xu         return -VTD_FR_ADDR_BEYOND_MGAW;
1414f06a696dSPeter Xu     }
1415f06a696dSPeter Xu 
14161b2b1237SJason Wang     if (!vtd_iova_range_check(s, end, ce, info->aw, pasid)) {
1417f06a696dSPeter Xu         /* Fix end so that it reaches the maximum */
14181b2b1237SJason Wang         end = vtd_iova_limit(s, ce, info->aw, pasid);
1419f06a696dSPeter Xu     }
1420f06a696dSPeter Xu 
1421fe215b0cSPeter Xu     return vtd_page_walk_level(addr, start, end, level, true, true, info);
1422f06a696dSPeter Xu }
1423f06a696dSPeter Xu 
vtd_root_entry_rsvd_bits_check(IntelIOMMUState * s,VTDRootEntry * re)1424fb43cf73SLiu, Yi L static int vtd_root_entry_rsvd_bits_check(IntelIOMMUState *s,
1425fb43cf73SLiu, Yi L                                           VTDRootEntry *re)
1426fb43cf73SLiu, Yi L {
1427fb43cf73SLiu, Yi L     /* Legacy Mode reserved bits check */
1428fb43cf73SLiu, Yi L     if (!s->root_scalable &&
1429fb43cf73SLiu, Yi L         (re->hi || (re->lo & VTD_ROOT_ENTRY_RSVD(s->aw_bits))))
1430fb43cf73SLiu, Yi L         goto rsvd_err;
1431fb43cf73SLiu, Yi L 
1432fb43cf73SLiu, Yi L     /* Scalable Mode reserved bits check */
1433fb43cf73SLiu, Yi L     if (s->root_scalable &&
1434fb43cf73SLiu, Yi L         ((re->lo & VTD_ROOT_ENTRY_RSVD(s->aw_bits)) ||
1435fb43cf73SLiu, Yi L          (re->hi & VTD_ROOT_ENTRY_RSVD(s->aw_bits))))
1436fb43cf73SLiu, Yi L         goto rsvd_err;
1437fb43cf73SLiu, Yi L 
1438fb43cf73SLiu, Yi L     return 0;
1439fb43cf73SLiu, Yi L 
1440fb43cf73SLiu, Yi L rsvd_err:
1441fb43cf73SLiu, Yi L     error_report_once("%s: invalid root entry: hi=0x%"PRIx64
1442fb43cf73SLiu, Yi L                       ", lo=0x%"PRIx64,
1443fb43cf73SLiu, Yi L                       __func__, re->hi, re->lo);
1444fb43cf73SLiu, Yi L     return -VTD_FR_ROOT_ENTRY_RSVD;
1445fb43cf73SLiu, Yi L }
1446fb43cf73SLiu, Yi L 
vtd_context_entry_rsvd_bits_check(IntelIOMMUState * s,VTDContextEntry * ce)1447fb43cf73SLiu, Yi L static inline int vtd_context_entry_rsvd_bits_check(IntelIOMMUState *s,
1448fb43cf73SLiu, Yi L                                                     VTDContextEntry *ce)
1449fb43cf73SLiu, Yi L {
1450fb43cf73SLiu, Yi L     if (!s->root_scalable &&
1451fb43cf73SLiu, Yi L         (ce->hi & VTD_CONTEXT_ENTRY_RSVD_HI ||
1452fb43cf73SLiu, Yi L          ce->lo & VTD_CONTEXT_ENTRY_RSVD_LO(s->aw_bits))) {
1453fb43cf73SLiu, Yi L         error_report_once("%s: invalid context entry: hi=%"PRIx64
1454fb43cf73SLiu, Yi L                           ", lo=%"PRIx64" (reserved nonzero)",
1455fb43cf73SLiu, Yi L                           __func__, ce->hi, ce->lo);
1456fb43cf73SLiu, Yi L         return -VTD_FR_CONTEXT_ENTRY_RSVD;
1457fb43cf73SLiu, Yi L     }
1458fb43cf73SLiu, Yi L 
1459fb43cf73SLiu, Yi L     if (s->root_scalable &&
1460fb43cf73SLiu, Yi L         (ce->val[0] & VTD_SM_CONTEXT_ENTRY_RSVD_VAL0(s->aw_bits) ||
1461fb43cf73SLiu, Yi L          ce->val[1] & VTD_SM_CONTEXT_ENTRY_RSVD_VAL1 ||
1462fb43cf73SLiu, Yi L          ce->val[2] ||
1463fb43cf73SLiu, Yi L          ce->val[3])) {
1464fb43cf73SLiu, Yi L         error_report_once("%s: invalid context entry: val[3]=%"PRIx64
1465fb43cf73SLiu, Yi L                           ", val[2]=%"PRIx64
1466fb43cf73SLiu, Yi L                           ", val[1]=%"PRIx64
1467fb43cf73SLiu, Yi L                           ", val[0]=%"PRIx64" (reserved nonzero)",
1468fb43cf73SLiu, Yi L                           __func__, ce->val[3], ce->val[2],
1469fb43cf73SLiu, Yi L                           ce->val[1], ce->val[0]);
1470fb43cf73SLiu, Yi L         return -VTD_FR_CONTEXT_ENTRY_RSVD;
1471fb43cf73SLiu, Yi L     }
1472fb43cf73SLiu, Yi L 
1473fb43cf73SLiu, Yi L     return 0;
1474fb43cf73SLiu, Yi L }
1475fb43cf73SLiu, Yi L 
vtd_ce_rid2pasid_check(IntelIOMMUState * s,VTDContextEntry * ce)1476fb43cf73SLiu, Yi L static int vtd_ce_rid2pasid_check(IntelIOMMUState *s,
1477fb43cf73SLiu, Yi L                                   VTDContextEntry *ce)
1478fb43cf73SLiu, Yi L {
1479fb43cf73SLiu, Yi L     VTDPASIDEntry pe;
1480fb43cf73SLiu, Yi L 
1481fb43cf73SLiu, Yi L     /*
1482fb43cf73SLiu, Yi L      * Make sure in Scalable Mode, a present context entry
1483fb43cf73SLiu, Yi L      * has valid rid2pasid setting, which includes valid
1484fb43cf73SLiu, Yi L      * rid2pasid field and corresponding pasid entry setting
1485fb43cf73SLiu, Yi L      */
14861b2b1237SJason Wang     return vtd_ce_get_rid2pasid_entry(s, ce, &pe, PCI_NO_PASID);
1487fb43cf73SLiu, Yi L }
1488fb43cf73SLiu, Yi L 
14891da12ec4SLe Tan /* Map a device to its corresponding domain (context-entry) */
vtd_dev_to_context_entry(IntelIOMMUState * s,uint8_t bus_num,uint8_t devfn,VTDContextEntry * ce)14901da12ec4SLe Tan static int vtd_dev_to_context_entry(IntelIOMMUState *s, uint8_t bus_num,
14911da12ec4SLe Tan                                     uint8_t devfn, VTDContextEntry *ce)
14921da12ec4SLe Tan {
14931da12ec4SLe Tan     VTDRootEntry re;
14941da12ec4SLe Tan     int ret_fr;
1495f80c9874SPeter Xu     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
14961da12ec4SLe Tan 
14971da12ec4SLe Tan     ret_fr = vtd_get_root_entry(s, bus_num, &re);
14981da12ec4SLe Tan     if (ret_fr) {
14991da12ec4SLe Tan         return ret_fr;
15001da12ec4SLe Tan     }
15011da12ec4SLe Tan 
1502fb43cf73SLiu, Yi L     if (!vtd_root_entry_present(s, &re, devfn)) {
15036c441e1dSPeter Xu         /* Not error - it's okay we don't have root entry. */
15046c441e1dSPeter Xu         trace_vtd_re_not_present(bus_num);
15051da12ec4SLe Tan         return -VTD_FR_ROOT_ENTRY_P;
1506f80c9874SPeter Xu     }
1507f80c9874SPeter Xu 
1508fb43cf73SLiu, Yi L     ret_fr = vtd_root_entry_rsvd_bits_check(s, &re);
1509fb43cf73SLiu, Yi L     if (ret_fr) {
1510fb43cf73SLiu, Yi L         return ret_fr;
15111da12ec4SLe Tan     }
15121da12ec4SLe Tan 
1513fb43cf73SLiu, Yi L     ret_fr = vtd_get_context_entry_from_root(s, &re, devfn, ce);
15141da12ec4SLe Tan     if (ret_fr) {
15151da12ec4SLe Tan         return ret_fr;
15161da12ec4SLe Tan     }
15171da12ec4SLe Tan 
15188f7d7161SPeter Xu     if (!vtd_ce_present(ce)) {
15196c441e1dSPeter Xu         /* Not error - it's okay we don't have context entry. */
15206c441e1dSPeter Xu         trace_vtd_ce_not_present(bus_num, devfn);
15211da12ec4SLe Tan         return -VTD_FR_CONTEXT_ENTRY_P;
1522f80c9874SPeter Xu     }
1523f80c9874SPeter Xu 
1524fb43cf73SLiu, Yi L     ret_fr = vtd_context_entry_rsvd_bits_check(s, ce);
1525fb43cf73SLiu, Yi L     if (ret_fr) {
1526fb43cf73SLiu, Yi L         return ret_fr;
15271da12ec4SLe Tan     }
1528f80c9874SPeter Xu 
15291da12ec4SLe Tan     /* Check if the programming of context-entry is valid */
1530fb43cf73SLiu, Yi L     if (!s->root_scalable &&
1531fb43cf73SLiu, Yi L         !vtd_is_level_supported(s, vtd_ce_get_level(ce))) {
1532095955b2SPeter Xu         error_report_once("%s: invalid context entry: hi=%"PRIx64
1533095955b2SPeter Xu                           ", lo=%"PRIx64" (level %d not supported)",
1534fb43cf73SLiu, Yi L                           __func__, ce->hi, ce->lo,
1535fb43cf73SLiu, Yi L                           vtd_ce_get_level(ce));
15361da12ec4SLe Tan         return -VTD_FR_CONTEXT_ENTRY_INV;
1537f80c9874SPeter Xu     }
1538f80c9874SPeter Xu 
1539fb43cf73SLiu, Yi L     if (!s->root_scalable) {
1540f80c9874SPeter Xu         /* Do translation type check */
1541f80c9874SPeter Xu         if (!vtd_ce_type_check(x86_iommu, ce)) {
1542095955b2SPeter Xu             /* Errors dumped in vtd_ce_type_check() */
15431da12ec4SLe Tan             return -VTD_FR_CONTEXT_ENTRY_INV;
15441da12ec4SLe Tan         }
1545fb43cf73SLiu, Yi L     } else {
1546fb43cf73SLiu, Yi L         /*
1547fb43cf73SLiu, Yi L          * Check if the programming of context-entry.rid2pasid
1548fb43cf73SLiu, Yi L          * and corresponding pasid setting is valid, and thus
1549fb43cf73SLiu, Yi L          * avoids to check pasid entry fetching result in future
1550fb43cf73SLiu, Yi L          * helper function calling.
1551fb43cf73SLiu, Yi L          */
1552fb43cf73SLiu, Yi L         ret_fr = vtd_ce_rid2pasid_check(s, ce);
1553fb43cf73SLiu, Yi L         if (ret_fr) {
1554fb43cf73SLiu, Yi L             return ret_fr;
1555fb43cf73SLiu, Yi L         }
1556fb43cf73SLiu, Yi L     }
1557f80c9874SPeter Xu 
15581da12ec4SLe Tan     return 0;
15591da12ec4SLe Tan }
15601da12ec4SLe Tan 
vtd_sync_shadow_page_hook(const IOMMUTLBEvent * event,void * private)1561fc9ad5cfSPhilippe Mathieu-Daudé static int vtd_sync_shadow_page_hook(const IOMMUTLBEvent *event,
156263b88968SPeter Xu                                      void *private)
156363b88968SPeter Xu {
15645039caf3SEugenio Pérez     memory_region_notify_iommu(private, 0, *event);
156563b88968SPeter Xu     return 0;
156663b88968SPeter Xu }
156763b88968SPeter Xu 
vtd_get_domain_id(IntelIOMMUState * s,VTDContextEntry * ce,uint32_t pasid)1568fb43cf73SLiu, Yi L static uint16_t vtd_get_domain_id(IntelIOMMUState *s,
15691b2b1237SJason Wang                                   VTDContextEntry *ce,
15701b2b1237SJason Wang                                   uint32_t pasid)
1571fb43cf73SLiu, Yi L {
1572fb43cf73SLiu, Yi L     VTDPASIDEntry pe;
1573fb43cf73SLiu, Yi L 
1574fb43cf73SLiu, Yi L     if (s->root_scalable) {
15751b2b1237SJason Wang         vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
1576fb43cf73SLiu, Yi L         return VTD_SM_PASID_ENTRY_DID(pe.val[1]);
1577fb43cf73SLiu, Yi L     }
1578fb43cf73SLiu, Yi L 
1579fb43cf73SLiu, Yi L     return VTD_CONTEXT_ENTRY_DID(ce->hi);
1580fb43cf73SLiu, Yi L }
1581fb43cf73SLiu, Yi L 
vtd_sync_shadow_page_table_range(VTDAddressSpace * vtd_as,VTDContextEntry * ce,hwaddr addr,hwaddr size)158263b88968SPeter Xu static int vtd_sync_shadow_page_table_range(VTDAddressSpace *vtd_as,
158363b88968SPeter Xu                                             VTDContextEntry *ce,
158463b88968SPeter Xu                                             hwaddr addr, hwaddr size)
158563b88968SPeter Xu {
158663b88968SPeter Xu     IntelIOMMUState *s = vtd_as->iommu_state;
158763b88968SPeter Xu     vtd_page_walk_info info = {
158863b88968SPeter Xu         .hook_fn = vtd_sync_shadow_page_hook,
158963b88968SPeter Xu         .private = (void *)&vtd_as->iommu,
159063b88968SPeter Xu         .notify_unmap = true,
159163b88968SPeter Xu         .aw = s->aw_bits,
159263b88968SPeter Xu         .as = vtd_as,
15931b2b1237SJason Wang         .domain_id = vtd_get_domain_id(s, ce, vtd_as->pasid),
159463b88968SPeter Xu     };
159563b88968SPeter Xu 
15961b2b1237SJason Wang     return vtd_page_walk(s, ce, addr, addr + size, &info, vtd_as->pasid);
159763b88968SPeter Xu }
159863b88968SPeter Xu 
vtd_address_space_sync(VTDAddressSpace * vtd_as)15993e090e34SPeter Xu static int vtd_address_space_sync(VTDAddressSpace *vtd_as)
160063b88968SPeter Xu {
160195ecd3dfSPeter Xu     int ret;
160295ecd3dfSPeter Xu     VTDContextEntry ce;
1603c28b535dSPeter Xu     IOMMUNotifier *n;
160495ecd3dfSPeter Xu 
16053e090e34SPeter Xu     /* If no MAP notifier registered, we simply invalidate all the cache */
16063e090e34SPeter Xu     if (!vtd_as_has_map_notifier(vtd_as)) {
16073e090e34SPeter Xu         IOMMU_NOTIFIER_FOREACH(n, &vtd_as->iommu) {
16083e090e34SPeter Xu             memory_region_unmap_iommu_notifier_range(n);
16093e090e34SPeter Xu         }
1610f7701e2cSEugenio Pérez         return 0;
1611f7701e2cSEugenio Pérez     }
1612f7701e2cSEugenio Pérez 
161395ecd3dfSPeter Xu     ret = vtd_dev_to_context_entry(vtd_as->iommu_state,
161495ecd3dfSPeter Xu                                    pci_bus_num(vtd_as->bus),
161595ecd3dfSPeter Xu                                    vtd_as->devfn, &ce);
161695ecd3dfSPeter Xu     if (ret) {
1617c28b535dSPeter Xu         if (ret == -VTD_FR_CONTEXT_ENTRY_P) {
1618c28b535dSPeter Xu             /*
1619c28b535dSPeter Xu              * It's a valid scenario to have a context entry that is
1620c28b535dSPeter Xu              * not present.  For example, when a device is removed
1621c28b535dSPeter Xu              * from an existing domain then the context entry will be
1622c28b535dSPeter Xu              * zeroed by the guest before it was put into another
1623c28b535dSPeter Xu              * domain.  When this happens, instead of synchronizing
1624c28b535dSPeter Xu              * the shadow pages we should invalidate all existing
1625c28b535dSPeter Xu              * mappings and notify the backends.
1626c28b535dSPeter Xu              */
1627c28b535dSPeter Xu             IOMMU_NOTIFIER_FOREACH(n, &vtd_as->iommu) {
1628c28b535dSPeter Xu                 vtd_address_space_unmap(vtd_as, n);
1629c28b535dSPeter Xu             }
1630c28b535dSPeter Xu             ret = 0;
1631c28b535dSPeter Xu         }
163295ecd3dfSPeter Xu         return ret;
163395ecd3dfSPeter Xu     }
163495ecd3dfSPeter Xu 
163595ecd3dfSPeter Xu     return vtd_sync_shadow_page_table_range(vtd_as, &ce, 0, UINT64_MAX);
163663b88968SPeter Xu }
163763b88968SPeter Xu 
1638dbaabb25SPeter Xu /*
163937557b09SCai Huoqing  * Check if specific device is configured to bypass address
1640fb43cf73SLiu, Yi L  * translation for DMA requests. In Scalable Mode, bypass
1641fb43cf73SLiu, Yi L  * 1st-level translation or 2nd-level translation, it depends
1642fb43cf73SLiu, Yi L  * on PGTT setting.
1643dbaabb25SPeter Xu  */
vtd_dev_pt_enabled(IntelIOMMUState * s,VTDContextEntry * ce,uint32_t pasid)16441b2b1237SJason Wang static bool vtd_dev_pt_enabled(IntelIOMMUState *s, VTDContextEntry *ce,
16451b2b1237SJason Wang                                uint32_t pasid)
16465178d78fSJason Wang {
16475178d78fSJason Wang     VTDPASIDEntry pe;
16485178d78fSJason Wang     int ret;
16495178d78fSJason Wang 
16505178d78fSJason Wang     if (s->root_scalable) {
16511b2b1237SJason Wang         ret = vtd_ce_get_rid2pasid_entry(s, ce, &pe, pasid);
16525178d78fSJason Wang         if (ret) {
1653fb1d084bSJason Wang             /*
1654fb1d084bSJason Wang              * This error is guest triggerable. We should assumt PT
1655fb1d084bSJason Wang              * not enabled for safety.
1656fb1d084bSJason Wang              */
16575178d78fSJason Wang             return false;
16585178d78fSJason Wang         }
16595178d78fSJason Wang         return (VTD_PE_GET_TYPE(&pe) == VTD_SM_PASID_ENTRY_PT);
16605178d78fSJason Wang     }
16615178d78fSJason Wang 
16625178d78fSJason Wang     return (vtd_ce_get_type(ce) == VTD_CONTEXT_TT_PASS_THROUGH);
16635178d78fSJason Wang 
16645178d78fSJason Wang }
16655178d78fSJason Wang 
vtd_as_pt_enabled(VTDAddressSpace * as)16665178d78fSJason Wang static bool vtd_as_pt_enabled(VTDAddressSpace *as)
1667dbaabb25SPeter Xu {
1668dbaabb25SPeter Xu     IntelIOMMUState *s;
1669dbaabb25SPeter Xu     VTDContextEntry ce;
1670dbaabb25SPeter Xu 
1671dbaabb25SPeter Xu     assert(as);
1672dbaabb25SPeter Xu 
1673fb43cf73SLiu, Yi L     s = as->iommu_state;
1674fb1d084bSJason Wang     if (vtd_dev_to_context_entry(s, pci_bus_num(as->bus), as->devfn,
1675fb1d084bSJason Wang                                  &ce)) {
1676dbaabb25SPeter Xu         /*
1677dbaabb25SPeter Xu          * Possibly failed to parse the context entry for some reason
1678dbaabb25SPeter Xu          * (e.g., during init, or any guest configuration errors on
1679dbaabb25SPeter Xu          * context entries). We should assume PT not enabled for
1680dbaabb25SPeter Xu          * safety.
1681dbaabb25SPeter Xu          */
1682dbaabb25SPeter Xu         return false;
1683dbaabb25SPeter Xu     }
1684dbaabb25SPeter Xu 
16851b2b1237SJason Wang     return vtd_dev_pt_enabled(s, &ce, as->pasid);
1686dbaabb25SPeter Xu }
1687dbaabb25SPeter Xu 
1688dbaabb25SPeter Xu /* Return whether the device is using IOMMU translation. */
vtd_switch_address_space(VTDAddressSpace * as)1689dbaabb25SPeter Xu static bool vtd_switch_address_space(VTDAddressSpace *as)
1690dbaabb25SPeter Xu {
16911b2b1237SJason Wang     bool use_iommu, pt;
169266a4a031SPeter Xu     /* Whether we need to take the BQL on our own */
1693195801d7SStefan Hajnoczi     bool take_bql = !bql_locked();
1694dbaabb25SPeter Xu 
1695dbaabb25SPeter Xu     assert(as);
1696dbaabb25SPeter Xu 
16975178d78fSJason Wang     use_iommu = as->iommu_state->dmar_enabled && !vtd_as_pt_enabled(as);
16981b2b1237SJason Wang     pt = as->iommu_state->dmar_enabled && vtd_as_pt_enabled(as);
1699dbaabb25SPeter Xu 
1700dbaabb25SPeter Xu     trace_vtd_switch_address_space(pci_bus_num(as->bus),
1701dbaabb25SPeter Xu                                    VTD_PCI_SLOT(as->devfn),
1702dbaabb25SPeter Xu                                    VTD_PCI_FUNC(as->devfn),
1703dbaabb25SPeter Xu                                    use_iommu);
1704dbaabb25SPeter Xu 
170566a4a031SPeter Xu     /*
170666a4a031SPeter Xu      * It's possible that we reach here without BQL, e.g., when called
170766a4a031SPeter Xu      * from vtd_pt_enable_fast_path(). However the memory APIs need
170866a4a031SPeter Xu      * it. We'd better make sure we have had it already, or, take it.
170966a4a031SPeter Xu      */
171066a4a031SPeter Xu     if (take_bql) {
1711195801d7SStefan Hajnoczi         bql_lock();
171266a4a031SPeter Xu     }
171366a4a031SPeter Xu 
1714dbaabb25SPeter Xu     /* Turn off first then on the other */
1715dbaabb25SPeter Xu     if (use_iommu) {
17164b519ef1SPeter Xu         memory_region_set_enabled(&as->nodmar, false);
17173df9d748SAlexey Kardashevskiy         memory_region_set_enabled(MEMORY_REGION(&as->iommu), true);
17181b2b1237SJason Wang         /*
17191b2b1237SJason Wang          * vt-d spec v3.4 3.14:
17201b2b1237SJason Wang          *
17211b2b1237SJason Wang          * """
17221b2b1237SJason Wang          * Requests-with-PASID with input address in range 0xFEEx_xxxx
17231b2b1237SJason Wang          * are translated normally like any other request-with-PASID
17241b2b1237SJason Wang          * through DMA-remapping hardware.
17251b2b1237SJason Wang          * """
17261b2b1237SJason Wang          *
17271b2b1237SJason Wang          * Need to disable ir for as with PASID.
17281b2b1237SJason Wang          */
17291b2b1237SJason Wang         if (as->pasid != PCI_NO_PASID) {
17301b2b1237SJason Wang             memory_region_set_enabled(&as->iommu_ir, false);
17311b2b1237SJason Wang         } else {
17321b2b1237SJason Wang             memory_region_set_enabled(&as->iommu_ir, true);
17331b2b1237SJason Wang         }
1734dbaabb25SPeter Xu     } else {
17353df9d748SAlexey Kardashevskiy         memory_region_set_enabled(MEMORY_REGION(&as->iommu), false);
17364b519ef1SPeter Xu         memory_region_set_enabled(&as->nodmar, true);
1737dbaabb25SPeter Xu     }
1738dbaabb25SPeter Xu 
17391b2b1237SJason Wang     /*
17401b2b1237SJason Wang      * vtd-spec v3.4 3.14:
17411b2b1237SJason Wang      *
17421b2b1237SJason Wang      * """
17431b2b1237SJason Wang      * Requests-with-PASID with input address in range 0xFEEx_xxxx are
17441b2b1237SJason Wang      * translated normally like any other request-with-PASID through
17451b2b1237SJason Wang      * DMA-remapping hardware. However, if such a request is processed
17461b2b1237SJason Wang      * using pass-through translation, it will be blocked as described
17471b2b1237SJason Wang      * in the paragraph below.
17481b2b1237SJason Wang      *
17491b2b1237SJason Wang      * Software must not program paging-structure entries to remap any
17501b2b1237SJason Wang      * address to the interrupt address range. Untranslated requests
17511b2b1237SJason Wang      * and translation requests that result in an address in the
17521b2b1237SJason Wang      * interrupt range will be blocked with condition code LGN.4 or
17531b2b1237SJason Wang      * SGN.8.
17541b2b1237SJason Wang      * """
17551b2b1237SJason Wang      *
17561b2b1237SJason Wang      * We enable per as memory region (iommu_ir_fault) for catching
1757bad5cfcdSMichael Tokarev      * the translation for interrupt range through PASID + PT.
17581b2b1237SJason Wang      */
17591b2b1237SJason Wang     if (pt && as->pasid != PCI_NO_PASID) {
17601b2b1237SJason Wang         memory_region_set_enabled(&as->iommu_ir_fault, true);
17611b2b1237SJason Wang     } else {
17621b2b1237SJason Wang         memory_region_set_enabled(&as->iommu_ir_fault, false);
17631b2b1237SJason Wang     }
17641b2b1237SJason Wang 
176566a4a031SPeter Xu     if (take_bql) {
1766195801d7SStefan Hajnoczi         bql_unlock();
176766a4a031SPeter Xu     }
176866a4a031SPeter Xu 
1769dbaabb25SPeter Xu     return use_iommu;
1770dbaabb25SPeter Xu }
1771dbaabb25SPeter Xu 
vtd_switch_address_space_all(IntelIOMMUState * s)1772dbaabb25SPeter Xu static void vtd_switch_address_space_all(IntelIOMMUState *s)
1773dbaabb25SPeter Xu {
1774da8d439cSJason Wang     VTDAddressSpace *vtd_as;
1775dbaabb25SPeter Xu     GHashTableIter iter;
1776dbaabb25SPeter Xu 
1777da8d439cSJason Wang     g_hash_table_iter_init(&iter, s->vtd_address_spaces);
1778da8d439cSJason Wang     while (g_hash_table_iter_next(&iter, NULL, (void **)&vtd_as)) {
1779da8d439cSJason Wang         vtd_switch_address_space(vtd_as);
1780dbaabb25SPeter Xu     }
17811da12ec4SLe Tan }
17821da12ec4SLe Tan 
17831da12ec4SLe Tan static const bool vtd_qualified_faults[] = {
17841da12ec4SLe Tan     [VTD_FR_RESERVED] = false,
17851da12ec4SLe Tan     [VTD_FR_ROOT_ENTRY_P] = false,
17861da12ec4SLe Tan     [VTD_FR_CONTEXT_ENTRY_P] = true,
17871da12ec4SLe Tan     [VTD_FR_CONTEXT_ENTRY_INV] = true,
17881da12ec4SLe Tan     [VTD_FR_ADDR_BEYOND_MGAW] = true,
17891da12ec4SLe Tan     [VTD_FR_WRITE] = true,
17901da12ec4SLe Tan     [VTD_FR_READ] = true,
17911da12ec4SLe Tan     [VTD_FR_PAGING_ENTRY_INV] = true,
17921da12ec4SLe Tan     [VTD_FR_ROOT_TABLE_INV] = false,
17931da12ec4SLe Tan     [VTD_FR_CONTEXT_TABLE_INV] = false,
1794ea97a1bdSJason Wang     [VTD_FR_INTERRUPT_ADDR] = true,
17951da12ec4SLe Tan     [VTD_FR_ROOT_ENTRY_RSVD] = false,
17961da12ec4SLe Tan     [VTD_FR_PAGING_ENTRY_RSVD] = true,
17971da12ec4SLe Tan     [VTD_FR_CONTEXT_ENTRY_TT] = true,
1798fb43cf73SLiu, Yi L     [VTD_FR_PASID_TABLE_INV] = false,
1799ea97a1bdSJason Wang     [VTD_FR_SM_INTERRUPT_ADDR] = true,
18001da12ec4SLe Tan     [VTD_FR_MAX] = false,
18011da12ec4SLe Tan };
18021da12ec4SLe Tan 
18031da12ec4SLe Tan /* To see if a fault condition is "qualified", which is reported to software
18041da12ec4SLe Tan  * only if the FPD field in the context-entry used to process the faulting
18051da12ec4SLe Tan  * request is 0.
18061da12ec4SLe Tan  */
vtd_is_qualified_fault(VTDFaultReason fault)18071da12ec4SLe Tan static inline bool vtd_is_qualified_fault(VTDFaultReason fault)
18081da12ec4SLe Tan {
18091da12ec4SLe Tan     return vtd_qualified_faults[fault];
18101da12ec4SLe Tan }
18111da12ec4SLe Tan 
vtd_is_interrupt_addr(hwaddr addr)18121da12ec4SLe Tan static inline bool vtd_is_interrupt_addr(hwaddr addr)
18131da12ec4SLe Tan {
18141da12ec4SLe Tan     return VTD_INTERRUPT_ADDR_FIRST <= addr && addr <= VTD_INTERRUPT_ADDR_LAST;
18151da12ec4SLe Tan }
18161da12ec4SLe Tan 
vtd_find_as_by_sid(gpointer key,gpointer value,gpointer user_data)1817da8d439cSJason Wang static gboolean vtd_find_as_by_sid(gpointer key, gpointer value,
1818da8d439cSJason Wang                                    gpointer user_data)
1819da8d439cSJason Wang {
1820da8d439cSJason Wang     struct vtd_as_key *as_key = (struct vtd_as_key *)key;
1821da8d439cSJason Wang     uint16_t target_sid = *(uint16_t *)user_data;
1822da8d439cSJason Wang     uint16_t sid = PCI_BUILD_BDF(pci_bus_num(as_key->bus), as_key->devfn);
1823da8d439cSJason Wang     return sid == target_sid;
1824da8d439cSJason Wang }
1825da8d439cSJason Wang 
vtd_get_as_by_sid(IntelIOMMUState * s,uint16_t sid)1826da8d439cSJason Wang static VTDAddressSpace *vtd_get_as_by_sid(IntelIOMMUState *s, uint16_t sid)
1827da8d439cSJason Wang {
1828da8d439cSJason Wang     uint8_t bus_num = PCI_BUS_NUM(sid);
1829da8d439cSJason Wang     VTDAddressSpace *vtd_as = s->vtd_as_cache[bus_num];
1830da8d439cSJason Wang 
1831da8d439cSJason Wang     if (vtd_as &&
1832da8d439cSJason Wang         (sid == PCI_BUILD_BDF(pci_bus_num(vtd_as->bus), vtd_as->devfn))) {
1833da8d439cSJason Wang         return vtd_as;
1834da8d439cSJason Wang     }
1835da8d439cSJason Wang 
1836da8d439cSJason Wang     vtd_as = g_hash_table_find(s->vtd_address_spaces, vtd_find_as_by_sid, &sid);
1837da8d439cSJason Wang     s->vtd_as_cache[bus_num] = vtd_as;
1838da8d439cSJason Wang 
1839da8d439cSJason Wang     return vtd_as;
1840da8d439cSJason Wang }
1841da8d439cSJason Wang 
vtd_pt_enable_fast_path(IntelIOMMUState * s,uint16_t source_id)1842dbaabb25SPeter Xu static void vtd_pt_enable_fast_path(IntelIOMMUState *s, uint16_t source_id)
1843dbaabb25SPeter Xu {
1844dbaabb25SPeter Xu     VTDAddressSpace *vtd_as;
1845dbaabb25SPeter Xu     bool success = false;
1846dbaabb25SPeter Xu 
1847da8d439cSJason Wang     vtd_as = vtd_get_as_by_sid(s, source_id);
1848dbaabb25SPeter Xu     if (!vtd_as) {
1849dbaabb25SPeter Xu         goto out;
1850dbaabb25SPeter Xu     }
1851dbaabb25SPeter Xu 
1852dbaabb25SPeter Xu     if (vtd_switch_address_space(vtd_as) == false) {
1853dbaabb25SPeter Xu         /* We switched off IOMMU region successfully. */
1854dbaabb25SPeter Xu         success = true;
1855dbaabb25SPeter Xu     }
1856dbaabb25SPeter Xu 
1857dbaabb25SPeter Xu out:
1858dbaabb25SPeter Xu     trace_vtd_pt_enable_fast_path(source_id, success);
1859dbaabb25SPeter Xu }
1860dbaabb25SPeter Xu 
vtd_report_fault(IntelIOMMUState * s,int err,bool is_fpd_set,uint16_t source_id,hwaddr addr,bool is_write,bool is_pasid,uint32_t pasid)1861940e5527SJason Wang static void vtd_report_fault(IntelIOMMUState *s,
1862940e5527SJason Wang                              int err, bool is_fpd_set,
1863940e5527SJason Wang                              uint16_t source_id,
1864940e5527SJason Wang                              hwaddr addr,
18651b2b1237SJason Wang                              bool is_write,
18661b2b1237SJason Wang                              bool is_pasid,
18671b2b1237SJason Wang                              uint32_t pasid)
1868940e5527SJason Wang {
1869940e5527SJason Wang     if (is_fpd_set && vtd_is_qualified_fault(err)) {
1870940e5527SJason Wang         trace_vtd_fault_disabled();
1871940e5527SJason Wang     } else {
18721b2b1237SJason Wang         vtd_report_dmar_fault(s, source_id, addr, err, is_write,
18731b2b1237SJason Wang                               is_pasid, pasid);
1874940e5527SJason Wang     }
1875940e5527SJason Wang }
1876940e5527SJason Wang 
18771da12ec4SLe Tan /* Map dev to context-entry then do a paging-structures walk to do a iommu
18781da12ec4SLe Tan  * translation.
187979e2b9aeSPaolo Bonzini  *
188079e2b9aeSPaolo Bonzini  * Called from RCU critical section.
188179e2b9aeSPaolo Bonzini  *
18821da12ec4SLe Tan  * @bus_num: The bus number
18831da12ec4SLe Tan  * @devfn: The devfn, which is the  combined of device and function number
18841da12ec4SLe Tan  * @is_write: The access is a write operation
18851da12ec4SLe Tan  * @entry: IOMMUTLBEntry that contain the addr to be translated and result
1886b9313021SPeter Xu  *
1887b9313021SPeter Xu  * Returns true if translation is successful, otherwise false.
18881da12ec4SLe Tan  */
vtd_do_iommu_translate(VTDAddressSpace * vtd_as,PCIBus * bus,uint8_t devfn,hwaddr addr,bool is_write,IOMMUTLBEntry * entry)1889b9313021SPeter Xu static bool vtd_do_iommu_translate(VTDAddressSpace *vtd_as, PCIBus *bus,
18901da12ec4SLe Tan                                    uint8_t devfn, hwaddr addr, bool is_write,
18911da12ec4SLe Tan                                    IOMMUTLBEntry *entry)
18921da12ec4SLe Tan {
1893d92fa2dcSLe Tan     IntelIOMMUState *s = vtd_as->iommu_state;
18941da12ec4SLe Tan     VTDContextEntry ce;
18957df953bdSKnut Omang     uint8_t bus_num = pci_bus_num(bus);
18961d9efa73SPeter Xu     VTDContextCacheEntry *cc_entry;
1897d66b969bSJason Wang     uint64_t slpte, page_mask;
18981b2b1237SJason Wang     uint32_t level, pasid = vtd_as->pasid;
1899da8d439cSJason Wang     uint16_t source_id = PCI_BUILD_BDF(bus_num, devfn);
19001da12ec4SLe Tan     int ret_fr;
19011da12ec4SLe Tan     bool is_fpd_set = false;
19021da12ec4SLe Tan     bool reads = true;
19031da12ec4SLe Tan     bool writes = true;
190407f7b733SPeter Xu     uint8_t access_flags;
19051b2b1237SJason Wang     bool rid2pasid = (pasid == PCI_NO_PASID) && s->root_scalable;
1906b5a280c0SLe Tan     VTDIOTLBEntry *iotlb_entry;
19071da12ec4SLe Tan 
1908046ab7e9SPeter Xu     /*
1909046ab7e9SPeter Xu      * We have standalone memory region for interrupt addresses, we
1910046ab7e9SPeter Xu      * should never receive translation requests in this region.
19111da12ec4SLe Tan      */
1912046ab7e9SPeter Xu     assert(!vtd_is_interrupt_addr(addr));
1913046ab7e9SPeter Xu 
19141d9efa73SPeter Xu     vtd_iommu_lock(s);
19151d9efa73SPeter Xu 
19161d9efa73SPeter Xu     cc_entry = &vtd_as->context_cache_entry;
19171d9efa73SPeter Xu 
19181b2b1237SJason Wang     /* Try to fetch slpte form IOTLB, we don't need RID2PASID logic */
19191b2b1237SJason Wang     if (!rid2pasid) {
19201b2b1237SJason Wang         iotlb_entry = vtd_lookup_iotlb(s, source_id, pasid, addr);
1921b5a280c0SLe Tan         if (iotlb_entry) {
19226c441e1dSPeter Xu             trace_vtd_iotlb_page_hit(source_id, addr, iotlb_entry->slpte,
19236c441e1dSPeter Xu                                      iotlb_entry->domain_id);
1924b5a280c0SLe Tan             slpte = iotlb_entry->slpte;
192507f7b733SPeter Xu             access_flags = iotlb_entry->access_flags;
1926d66b969bSJason Wang             page_mask = iotlb_entry->mask;
1927b5a280c0SLe Tan             goto out;
1928b5a280c0SLe Tan         }
19291b2b1237SJason Wang     }
1930b9313021SPeter Xu 
1931d92fa2dcSLe Tan     /* Try to fetch context-entry from cache first */
1932d92fa2dcSLe Tan     if (cc_entry->context_cache_gen == s->context_cache_gen) {
19336c441e1dSPeter Xu         trace_vtd_iotlb_cc_hit(bus_num, devfn, cc_entry->context_entry.hi,
19346c441e1dSPeter Xu                                cc_entry->context_entry.lo,
19356c441e1dSPeter Xu                                cc_entry->context_cache_gen);
1936d92fa2dcSLe Tan         ce = cc_entry->context_entry;
1937d92fa2dcSLe Tan         is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;
1938fb43cf73SLiu, Yi L         if (!is_fpd_set && s->root_scalable) {
19391b2b1237SJason Wang             ret_fr = vtd_ce_get_pasid_fpd(s, &ce, &is_fpd_set, pasid);
1940940e5527SJason Wang             if (ret_fr) {
1941940e5527SJason Wang                 vtd_report_fault(s, -ret_fr, is_fpd_set,
19421b2b1237SJason Wang                                  source_id, addr, is_write,
19431b2b1237SJason Wang                                  false, 0);
1944940e5527SJason Wang                 goto error;
1945940e5527SJason Wang             }
1946fb43cf73SLiu, Yi L         }
1947d92fa2dcSLe Tan     } else {
19481da12ec4SLe Tan         ret_fr = vtd_dev_to_context_entry(s, bus_num, devfn, &ce);
19491da12ec4SLe Tan         is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;
1950fb43cf73SLiu, Yi L         if (!ret_fr && !is_fpd_set && s->root_scalable) {
19511b2b1237SJason Wang             ret_fr = vtd_ce_get_pasid_fpd(s, &ce, &is_fpd_set, pasid);
19521da12ec4SLe Tan         }
1953940e5527SJason Wang         if (ret_fr) {
1954940e5527SJason Wang             vtd_report_fault(s, -ret_fr, is_fpd_set,
19551b2b1237SJason Wang                              source_id, addr, is_write,
19561b2b1237SJason Wang                              false, 0);
1957940e5527SJason Wang             goto error;
1958940e5527SJason Wang         }
1959d92fa2dcSLe Tan         /* Update context-cache */
19606c441e1dSPeter Xu         trace_vtd_iotlb_cc_update(bus_num, devfn, ce.hi, ce.lo,
19616c441e1dSPeter Xu                                   cc_entry->context_cache_gen,
19626c441e1dSPeter Xu                                   s->context_cache_gen);
1963d92fa2dcSLe Tan         cc_entry->context_entry = ce;
1964d92fa2dcSLe Tan         cc_entry->context_cache_gen = s->context_cache_gen;
1965d92fa2dcSLe Tan     }
19661da12ec4SLe Tan 
19671b2b1237SJason Wang     if (rid2pasid) {
19681b2b1237SJason Wang         pasid = VTD_CE_GET_RID2PASID(&ce);
19691b2b1237SJason Wang     }
19701b2b1237SJason Wang 
1971dbaabb25SPeter Xu     /*
1972dbaabb25SPeter Xu      * We don't need to translate for pass-through context entries.
1973dbaabb25SPeter Xu      * Also, let's ignore IOTLB caching as well for PT devices.
1974dbaabb25SPeter Xu      */
19751b2b1237SJason Wang     if (vtd_dev_pt_enabled(s, &ce, pasid)) {
1976892721d9SPeter Xu         entry->iova = addr & VTD_PAGE_MASK_4K;
1977dbaabb25SPeter Xu         entry->translated_addr = entry->iova;
1978892721d9SPeter Xu         entry->addr_mask = ~VTD_PAGE_MASK_4K;
1979dbaabb25SPeter Xu         entry->perm = IOMMU_RW;
1980dbaabb25SPeter Xu         trace_vtd_translate_pt(source_id, entry->iova);
1981dbaabb25SPeter Xu 
1982dbaabb25SPeter Xu         /*
1983dbaabb25SPeter Xu          * When this happens, it means firstly caching-mode is not
1984dbaabb25SPeter Xu          * enabled, and this is the first passthrough translation for
1985dbaabb25SPeter Xu          * the device. Let's enable the fast path for passthrough.
1986dbaabb25SPeter Xu          *
1987dbaabb25SPeter Xu          * When passthrough is disabled again for the device, we can
1988dbaabb25SPeter Xu          * capture it via the context entry invalidation, then the
1989dbaabb25SPeter Xu          * IOMMU region can be swapped back.
1990dbaabb25SPeter Xu          */
1991dbaabb25SPeter Xu         vtd_pt_enable_fast_path(s, source_id);
19921d9efa73SPeter Xu         vtd_iommu_unlock(s);
1993b9313021SPeter Xu         return true;
1994dbaabb25SPeter Xu     }
1995dbaabb25SPeter Xu 
19961b2b1237SJason Wang     /* Try to fetch slpte form IOTLB for RID2PASID slow path */
19971b2b1237SJason Wang     if (rid2pasid) {
19981b2b1237SJason Wang         iotlb_entry = vtd_lookup_iotlb(s, source_id, pasid, addr);
19991b2b1237SJason Wang         if (iotlb_entry) {
20001b2b1237SJason Wang             trace_vtd_iotlb_page_hit(source_id, addr, iotlb_entry->slpte,
20011b2b1237SJason Wang                                      iotlb_entry->domain_id);
20021b2b1237SJason Wang             slpte = iotlb_entry->slpte;
20031b2b1237SJason Wang             access_flags = iotlb_entry->access_flags;
20041b2b1237SJason Wang             page_mask = iotlb_entry->mask;
20051b2b1237SJason Wang             goto out;
20061b2b1237SJason Wang         }
20071b2b1237SJason Wang     }
20081b2b1237SJason Wang 
2009fb43cf73SLiu, Yi L     ret_fr = vtd_iova_to_slpte(s, &ce, addr, is_write, &slpte, &level,
20101b2b1237SJason Wang                                &reads, &writes, s->aw_bits, pasid);
2011940e5527SJason Wang     if (ret_fr) {
2012940e5527SJason Wang         vtd_report_fault(s, -ret_fr, is_fpd_set, source_id,
20131b2b1237SJason Wang                          addr, is_write, pasid != PCI_NO_PASID, pasid);
2014940e5527SJason Wang         goto error;
2015940e5527SJason Wang     }
20161da12ec4SLe Tan 
2017d66b969bSJason Wang     page_mask = vtd_slpt_level_page_mask(level);
201807f7b733SPeter Xu     access_flags = IOMMU_ACCESS_FLAG(reads, writes);
20191b2b1237SJason Wang     vtd_update_iotlb(s, source_id, vtd_get_domain_id(s, &ce, pasid),
20201b2b1237SJason Wang                      addr, slpte, access_flags, level, pasid);
2021b5a280c0SLe Tan out:
20221d9efa73SPeter Xu     vtd_iommu_unlock(s);
2023d66b969bSJason Wang     entry->iova = addr & page_mask;
202437f51384SPrasad Singamsetty     entry->translated_addr = vtd_get_slpte_addr(slpte, s->aw_bits) & page_mask;
2025d66b969bSJason Wang     entry->addr_mask = ~page_mask;
202607f7b733SPeter Xu     entry->perm = access_flags;
2027b9313021SPeter Xu     return true;
2028b9313021SPeter Xu 
2029b9313021SPeter Xu error:
20301d9efa73SPeter Xu     vtd_iommu_unlock(s);
2031b9313021SPeter Xu     entry->iova = 0;
2032b9313021SPeter Xu     entry->translated_addr = 0;
2033b9313021SPeter Xu     entry->addr_mask = 0;
2034b9313021SPeter Xu     entry->perm = IOMMU_NONE;
2035b9313021SPeter Xu     return false;
20361da12ec4SLe Tan }
20371da12ec4SLe Tan 
vtd_root_table_setup(IntelIOMMUState * s)20381da12ec4SLe Tan static void vtd_root_table_setup(IntelIOMMUState *s)
20391da12ec4SLe Tan {
20401da12ec4SLe Tan     s->root = vtd_get_quad_raw(s, DMAR_RTADDR_REG);
204137f51384SPrasad Singamsetty     s->root &= VTD_RTADDR_ADDR_MASK(s->aw_bits);
20421da12ec4SLe Tan 
20432811af3bSPeter Xu     vtd_update_scalable_state(s);
20442811af3bSPeter Xu 
204581fb1e64SPeter Xu     trace_vtd_reg_dmar_root(s->root, s->root_scalable);
20461da12ec4SLe Tan }
20471da12ec4SLe Tan 
vtd_iec_notify_all(IntelIOMMUState * s,bool global,uint32_t index,uint32_t mask)204802a2cbc8SPeter Xu static void vtd_iec_notify_all(IntelIOMMUState *s, bool global,
204902a2cbc8SPeter Xu                                uint32_t index, uint32_t mask)
205002a2cbc8SPeter Xu {
205102a2cbc8SPeter Xu     x86_iommu_iec_notify_all(X86_IOMMU_DEVICE(s), global, index, mask);
205202a2cbc8SPeter Xu }
205302a2cbc8SPeter Xu 
vtd_interrupt_remap_table_setup(IntelIOMMUState * s)2054a5861439SPeter Xu static void vtd_interrupt_remap_table_setup(IntelIOMMUState *s)
2055a5861439SPeter Xu {
2056a5861439SPeter Xu     uint64_t value = 0;
2057a5861439SPeter Xu     value = vtd_get_quad_raw(s, DMAR_IRTA_REG);
2058a5861439SPeter Xu     s->intr_size = 1UL << ((value & VTD_IRTA_SIZE_MASK) + 1);
205937f51384SPrasad Singamsetty     s->intr_root = value & VTD_IRTA_ADDR_MASK(s->aw_bits);
206028589311SJan Kiszka     s->intr_eime = value & VTD_IRTA_EIME;
2061a5861439SPeter Xu 
206202a2cbc8SPeter Xu     /* Notify global invalidation */
206302a2cbc8SPeter Xu     vtd_iec_notify_all(s, true, 0, 0);
2064a5861439SPeter Xu 
20657feb51b7SPeter Xu     trace_vtd_reg_ir_root(s->intr_root, s->intr_size);
2066a5861439SPeter Xu }
2067a5861439SPeter Xu 
vtd_iommu_replay_all(IntelIOMMUState * s)2068dd4d607eSPeter Xu static void vtd_iommu_replay_all(IntelIOMMUState *s)
2069dd4d607eSPeter Xu {
2070b4a4ba0dSPeter Xu     VTDAddressSpace *vtd_as;
2071dd4d607eSPeter Xu 
2072b4a4ba0dSPeter Xu     QLIST_FOREACH(vtd_as, &s->vtd_as_with_notifiers, next) {
20733e090e34SPeter Xu         vtd_address_space_sync(vtd_as);
2074dd4d607eSPeter Xu     }
2075dd4d607eSPeter Xu }
2076dd4d607eSPeter Xu 
vtd_context_global_invalidate(IntelIOMMUState * s)2077d92fa2dcSLe Tan static void vtd_context_global_invalidate(IntelIOMMUState *s)
2078d92fa2dcSLe Tan {
2079bc535e59SPeter Xu     trace_vtd_inv_desc_cc_global();
20801d9efa73SPeter Xu     /* Protects context cache */
20811d9efa73SPeter Xu     vtd_iommu_lock(s);
2082d92fa2dcSLe Tan     s->context_cache_gen++;
2083d92fa2dcSLe Tan     if (s->context_cache_gen == VTD_CONTEXT_CACHE_GEN_MAX) {
20841d9efa73SPeter Xu         vtd_reset_context_cache_locked(s);
2085d92fa2dcSLe Tan     }
20861d9efa73SPeter Xu     vtd_iommu_unlock(s);
20872cc9ddccSPeter Xu     vtd_address_space_refresh_all(s);
2088dd4d607eSPeter Xu     /*
2089dd4d607eSPeter Xu      * From VT-d spec 6.5.2.1, a global context entry invalidation
2090dd4d607eSPeter Xu      * should be followed by a IOTLB global invalidation, so we should
2091dd4d607eSPeter Xu      * be safe even without this. Hoewever, let's replay the region as
2092dd4d607eSPeter Xu      * well to be safer, and go back here when we need finer tunes for
2093dd4d607eSPeter Xu      * VT-d emulation codes.
2094dd4d607eSPeter Xu      */
2095dd4d607eSPeter Xu     vtd_iommu_replay_all(s);
2096d92fa2dcSLe Tan }
2097d92fa2dcSLe Tan 
2098d92fa2dcSLe Tan /* Do a context-cache device-selective invalidation.
2099d92fa2dcSLe Tan  * @func_mask: FM field after shifting
2100d92fa2dcSLe Tan  */
vtd_context_device_invalidate(IntelIOMMUState * s,uint16_t source_id,uint16_t func_mask)2101d92fa2dcSLe Tan static void vtd_context_device_invalidate(IntelIOMMUState *s,
2102d92fa2dcSLe Tan                                           uint16_t source_id,
2103d92fa2dcSLe Tan                                           uint16_t func_mask)
2104d92fa2dcSLe Tan {
2105da8d439cSJason Wang     GHashTableIter as_it;
2106d92fa2dcSLe Tan     uint16_t mask;
2107d92fa2dcSLe Tan     VTDAddressSpace *vtd_as;
2108bc535e59SPeter Xu     uint8_t bus_n, devfn;
2109d92fa2dcSLe Tan 
2110bc535e59SPeter Xu     trace_vtd_inv_desc_cc_devices(source_id, func_mask);
2111bc535e59SPeter Xu 
2112d92fa2dcSLe Tan     switch (func_mask & 3) {
2113d92fa2dcSLe Tan     case 0:
2114d92fa2dcSLe Tan         mask = 0;   /* No bits in the SID field masked */
2115d92fa2dcSLe Tan         break;
2116d92fa2dcSLe Tan     case 1:
2117d92fa2dcSLe Tan         mask = 4;   /* Mask bit 2 in the SID field */
2118d92fa2dcSLe Tan         break;
2119d92fa2dcSLe Tan     case 2:
2120d92fa2dcSLe Tan         mask = 6;   /* Mask bit 2:1 in the SID field */
2121d92fa2dcSLe Tan         break;
2122d92fa2dcSLe Tan     case 3:
2123d92fa2dcSLe Tan         mask = 7;   /* Mask bit 2:0 in the SID field */
2124d92fa2dcSLe Tan         break;
212541ce9a91SEric Auger     default:
212641ce9a91SEric Auger         g_assert_not_reached();
2127d92fa2dcSLe Tan     }
21286cb99accSPeter Xu     mask = ~mask;
2129bc535e59SPeter Xu 
2130bc535e59SPeter Xu     bus_n = VTD_SID_TO_BUS(source_id);
2131d92fa2dcSLe Tan     devfn = VTD_SID_TO_DEVFN(source_id);
2132da8d439cSJason Wang 
2133da8d439cSJason Wang     g_hash_table_iter_init(&as_it, s->vtd_address_spaces);
2134da8d439cSJason Wang     while (g_hash_table_iter_next(&as_it, NULL, (void **)&vtd_as)) {
2135da8d439cSJason Wang         if ((pci_bus_num(vtd_as->bus) == bus_n) &&
2136da8d439cSJason Wang             (vtd_as->devfn & mask) == (devfn & mask)) {
2137da8d439cSJason Wang             trace_vtd_inv_desc_cc_device(bus_n, VTD_PCI_SLOT(vtd_as->devfn),
2138da8d439cSJason Wang                                          VTD_PCI_FUNC(vtd_as->devfn));
21391d9efa73SPeter Xu             vtd_iommu_lock(s);
2140d92fa2dcSLe Tan             vtd_as->context_cache_entry.context_cache_gen = 0;
21411d9efa73SPeter Xu             vtd_iommu_unlock(s);
2142dd4d607eSPeter Xu             /*
2143dbaabb25SPeter Xu              * Do switch address space when needed, in case if the
2144dbaabb25SPeter Xu              * device passthrough bit is switched.
2145dbaabb25SPeter Xu              */
2146dbaabb25SPeter Xu             vtd_switch_address_space(vtd_as);
2147dbaabb25SPeter Xu             /*
2148dd4d607eSPeter Xu              * So a device is moving out of (or moving into) a
214963b88968SPeter Xu              * domain, resync the shadow page table.
2150dd4d607eSPeter Xu              * This won't bring bad even if we have no such
2151dd4d607eSPeter Xu              * notifier registered - the IOMMU notification
2152dd4d607eSPeter Xu              * framework will skip MAP notifications if that
2153dd4d607eSPeter Xu              * happened.
2154dd4d607eSPeter Xu              */
21553e090e34SPeter Xu             vtd_address_space_sync(vtd_as);
2156d92fa2dcSLe Tan         }
2157d92fa2dcSLe Tan     }
2158d92fa2dcSLe Tan }
2159d92fa2dcSLe Tan 
21601da12ec4SLe Tan /* Context-cache invalidation
21611da12ec4SLe Tan  * Returns the Context Actual Invalidation Granularity.
21621da12ec4SLe Tan  * @val: the content of the CCMD_REG
21631da12ec4SLe Tan  */
vtd_context_cache_invalidate(IntelIOMMUState * s,uint64_t val)21641da12ec4SLe Tan static uint64_t vtd_context_cache_invalidate(IntelIOMMUState *s, uint64_t val)
21651da12ec4SLe Tan {
21661da12ec4SLe Tan     uint64_t caig;
21671da12ec4SLe Tan     uint64_t type = val & VTD_CCMD_CIRG_MASK;
21681da12ec4SLe Tan 
21691da12ec4SLe Tan     switch (type) {
21701da12ec4SLe Tan     case VTD_CCMD_DOMAIN_INVL:
2171d92fa2dcSLe Tan         /* Fall through */
2172d92fa2dcSLe Tan     case VTD_CCMD_GLOBAL_INVL:
2173d92fa2dcSLe Tan         caig = VTD_CCMD_GLOBAL_INVL_A;
2174d92fa2dcSLe Tan         vtd_context_global_invalidate(s);
21751da12ec4SLe Tan         break;
21761da12ec4SLe Tan 
21771da12ec4SLe Tan     case VTD_CCMD_DEVICE_INVL:
21781da12ec4SLe Tan         caig = VTD_CCMD_DEVICE_INVL_A;
2179d92fa2dcSLe Tan         vtd_context_device_invalidate(s, VTD_CCMD_SID(val), VTD_CCMD_FM(val));
21801da12ec4SLe Tan         break;
21811da12ec4SLe Tan 
21821da12ec4SLe Tan     default:
21831376211fSPeter Xu         error_report_once("%s: invalid context: 0x%" PRIx64,
21841376211fSPeter Xu                           __func__, val);
21851da12ec4SLe Tan         caig = 0;
21861da12ec4SLe Tan     }
21871da12ec4SLe Tan     return caig;
21881da12ec4SLe Tan }
21891da12ec4SLe Tan 
vtd_iotlb_global_invalidate(IntelIOMMUState * s)2190b5a280c0SLe Tan static void vtd_iotlb_global_invalidate(IntelIOMMUState *s)
2191b5a280c0SLe Tan {
21927feb51b7SPeter Xu     trace_vtd_inv_desc_iotlb_global();
2193b5a280c0SLe Tan     vtd_reset_iotlb(s);
2194dd4d607eSPeter Xu     vtd_iommu_replay_all(s);
2195b5a280c0SLe Tan }
2196b5a280c0SLe Tan 
vtd_iotlb_domain_invalidate(IntelIOMMUState * s,uint16_t domain_id)2197b5a280c0SLe Tan static void vtd_iotlb_domain_invalidate(IntelIOMMUState *s, uint16_t domain_id)
2198b5a280c0SLe Tan {
2199dd4d607eSPeter Xu     VTDContextEntry ce;
2200dd4d607eSPeter Xu     VTDAddressSpace *vtd_as;
2201dd4d607eSPeter Xu 
22027feb51b7SPeter Xu     trace_vtd_inv_desc_iotlb_domain(domain_id);
22037feb51b7SPeter Xu 
22041d9efa73SPeter Xu     vtd_iommu_lock(s);
2205b5a280c0SLe Tan     g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_domain,
2206b5a280c0SLe Tan                                 &domain_id);
22071d9efa73SPeter Xu     vtd_iommu_unlock(s);
2208dd4d607eSPeter Xu 
2209b4a4ba0dSPeter Xu     QLIST_FOREACH(vtd_as, &s->vtd_as_with_notifiers, next) {
2210dd4d607eSPeter Xu         if (!vtd_dev_to_context_entry(s, pci_bus_num(vtd_as->bus),
2211dd4d607eSPeter Xu                                       vtd_as->devfn, &ce) &&
22121b2b1237SJason Wang             domain_id == vtd_get_domain_id(s, &ce, vtd_as->pasid)) {
22133e090e34SPeter Xu             vtd_address_space_sync(vtd_as);
2214dd4d607eSPeter Xu         }
2215dd4d607eSPeter Xu     }
2216dd4d607eSPeter Xu }
2217dd4d607eSPeter Xu 
vtd_iotlb_page_invalidate_notify(IntelIOMMUState * s,uint16_t domain_id,hwaddr addr,uint8_t am,uint32_t pasid)2218dd4d607eSPeter Xu static void vtd_iotlb_page_invalidate_notify(IntelIOMMUState *s,
2219dd4d607eSPeter Xu                                            uint16_t domain_id, hwaddr addr,
22201b2b1237SJason Wang                                              uint8_t am, uint32_t pasid)
2221dd4d607eSPeter Xu {
2222b4a4ba0dSPeter Xu     VTDAddressSpace *vtd_as;
2223dd4d607eSPeter Xu     VTDContextEntry ce;
2224dd4d607eSPeter Xu     int ret;
22254f8a62a9SPeter Xu     hwaddr size = (1 << am) * VTD_PAGE_SIZE;
2226dd4d607eSPeter Xu 
2227b4a4ba0dSPeter Xu     QLIST_FOREACH(vtd_as, &(s->vtd_as_with_notifiers), next) {
22281b2b1237SJason Wang         if (pasid != PCI_NO_PASID && pasid != vtd_as->pasid) {
22291b2b1237SJason Wang             continue;
22301b2b1237SJason Wang         }
2231dd4d607eSPeter Xu         ret = vtd_dev_to_context_entry(s, pci_bus_num(vtd_as->bus),
2232dd4d607eSPeter Xu                                        vtd_as->devfn, &ce);
22331b2b1237SJason Wang         if (!ret && domain_id == vtd_get_domain_id(s, &ce, vtd_as->pasid)) {
22344f8a62a9SPeter Xu             if (vtd_as_has_map_notifier(vtd_as)) {
22354f8a62a9SPeter Xu                 /*
22364f8a62a9SPeter Xu                  * As long as we have MAP notifications registered in
22374f8a62a9SPeter Xu                  * any of our IOMMU notifiers, we need to sync the
22384f8a62a9SPeter Xu                  * shadow page table.
22394f8a62a9SPeter Xu                  */
224063b88968SPeter Xu                 vtd_sync_shadow_page_table_range(vtd_as, &ce, addr, size);
22414f8a62a9SPeter Xu             } else {
22424f8a62a9SPeter Xu                 /*
22434f8a62a9SPeter Xu                  * For UNMAP-only notifiers, we don't need to walk the
22444f8a62a9SPeter Xu                  * page tables.  We just deliver the PSI down to
22454f8a62a9SPeter Xu                  * invalidate caches.
22464f8a62a9SPeter Xu                  */
2247fc9ad5cfSPhilippe Mathieu-Daudé                 const IOMMUTLBEvent event = {
22485039caf3SEugenio Pérez                     .type = IOMMU_NOTIFIER_UNMAP,
22495039caf3SEugenio Pérez                     .entry = {
22504f8a62a9SPeter Xu                         .target_as = &address_space_memory,
22514f8a62a9SPeter Xu                         .iova = addr,
22524f8a62a9SPeter Xu                         .translated_addr = 0,
22534f8a62a9SPeter Xu                         .addr_mask = size - 1,
22544f8a62a9SPeter Xu                         .perm = IOMMU_NONE,
22555039caf3SEugenio Pérez                     },
22564f8a62a9SPeter Xu                 };
22575039caf3SEugenio Pérez                 memory_region_notify_iommu(&vtd_as->iommu, 0, event);
22584f8a62a9SPeter Xu             }
2259dd4d607eSPeter Xu         }
2260dd4d607eSPeter Xu     }
2261b5a280c0SLe Tan }
2262b5a280c0SLe Tan 
vtd_iotlb_page_invalidate(IntelIOMMUState * s,uint16_t domain_id,hwaddr addr,uint8_t am)2263b5a280c0SLe Tan static void vtd_iotlb_page_invalidate(IntelIOMMUState *s, uint16_t domain_id,
2264b5a280c0SLe Tan                                       hwaddr addr, uint8_t am)
2265b5a280c0SLe Tan {
2266b5a280c0SLe Tan     VTDIOTLBPageInvInfo info;
2267b5a280c0SLe Tan 
22687feb51b7SPeter Xu     trace_vtd_inv_desc_iotlb_pages(domain_id, addr, am);
22697feb51b7SPeter Xu 
2270b5a280c0SLe Tan     assert(am <= VTD_MAMV);
2271b5a280c0SLe Tan     info.domain_id = domain_id;
2272d66b969bSJason Wang     info.addr = addr;
2273b5a280c0SLe Tan     info.mask = ~((1 << am) - 1);
22741d9efa73SPeter Xu     vtd_iommu_lock(s);
2275b5a280c0SLe Tan     g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_page, &info);
22761d9efa73SPeter Xu     vtd_iommu_unlock(s);
22771b2b1237SJason Wang     vtd_iotlb_page_invalidate_notify(s, domain_id, addr, am, PCI_NO_PASID);
2278b5a280c0SLe Tan }
2279b5a280c0SLe Tan 
22801da12ec4SLe Tan /* Flush IOTLB
22811da12ec4SLe Tan  * Returns the IOTLB Actual Invalidation Granularity.
22821da12ec4SLe Tan  * @val: the content of the IOTLB_REG
22831da12ec4SLe Tan  */
vtd_iotlb_flush(IntelIOMMUState * s,uint64_t val)22841da12ec4SLe Tan static uint64_t vtd_iotlb_flush(IntelIOMMUState *s, uint64_t val)
22851da12ec4SLe Tan {
22861da12ec4SLe Tan     uint64_t iaig;
22871da12ec4SLe Tan     uint64_t type = val & VTD_TLB_FLUSH_GRANU_MASK;
2288b5a280c0SLe Tan     uint16_t domain_id;
2289b5a280c0SLe Tan     hwaddr addr;
2290b5a280c0SLe Tan     uint8_t am;
22911da12ec4SLe Tan 
22921da12ec4SLe Tan     switch (type) {
22931da12ec4SLe Tan     case VTD_TLB_GLOBAL_FLUSH:
22941da12ec4SLe Tan         iaig = VTD_TLB_GLOBAL_FLUSH_A;
2295b5a280c0SLe Tan         vtd_iotlb_global_invalidate(s);
22961da12ec4SLe Tan         break;
22971da12ec4SLe Tan 
22981da12ec4SLe Tan     case VTD_TLB_DSI_FLUSH:
2299b5a280c0SLe Tan         domain_id = VTD_TLB_DID(val);
23001da12ec4SLe Tan         iaig = VTD_TLB_DSI_FLUSH_A;
2301b5a280c0SLe Tan         vtd_iotlb_domain_invalidate(s, domain_id);
23021da12ec4SLe Tan         break;
23031da12ec4SLe Tan 
23041da12ec4SLe Tan     case VTD_TLB_PSI_FLUSH:
2305b5a280c0SLe Tan         domain_id = VTD_TLB_DID(val);
2306b5a280c0SLe Tan         addr = vtd_get_quad_raw(s, DMAR_IVA_REG);
2307b5a280c0SLe Tan         am = VTD_IVA_AM(addr);
2308b5a280c0SLe Tan         addr = VTD_IVA_ADDR(addr);
2309b5a280c0SLe Tan         if (am > VTD_MAMV) {
23101376211fSPeter Xu             error_report_once("%s: address mask overflow: 0x%" PRIx64,
23111376211fSPeter Xu                               __func__, vtd_get_quad_raw(s, DMAR_IVA_REG));
2312b5a280c0SLe Tan             iaig = 0;
2313b5a280c0SLe Tan             break;
2314b5a280c0SLe Tan         }
23151da12ec4SLe Tan         iaig = VTD_TLB_PSI_FLUSH_A;
2316b5a280c0SLe Tan         vtd_iotlb_page_invalidate(s, domain_id, addr, am);
23171da12ec4SLe Tan         break;
23181da12ec4SLe Tan 
23191da12ec4SLe Tan     default:
23201376211fSPeter Xu         error_report_once("%s: invalid granularity: 0x%" PRIx64,
23211376211fSPeter Xu                           __func__, val);
23221da12ec4SLe Tan         iaig = 0;
23231da12ec4SLe Tan     }
23241da12ec4SLe Tan     return iaig;
23251da12ec4SLe Tan }
23261da12ec4SLe Tan 
23278991c460SLadi Prosek static void vtd_fetch_inv_desc(IntelIOMMUState *s);
2328ed7b8fbcSLe Tan 
vtd_queued_inv_disable_check(IntelIOMMUState * s)2329ed7b8fbcSLe Tan static inline bool vtd_queued_inv_disable_check(IntelIOMMUState *s)
2330ed7b8fbcSLe Tan {
2331ed7b8fbcSLe Tan     return s->qi_enabled && (s->iq_tail == s->iq_head) &&
2332ed7b8fbcSLe Tan            (s->iq_last_desc_type == VTD_INV_DESC_WAIT);
2333ed7b8fbcSLe Tan }
2334ed7b8fbcSLe Tan 
vtd_handle_gcmd_qie(IntelIOMMUState * s,bool en)2335ed7b8fbcSLe Tan static void vtd_handle_gcmd_qie(IntelIOMMUState *s, bool en)
2336ed7b8fbcSLe Tan {
2337ed7b8fbcSLe Tan     uint64_t iqa_val = vtd_get_quad_raw(s, DMAR_IQA_REG);
2338ed7b8fbcSLe Tan 
23397feb51b7SPeter Xu     trace_vtd_inv_qi_enable(en);
23407feb51b7SPeter Xu 
2341ed7b8fbcSLe Tan     if (en) {
234237f51384SPrasad Singamsetty         s->iq = iqa_val & VTD_IQA_IQA_MASK(s->aw_bits);
2343ed7b8fbcSLe Tan         /* 2^(x+8) entries */
2344c0c1d351SLiu, Yi L         s->iq_size = 1UL << ((iqa_val & VTD_IQA_QS) + 8 - (s->iq_dw ? 1 : 0));
2345ed7b8fbcSLe Tan         s->qi_enabled = true;
23467feb51b7SPeter Xu         trace_vtd_inv_qi_setup(s->iq, s->iq_size);
2347ed7b8fbcSLe Tan         /* Ok - report back to driver */
2348ed7b8fbcSLe Tan         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_QIES);
23498991c460SLadi Prosek 
23508991c460SLadi Prosek         if (s->iq_tail != 0) {
23518991c460SLadi Prosek             /*
23528991c460SLadi Prosek              * This is a spec violation but Windows guests are known to set up
23538991c460SLadi Prosek              * Queued Invalidation this way so we allow the write and process
23548991c460SLadi Prosek              * Invalidation Descriptors right away.
23558991c460SLadi Prosek              */
23568991c460SLadi Prosek             trace_vtd_warn_invalid_qi_tail(s->iq_tail);
23578991c460SLadi Prosek             if (!(vtd_get_long_raw(s, DMAR_FSTS_REG) & VTD_FSTS_IQE)) {
23588991c460SLadi Prosek                 vtd_fetch_inv_desc(s);
23598991c460SLadi Prosek             }
2360ed7b8fbcSLe Tan         }
2361ed7b8fbcSLe Tan     } else {
2362ed7b8fbcSLe Tan         if (vtd_queued_inv_disable_check(s)) {
2363ed7b8fbcSLe Tan             /* disable Queued Invalidation */
2364ed7b8fbcSLe Tan             vtd_set_quad_raw(s, DMAR_IQH_REG, 0);
2365ed7b8fbcSLe Tan             s->iq_head = 0;
2366ed7b8fbcSLe Tan             s->qi_enabled = false;
2367ed7b8fbcSLe Tan             /* Ok - report back to driver */
2368ed7b8fbcSLe Tan             vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_QIES, 0);
2369ed7b8fbcSLe Tan         } else {
23704e4abd11SPeter Xu             error_report_once("%s: detected improper state when disable QI "
23714e4abd11SPeter Xu                               "(head=0x%x, tail=0x%x, last_type=%d)",
23724e4abd11SPeter Xu                               __func__,
23734e4abd11SPeter Xu                               s->iq_head, s->iq_tail, s->iq_last_desc_type);
2374ed7b8fbcSLe Tan         }
2375ed7b8fbcSLe Tan     }
2376ed7b8fbcSLe Tan }
2377ed7b8fbcSLe Tan 
23781da12ec4SLe Tan /* Set Root Table Pointer */
vtd_handle_gcmd_srtp(IntelIOMMUState * s)23791da12ec4SLe Tan static void vtd_handle_gcmd_srtp(IntelIOMMUState *s)
23801da12ec4SLe Tan {
23811da12ec4SLe Tan     vtd_root_table_setup(s);
23821da12ec4SLe Tan     /* Ok - report back to driver */
23831da12ec4SLe Tan     vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_RTPS);
23842cc9ddccSPeter Xu     vtd_reset_caches(s);
23852cc9ddccSPeter Xu     vtd_address_space_refresh_all(s);
23861da12ec4SLe Tan }
23871da12ec4SLe Tan 
2388a5861439SPeter Xu /* Set Interrupt Remap Table Pointer */
vtd_handle_gcmd_sirtp(IntelIOMMUState * s)2389a5861439SPeter Xu static void vtd_handle_gcmd_sirtp(IntelIOMMUState *s)
2390a5861439SPeter Xu {
2391a5861439SPeter Xu     vtd_interrupt_remap_table_setup(s);
2392a5861439SPeter Xu     /* Ok - report back to driver */
2393a5861439SPeter Xu     vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_IRTPS);
2394a5861439SPeter Xu }
2395a5861439SPeter Xu 
23961da12ec4SLe Tan /* Handle Translation Enable/Disable */
vtd_handle_gcmd_te(IntelIOMMUState * s,bool en)23971da12ec4SLe Tan static void vtd_handle_gcmd_te(IntelIOMMUState *s, bool en)
23981da12ec4SLe Tan {
2399558e0024SPeter Xu     if (s->dmar_enabled == en) {
2400558e0024SPeter Xu         return;
2401558e0024SPeter Xu     }
2402558e0024SPeter Xu 
24037feb51b7SPeter Xu     trace_vtd_dmar_enable(en);
24041da12ec4SLe Tan 
24051da12ec4SLe Tan     if (en) {
24061da12ec4SLe Tan         s->dmar_enabled = true;
24071da12ec4SLe Tan         /* Ok - report back to driver */
24081da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_TES);
24091da12ec4SLe Tan     } else {
24101da12ec4SLe Tan         s->dmar_enabled = false;
24111da12ec4SLe Tan 
24121da12ec4SLe Tan         /* Clear the index of Fault Recording Register */
24131da12ec4SLe Tan         s->next_frcd_reg = 0;
24141da12ec4SLe Tan         /* Ok - report back to driver */
24151da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_TES, 0);
24161da12ec4SLe Tan     }
2417558e0024SPeter Xu 
24182cc9ddccSPeter Xu     vtd_reset_caches(s);
24192cc9ddccSPeter Xu     vtd_address_space_refresh_all(s);
24201da12ec4SLe Tan }
24211da12ec4SLe Tan 
242280de52baSPeter Xu /* Handle Interrupt Remap Enable/Disable */
vtd_handle_gcmd_ire(IntelIOMMUState * s,bool en)242380de52baSPeter Xu static void vtd_handle_gcmd_ire(IntelIOMMUState *s, bool en)
242480de52baSPeter Xu {
24257feb51b7SPeter Xu     trace_vtd_ir_enable(en);
242680de52baSPeter Xu 
242780de52baSPeter Xu     if (en) {
242880de52baSPeter Xu         s->intr_enabled = true;
242980de52baSPeter Xu         /* Ok - report back to driver */
243080de52baSPeter Xu         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_IRES);
243180de52baSPeter Xu     } else {
243280de52baSPeter Xu         s->intr_enabled = false;
243380de52baSPeter Xu         /* Ok - report back to driver */
243480de52baSPeter Xu         vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_IRES, 0);
243580de52baSPeter Xu     }
243680de52baSPeter Xu }
243780de52baSPeter Xu 
24381da12ec4SLe Tan /* Handle write to Global Command Register */
vtd_handle_gcmd_write(IntelIOMMUState * s)24391da12ec4SLe Tan static void vtd_handle_gcmd_write(IntelIOMMUState *s)
24401da12ec4SLe Tan {
2441175f3a59SDavid Woodhouse     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
24421da12ec4SLe Tan     uint32_t status = vtd_get_long_raw(s, DMAR_GSTS_REG);
24431da12ec4SLe Tan     uint32_t val = vtd_get_long_raw(s, DMAR_GCMD_REG);
24441da12ec4SLe Tan     uint32_t changed = status ^ val;
24451da12ec4SLe Tan 
24467feb51b7SPeter Xu     trace_vtd_reg_write_gcmd(status, val);
24478646d9c7SDavid Woodhouse     if ((changed & VTD_GCMD_TE) && s->dma_translation) {
24481da12ec4SLe Tan         /* Translation enable/disable */
24491da12ec4SLe Tan         vtd_handle_gcmd_te(s, val & VTD_GCMD_TE);
24501da12ec4SLe Tan     }
24511da12ec4SLe Tan     if (val & VTD_GCMD_SRTP) {
24521da12ec4SLe Tan         /* Set/update the root-table pointer */
24531da12ec4SLe Tan         vtd_handle_gcmd_srtp(s);
24541da12ec4SLe Tan     }
2455ed7b8fbcSLe Tan     if (changed & VTD_GCMD_QIE) {
2456ed7b8fbcSLe Tan         /* Queued Invalidation Enable */
2457ed7b8fbcSLe Tan         vtd_handle_gcmd_qie(s, val & VTD_GCMD_QIE);
2458ed7b8fbcSLe Tan     }
2459a5861439SPeter Xu     if (val & VTD_GCMD_SIRTP) {
2460a5861439SPeter Xu         /* Set/update the interrupt remapping root-table pointer */
2461a5861439SPeter Xu         vtd_handle_gcmd_sirtp(s);
2462a5861439SPeter Xu     }
2463175f3a59SDavid Woodhouse     if ((changed & VTD_GCMD_IRE) &&
2464175f3a59SDavid Woodhouse         x86_iommu_ir_supported(x86_iommu)) {
246580de52baSPeter Xu         /* Interrupt remap enable/disable */
246680de52baSPeter Xu         vtd_handle_gcmd_ire(s, val & VTD_GCMD_IRE);
246780de52baSPeter Xu     }
24681da12ec4SLe Tan }
24691da12ec4SLe Tan 
24701da12ec4SLe Tan /* Handle write to Context Command Register */
vtd_handle_ccmd_write(IntelIOMMUState * s)24711da12ec4SLe Tan static void vtd_handle_ccmd_write(IntelIOMMUState *s)
24721da12ec4SLe Tan {
24731da12ec4SLe Tan     uint64_t ret;
24741da12ec4SLe Tan     uint64_t val = vtd_get_quad_raw(s, DMAR_CCMD_REG);
24751da12ec4SLe Tan 
24761da12ec4SLe Tan     /* Context-cache invalidation request */
24771da12ec4SLe Tan     if (val & VTD_CCMD_ICC) {
2478ed7b8fbcSLe Tan         if (s->qi_enabled) {
24791376211fSPeter Xu             error_report_once("Queued Invalidation enabled, "
2480ed7b8fbcSLe Tan                               "should not use register-based invalidation");
2481ed7b8fbcSLe Tan             return;
2482ed7b8fbcSLe Tan         }
24831da12ec4SLe Tan         ret = vtd_context_cache_invalidate(s, val);
24841da12ec4SLe Tan         /* Invalidation completed. Change something to show */
24851da12ec4SLe Tan         vtd_set_clear_mask_quad(s, DMAR_CCMD_REG, VTD_CCMD_ICC, 0ULL);
24861da12ec4SLe Tan         ret = vtd_set_clear_mask_quad(s, DMAR_CCMD_REG, VTD_CCMD_CAIG_MASK,
24871da12ec4SLe Tan                                       ret);
24881da12ec4SLe Tan     }
24891da12ec4SLe Tan }
24901da12ec4SLe Tan 
24911da12ec4SLe Tan /* Handle write to IOTLB Invalidation Register */
vtd_handle_iotlb_write(IntelIOMMUState * s)24921da12ec4SLe Tan static void vtd_handle_iotlb_write(IntelIOMMUState *s)
24931da12ec4SLe Tan {
24941da12ec4SLe Tan     uint64_t ret;
24951da12ec4SLe Tan     uint64_t val = vtd_get_quad_raw(s, DMAR_IOTLB_REG);
24961da12ec4SLe Tan 
24971da12ec4SLe Tan     /* IOTLB invalidation request */
24981da12ec4SLe Tan     if (val & VTD_TLB_IVT) {
2499ed7b8fbcSLe Tan         if (s->qi_enabled) {
25001376211fSPeter Xu             error_report_once("Queued Invalidation enabled, "
25011376211fSPeter Xu                               "should not use register-based invalidation");
2502ed7b8fbcSLe Tan             return;
2503ed7b8fbcSLe Tan         }
25041da12ec4SLe Tan         ret = vtd_iotlb_flush(s, val);
25051da12ec4SLe Tan         /* Invalidation completed. Change something to show */
25061da12ec4SLe Tan         vtd_set_clear_mask_quad(s, DMAR_IOTLB_REG, VTD_TLB_IVT, 0ULL);
25071da12ec4SLe Tan         ret = vtd_set_clear_mask_quad(s, DMAR_IOTLB_REG,
25081da12ec4SLe Tan                                       VTD_TLB_FLUSH_GRANU_MASK_A, ret);
25091da12ec4SLe Tan     }
25101da12ec4SLe Tan }
25111da12ec4SLe Tan 
2512ed7b8fbcSLe Tan /* Fetch an Invalidation Descriptor from the Invalidation Queue */
vtd_get_inv_desc(IntelIOMMUState * s,VTDInvDesc * inv_desc)2513c0c1d351SLiu, Yi L static bool vtd_get_inv_desc(IntelIOMMUState *s,
2514ed7b8fbcSLe Tan                              VTDInvDesc *inv_desc)
2515ed7b8fbcSLe Tan {
2516c0c1d351SLiu, Yi L     dma_addr_t base_addr = s->iq;
2517c0c1d351SLiu, Yi L     uint32_t offset = s->iq_head;
2518c0c1d351SLiu, Yi L     uint32_t dw = s->iq_dw ? 32 : 16;
2519c0c1d351SLiu, Yi L     dma_addr_t addr = base_addr + offset * dw;
2520c0c1d351SLiu, Yi L 
2521ba06fe8aSPhilippe Mathieu-Daudé     if (dma_memory_read(&address_space_memory, addr,
2522ba06fe8aSPhilippe Mathieu-Daudé                         inv_desc, dw, MEMTXATTRS_UNSPECIFIED)) {
2523c0c1d351SLiu, Yi L         error_report_once("Read INV DESC failed.");
2524ed7b8fbcSLe Tan         return false;
2525ed7b8fbcSLe Tan     }
2526ed7b8fbcSLe Tan     inv_desc->lo = le64_to_cpu(inv_desc->lo);
2527ed7b8fbcSLe Tan     inv_desc->hi = le64_to_cpu(inv_desc->hi);
2528c0c1d351SLiu, Yi L     if (dw == 32) {
2529c0c1d351SLiu, Yi L         inv_desc->val[2] = le64_to_cpu(inv_desc->val[2]);
2530c0c1d351SLiu, Yi L         inv_desc->val[3] = le64_to_cpu(inv_desc->val[3]);
2531c0c1d351SLiu, Yi L     }
2532ed7b8fbcSLe Tan     return true;
2533ed7b8fbcSLe Tan }
2534ed7b8fbcSLe Tan 
vtd_inv_desc_reserved_check(IntelIOMMUState * s,VTDInvDesc * inv_desc,uint64_t mask[4],bool dw,const char * func_name,const char * desc_type)25358e761fb6SZhenzhong Duan static bool vtd_inv_desc_reserved_check(IntelIOMMUState *s,
25368e761fb6SZhenzhong Duan                                         VTDInvDesc *inv_desc,
25378e761fb6SZhenzhong Duan                                         uint64_t mask[4], bool dw,
25388e761fb6SZhenzhong Duan                                         const char *func_name,
25398e761fb6SZhenzhong Duan                                         const char *desc_type)
2540ed7b8fbcSLe Tan {
25418e761fb6SZhenzhong Duan     if (s->iq_dw) {
25428e761fb6SZhenzhong Duan         if (inv_desc->val[0] & mask[0] || inv_desc->val[1] & mask[1] ||
25438e761fb6SZhenzhong Duan             inv_desc->val[2] & mask[2] || inv_desc->val[3] & mask[3]) {
25448e761fb6SZhenzhong Duan             error_report("%s: invalid %s desc val[3]: 0x%"PRIx64
25458e761fb6SZhenzhong Duan                          " val[2]: 0x%"PRIx64" val[1]=0x%"PRIx64
25468e761fb6SZhenzhong Duan                          " val[0]=0x%"PRIx64" (reserved nonzero)",
25478e761fb6SZhenzhong Duan                          func_name, desc_type, inv_desc->val[3],
25488e761fb6SZhenzhong Duan                          inv_desc->val[2], inv_desc->val[1],
25498e761fb6SZhenzhong Duan                          inv_desc->val[0]);
2550ed7b8fbcSLe Tan             return false;
2551ed7b8fbcSLe Tan         }
25528e761fb6SZhenzhong Duan     } else {
25538e761fb6SZhenzhong Duan         if (dw) {
25548e761fb6SZhenzhong Duan             error_report("%s: 256-bit %s desc in 128-bit invalidation queue",
25558e761fb6SZhenzhong Duan                          func_name, desc_type);
25568e761fb6SZhenzhong Duan             return false;
25578e761fb6SZhenzhong Duan         }
25588e761fb6SZhenzhong Duan 
25598e761fb6SZhenzhong Duan         if (inv_desc->lo & mask[0] || inv_desc->hi & mask[1]) {
25608e761fb6SZhenzhong Duan             error_report("%s: invalid %s desc: hi=%"PRIx64", lo=%"PRIx64
25618e761fb6SZhenzhong Duan                          " (reserved nonzero)", func_name, desc_type,
25628e761fb6SZhenzhong Duan                          inv_desc->hi, inv_desc->lo);
25638e761fb6SZhenzhong Duan             return false;
25648e761fb6SZhenzhong Duan         }
25658e761fb6SZhenzhong Duan     }
25668e761fb6SZhenzhong Duan 
25678e761fb6SZhenzhong Duan     return true;
25688e761fb6SZhenzhong Duan }
25698e761fb6SZhenzhong Duan 
vtd_process_wait_desc(IntelIOMMUState * s,VTDInvDesc * inv_desc)25708e761fb6SZhenzhong Duan static bool vtd_process_wait_desc(IntelIOMMUState *s, VTDInvDesc *inv_desc)
25718e761fb6SZhenzhong Duan {
25728e761fb6SZhenzhong Duan     uint64_t mask[4] = {VTD_INV_DESC_WAIT_RSVD_LO, VTD_INV_DESC_WAIT_RSVD_HI,
25738e761fb6SZhenzhong Duan                         VTD_INV_DESC_ALL_ONE, VTD_INV_DESC_ALL_ONE};
25748e761fb6SZhenzhong Duan 
25758e761fb6SZhenzhong Duan     if (!vtd_inv_desc_reserved_check(s, inv_desc, mask, false,
25768e761fb6SZhenzhong Duan                                      __func__, "wait")) {
25778e761fb6SZhenzhong Duan         return false;
25788e761fb6SZhenzhong Duan     }
25798e761fb6SZhenzhong Duan 
2580ed7b8fbcSLe Tan     if (inv_desc->lo & VTD_INV_DESC_WAIT_SW) {
2581ed7b8fbcSLe Tan         /* Status Write */
2582ed7b8fbcSLe Tan         uint32_t status_data = (uint32_t)(inv_desc->lo >>
2583ed7b8fbcSLe Tan                                VTD_INV_DESC_WAIT_DATA_SHIFT);
2584ed7b8fbcSLe Tan 
2585ed7b8fbcSLe Tan         assert(!(inv_desc->lo & VTD_INV_DESC_WAIT_IF));
2586ed7b8fbcSLe Tan 
2587ed7b8fbcSLe Tan         /* FIXME: need to be masked with HAW? */
2588ed7b8fbcSLe Tan         dma_addr_t status_addr = inv_desc->hi;
2589bc535e59SPeter Xu         trace_vtd_inv_desc_wait_sw(status_addr, status_data);
2590ed7b8fbcSLe Tan         status_data = cpu_to_le32(status_data);
2591ba06fe8aSPhilippe Mathieu-Daudé         if (dma_memory_write(&address_space_memory, status_addr,
2592ba06fe8aSPhilippe Mathieu-Daudé                              &status_data, sizeof(status_data),
2593ba06fe8aSPhilippe Mathieu-Daudé                              MEMTXATTRS_UNSPECIFIED)) {
2594bc535e59SPeter Xu             trace_vtd_inv_desc_wait_write_fail(inv_desc->hi, inv_desc->lo);
2595ed7b8fbcSLe Tan             return false;
2596ed7b8fbcSLe Tan         }
2597ed7b8fbcSLe Tan     } else if (inv_desc->lo & VTD_INV_DESC_WAIT_IF) {
2598ed7b8fbcSLe Tan         /* Interrupt flag */
2599ed7b8fbcSLe Tan         vtd_generate_completion_event(s);
2600ed7b8fbcSLe Tan     } else {
2601095955b2SPeter Xu         error_report_once("%s: invalid wait desc: hi=%"PRIx64", lo=%"PRIx64
2602095955b2SPeter Xu                           " (unknown type)", __func__, inv_desc->hi,
2603095955b2SPeter Xu                           inv_desc->lo);
2604ed7b8fbcSLe Tan         return false;
2605ed7b8fbcSLe Tan     }
2606ed7b8fbcSLe Tan     return true;
2607ed7b8fbcSLe Tan }
2608ed7b8fbcSLe Tan 
vtd_process_context_cache_desc(IntelIOMMUState * s,VTDInvDesc * inv_desc)2609d92fa2dcSLe Tan static bool vtd_process_context_cache_desc(IntelIOMMUState *s,
2610d92fa2dcSLe Tan                                            VTDInvDesc *inv_desc)
2611d92fa2dcSLe Tan {
2612bc535e59SPeter Xu     uint16_t sid, fmask;
26138e761fb6SZhenzhong Duan     uint64_t mask[4] = {VTD_INV_DESC_CC_RSVD, VTD_INV_DESC_ALL_ONE,
26148e761fb6SZhenzhong Duan                         VTD_INV_DESC_ALL_ONE, VTD_INV_DESC_ALL_ONE};
2615bc535e59SPeter Xu 
26168e761fb6SZhenzhong Duan     if (!vtd_inv_desc_reserved_check(s, inv_desc, mask, false,
26178e761fb6SZhenzhong Duan                                      __func__, "cc inv")) {
2618d92fa2dcSLe Tan         return false;
2619d92fa2dcSLe Tan     }
26208e761fb6SZhenzhong Duan 
2621d92fa2dcSLe Tan     switch (inv_desc->lo & VTD_INV_DESC_CC_G) {
2622d92fa2dcSLe Tan     case VTD_INV_DESC_CC_DOMAIN:
2623bc535e59SPeter Xu         trace_vtd_inv_desc_cc_domain(
2624d92fa2dcSLe Tan             (uint16_t)VTD_INV_DESC_CC_DID(inv_desc->lo));
2625d92fa2dcSLe Tan         /* Fall through */
2626d92fa2dcSLe Tan     case VTD_INV_DESC_CC_GLOBAL:
2627d92fa2dcSLe Tan         vtd_context_global_invalidate(s);
2628d92fa2dcSLe Tan         break;
2629d92fa2dcSLe Tan 
2630d92fa2dcSLe Tan     case VTD_INV_DESC_CC_DEVICE:
2631bc535e59SPeter Xu         sid = VTD_INV_DESC_CC_SID(inv_desc->lo);
2632bc535e59SPeter Xu         fmask = VTD_INV_DESC_CC_FM(inv_desc->lo);
2633bc535e59SPeter Xu         vtd_context_device_invalidate(s, sid, fmask);
2634d92fa2dcSLe Tan         break;
2635d92fa2dcSLe Tan 
2636d92fa2dcSLe Tan     default:
2637095955b2SPeter Xu         error_report_once("%s: invalid cc inv desc: hi=%"PRIx64", lo=%"PRIx64
2638095955b2SPeter Xu                           " (invalid type)", __func__, inv_desc->hi,
2639095955b2SPeter Xu                           inv_desc->lo);
2640d92fa2dcSLe Tan         return false;
2641d92fa2dcSLe Tan     }
2642d92fa2dcSLe Tan     return true;
2643d92fa2dcSLe Tan }
2644d92fa2dcSLe Tan 
vtd_process_iotlb_desc(IntelIOMMUState * s,VTDInvDesc * inv_desc)2645b5a280c0SLe Tan static bool vtd_process_iotlb_desc(IntelIOMMUState *s, VTDInvDesc *inv_desc)
2646b5a280c0SLe Tan {
2647b5a280c0SLe Tan     uint16_t domain_id;
2648b5a280c0SLe Tan     uint8_t am;
2649b5a280c0SLe Tan     hwaddr addr;
26508e761fb6SZhenzhong Duan     uint64_t mask[4] = {VTD_INV_DESC_IOTLB_RSVD_LO, VTD_INV_DESC_IOTLB_RSVD_HI,
26518e761fb6SZhenzhong Duan                         VTD_INV_DESC_ALL_ONE, VTD_INV_DESC_ALL_ONE};
2652b5a280c0SLe Tan 
26538e761fb6SZhenzhong Duan     if (!vtd_inv_desc_reserved_check(s, inv_desc, mask, false,
26548e761fb6SZhenzhong Duan                                      __func__, "iotlb inv")) {
2655b5a280c0SLe Tan         return false;
2656b5a280c0SLe Tan     }
2657b5a280c0SLe Tan 
2658b5a280c0SLe Tan     switch (inv_desc->lo & VTD_INV_DESC_IOTLB_G) {
2659b5a280c0SLe Tan     case VTD_INV_DESC_IOTLB_GLOBAL:
2660b5a280c0SLe Tan         vtd_iotlb_global_invalidate(s);
2661b5a280c0SLe Tan         break;
2662b5a280c0SLe Tan 
2663b5a280c0SLe Tan     case VTD_INV_DESC_IOTLB_DOMAIN:
2664b5a280c0SLe Tan         domain_id = VTD_INV_DESC_IOTLB_DID(inv_desc->lo);
2665b5a280c0SLe Tan         vtd_iotlb_domain_invalidate(s, domain_id);
2666b5a280c0SLe Tan         break;
2667b5a280c0SLe Tan 
2668b5a280c0SLe Tan     case VTD_INV_DESC_IOTLB_PAGE:
2669b5a280c0SLe Tan         domain_id = VTD_INV_DESC_IOTLB_DID(inv_desc->lo);
2670b5a280c0SLe Tan         addr = VTD_INV_DESC_IOTLB_ADDR(inv_desc->hi);
2671b5a280c0SLe Tan         am = VTD_INV_DESC_IOTLB_AM(inv_desc->hi);
2672b5a280c0SLe Tan         if (am > VTD_MAMV) {
2673095955b2SPeter Xu             error_report_once("%s: invalid iotlb inv desc: hi=0x%"PRIx64
2674ff5b5d5bSMarkus Armbruster                               ", lo=0x%"PRIx64" (am=%u > VTD_MAMV=%u)",
2675095955b2SPeter Xu                               __func__, inv_desc->hi, inv_desc->lo,
2676095955b2SPeter Xu                               am, (unsigned)VTD_MAMV);
2677b5a280c0SLe Tan             return false;
2678b5a280c0SLe Tan         }
2679b5a280c0SLe Tan         vtd_iotlb_page_invalidate(s, domain_id, addr, am);
2680b5a280c0SLe Tan         break;
2681b5a280c0SLe Tan 
2682b5a280c0SLe Tan     default:
2683095955b2SPeter Xu         error_report_once("%s: invalid iotlb inv desc: hi=0x%"PRIx64
2684ff5b5d5bSMarkus Armbruster                           ", lo=0x%"PRIx64" (type mismatch: 0x%llx)",
2685095955b2SPeter Xu                           __func__, inv_desc->hi, inv_desc->lo,
2686095955b2SPeter Xu                           inv_desc->lo & VTD_INV_DESC_IOTLB_G);
2687b5a280c0SLe Tan         return false;
2688b5a280c0SLe Tan     }
2689b5a280c0SLe Tan     return true;
2690b5a280c0SLe Tan }
2691b5a280c0SLe Tan 
vtd_process_inv_iec_desc(IntelIOMMUState * s,VTDInvDesc * inv_desc)269202a2cbc8SPeter Xu static bool vtd_process_inv_iec_desc(IntelIOMMUState *s,
269302a2cbc8SPeter Xu                                      VTDInvDesc *inv_desc)
269402a2cbc8SPeter Xu {
2695*096d96e7SZhenzhong Duan     uint64_t mask[4] = {VTD_INV_DESC_IEC_RSVD, VTD_INV_DESC_ALL_ONE,
2696*096d96e7SZhenzhong Duan                         VTD_INV_DESC_ALL_ONE, VTD_INV_DESC_ALL_ONE};
2697*096d96e7SZhenzhong Duan 
2698*096d96e7SZhenzhong Duan     if (!vtd_inv_desc_reserved_check(s, inv_desc, mask, false,
2699*096d96e7SZhenzhong Duan                                      __func__, "iec inv")) {
2700*096d96e7SZhenzhong Duan         return false;
2701*096d96e7SZhenzhong Duan     }
2702*096d96e7SZhenzhong Duan 
27037feb51b7SPeter Xu     trace_vtd_inv_desc_iec(inv_desc->iec.granularity,
270402a2cbc8SPeter Xu                            inv_desc->iec.index,
270502a2cbc8SPeter Xu                            inv_desc->iec.index_mask);
270602a2cbc8SPeter Xu 
270702a2cbc8SPeter Xu     vtd_iec_notify_all(s, !inv_desc->iec.granularity,
270802a2cbc8SPeter Xu                        inv_desc->iec.index,
270902a2cbc8SPeter Xu                        inv_desc->iec.index_mask);
2710554f5e16SJason Wang     return true;
2711554f5e16SJason Wang }
271202a2cbc8SPeter Xu 
do_invalidate_device_tlb(VTDAddressSpace * vtd_dev_as,bool size,hwaddr addr)271335422553SClément Mathieu--Drif static void do_invalidate_device_tlb(VTDAddressSpace *vtd_dev_as,
271435422553SClément Mathieu--Drif                                      bool size, hwaddr addr)
271535422553SClément Mathieu--Drif {
271635422553SClément Mathieu--Drif     /*
271735422553SClément Mathieu--Drif      * According to ATS spec table 2.4:
271835422553SClément Mathieu--Drif      * S = 0, bits 15:12 = xxxx     range size: 4K
271935422553SClément Mathieu--Drif      * S = 1, bits 15:12 = xxx0     range size: 8K
272035422553SClément Mathieu--Drif      * S = 1, bits 15:12 = xx01     range size: 16K
272135422553SClément Mathieu--Drif      * S = 1, bits 15:12 = x011     range size: 32K
272235422553SClément Mathieu--Drif      * S = 1, bits 15:12 = 0111     range size: 64K
272335422553SClément Mathieu--Drif      * ...
272435422553SClément Mathieu--Drif      */
272535422553SClément Mathieu--Drif 
272635422553SClément Mathieu--Drif     IOMMUTLBEvent event;
272735422553SClément Mathieu--Drif     uint64_t sz;
272835422553SClément Mathieu--Drif 
272935422553SClément Mathieu--Drif     if (size) {
273035422553SClément Mathieu--Drif         sz = (VTD_PAGE_SIZE * 2) << cto64(addr >> VTD_PAGE_SHIFT);
273135422553SClément Mathieu--Drif         addr &= ~(sz - 1);
273235422553SClément Mathieu--Drif     } else {
273335422553SClément Mathieu--Drif         sz = VTD_PAGE_SIZE;
273435422553SClément Mathieu--Drif     }
273535422553SClément Mathieu--Drif 
273635422553SClément Mathieu--Drif     event.type = IOMMU_NOTIFIER_DEVIOTLB_UNMAP;
273735422553SClément Mathieu--Drif     event.entry.target_as = &vtd_dev_as->as;
273835422553SClément Mathieu--Drif     event.entry.addr_mask = sz - 1;
273935422553SClément Mathieu--Drif     event.entry.iova = addr;
274035422553SClément Mathieu--Drif     event.entry.perm = IOMMU_NONE;
274135422553SClément Mathieu--Drif     event.entry.translated_addr = 0;
274235422553SClément Mathieu--Drif     memory_region_notify_iommu(&vtd_dev_as->iommu, 0, event);
274335422553SClément Mathieu--Drif }
274435422553SClément Mathieu--Drif 
vtd_process_device_iotlb_desc(IntelIOMMUState * s,VTDInvDesc * inv_desc)2745554f5e16SJason Wang static bool vtd_process_device_iotlb_desc(IntelIOMMUState *s,
2746554f5e16SJason Wang                                           VTDInvDesc *inv_desc)
2747554f5e16SJason Wang {
2748554f5e16SJason Wang     VTDAddressSpace *vtd_dev_as;
2749554f5e16SJason Wang     hwaddr addr;
2750554f5e16SJason Wang     uint16_t sid;
2751554f5e16SJason Wang     bool size;
27528e761fb6SZhenzhong Duan     uint64_t mask[4] = {VTD_INV_DESC_DEVICE_IOTLB_RSVD_LO,
27538e761fb6SZhenzhong Duan                         VTD_INV_DESC_DEVICE_IOTLB_RSVD_HI,
27548e761fb6SZhenzhong Duan                         VTD_INV_DESC_ALL_ONE, VTD_INV_DESC_ALL_ONE};
27558e761fb6SZhenzhong Duan 
27568e761fb6SZhenzhong Duan     if (!vtd_inv_desc_reserved_check(s, inv_desc, mask, false,
27578e761fb6SZhenzhong Duan                                      __func__, "dev-iotlb inv")) {
27588e761fb6SZhenzhong Duan         return false;
27598e761fb6SZhenzhong Duan     }
2760554f5e16SJason Wang 
2761554f5e16SJason Wang     addr = VTD_INV_DESC_DEVICE_IOTLB_ADDR(inv_desc->hi);
2762554f5e16SJason Wang     sid = VTD_INV_DESC_DEVICE_IOTLB_SID(inv_desc->lo);
2763554f5e16SJason Wang     size = VTD_INV_DESC_DEVICE_IOTLB_SIZE(inv_desc->hi);
2764554f5e16SJason Wang 
2765da8d439cSJason Wang     /*
2766da8d439cSJason Wang      * Using sid is OK since the guest should have finished the
2767da8d439cSJason Wang      * initialization of both the bus and device.
2768da8d439cSJason Wang      */
2769da8d439cSJason Wang     vtd_dev_as = vtd_get_as_by_sid(s, sid);
2770554f5e16SJason Wang     if (!vtd_dev_as) {
2771554f5e16SJason Wang         goto done;
2772554f5e16SJason Wang     }
2773554f5e16SJason Wang 
277435422553SClément Mathieu--Drif     do_invalidate_device_tlb(vtd_dev_as, size, addr);
2775554f5e16SJason Wang 
2776554f5e16SJason Wang done:
277702a2cbc8SPeter Xu     return true;
277802a2cbc8SPeter Xu }
277902a2cbc8SPeter Xu 
vtd_process_inv_desc(IntelIOMMUState * s)2780ed7b8fbcSLe Tan static bool vtd_process_inv_desc(IntelIOMMUState *s)
2781ed7b8fbcSLe Tan {
2782ed7b8fbcSLe Tan     VTDInvDesc inv_desc;
2783ed7b8fbcSLe Tan     uint8_t desc_type;
2784ed7b8fbcSLe Tan 
27857feb51b7SPeter Xu     trace_vtd_inv_qi_head(s->iq_head);
2786c0c1d351SLiu, Yi L     if (!vtd_get_inv_desc(s, &inv_desc)) {
2787ed7b8fbcSLe Tan         s->iq_last_desc_type = VTD_INV_DESC_NONE;
2788ed7b8fbcSLe Tan         return false;
2789ed7b8fbcSLe Tan     }
2790c0c1d351SLiu, Yi L 
279166316894SZhenzhong Duan     desc_type = VTD_INV_DESC_TYPE(inv_desc.lo);
2792ed7b8fbcSLe Tan     /* FIXME: should update at first or at last? */
2793ed7b8fbcSLe Tan     s->iq_last_desc_type = desc_type;
2794ed7b8fbcSLe Tan 
2795ed7b8fbcSLe Tan     switch (desc_type) {
2796ed7b8fbcSLe Tan     case VTD_INV_DESC_CC:
2797bc535e59SPeter Xu         trace_vtd_inv_desc("context-cache", inv_desc.hi, inv_desc.lo);
2798d92fa2dcSLe Tan         if (!vtd_process_context_cache_desc(s, &inv_desc)) {
2799d92fa2dcSLe Tan             return false;
2800d92fa2dcSLe Tan         }
2801ed7b8fbcSLe Tan         break;
2802ed7b8fbcSLe Tan 
2803ed7b8fbcSLe Tan     case VTD_INV_DESC_IOTLB:
2804bc535e59SPeter Xu         trace_vtd_inv_desc("iotlb", inv_desc.hi, inv_desc.lo);
2805b5a280c0SLe Tan         if (!vtd_process_iotlb_desc(s, &inv_desc)) {
2806b5a280c0SLe Tan             return false;
2807b5a280c0SLe Tan         }
2808ed7b8fbcSLe Tan         break;
2809ed7b8fbcSLe Tan 
2810ed7b8fbcSLe Tan     case VTD_INV_DESC_WAIT:
2811bc535e59SPeter Xu         trace_vtd_inv_desc("wait", inv_desc.hi, inv_desc.lo);
2812ed7b8fbcSLe Tan         if (!vtd_process_wait_desc(s, &inv_desc)) {
2813ed7b8fbcSLe Tan             return false;
2814ed7b8fbcSLe Tan         }
2815ed7b8fbcSLe Tan         break;
2816ed7b8fbcSLe Tan 
2817b7910472SPeter Xu     case VTD_INV_DESC_IEC:
2818bc535e59SPeter Xu         trace_vtd_inv_desc("iec", inv_desc.hi, inv_desc.lo);
281902a2cbc8SPeter Xu         if (!vtd_process_inv_iec_desc(s, &inv_desc)) {
282002a2cbc8SPeter Xu             return false;
282102a2cbc8SPeter Xu         }
2822b7910472SPeter Xu         break;
2823b7910472SPeter Xu 
2824554f5e16SJason Wang     case VTD_INV_DESC_DEVICE:
28257feb51b7SPeter Xu         trace_vtd_inv_desc("device", inv_desc.hi, inv_desc.lo);
2826554f5e16SJason Wang         if (!vtd_process_device_iotlb_desc(s, &inv_desc)) {
2827554f5e16SJason Wang             return false;
2828554f5e16SJason Wang         }
2829554f5e16SJason Wang         break;
2830554f5e16SJason Wang 
28313b52cea8SZhenzhong Duan     /*
28323b52cea8SZhenzhong Duan      * TODO: the entity of below two cases will be implemented in future series.
28333b52cea8SZhenzhong Duan      * To make guest (which integrates scalable mode support patch set in
28343b52cea8SZhenzhong Duan      * iommu driver) work, just return true is enough so far.
28353b52cea8SZhenzhong Duan      */
28363b52cea8SZhenzhong Duan     case VTD_INV_DESC_PC:
28373b52cea8SZhenzhong Duan     case VTD_INV_DESC_PIOTLB:
28383b52cea8SZhenzhong Duan         if (s->scalable_mode) {
28393b52cea8SZhenzhong Duan             break;
28403b52cea8SZhenzhong Duan         }
28413b52cea8SZhenzhong Duan     /* fallthrough */
2842ed7b8fbcSLe Tan     default:
2843095955b2SPeter Xu         error_report_once("%s: invalid inv desc: hi=%"PRIx64", lo=%"PRIx64
2844095955b2SPeter Xu                           " (unknown type)", __func__, inv_desc.hi,
2845095955b2SPeter Xu                           inv_desc.lo);
2846ed7b8fbcSLe Tan         return false;
2847ed7b8fbcSLe Tan     }
2848ed7b8fbcSLe Tan     s->iq_head++;
2849ed7b8fbcSLe Tan     if (s->iq_head == s->iq_size) {
2850ed7b8fbcSLe Tan         s->iq_head = 0;
2851ed7b8fbcSLe Tan     }
2852ed7b8fbcSLe Tan     return true;
2853ed7b8fbcSLe Tan }
2854ed7b8fbcSLe Tan 
2855ed7b8fbcSLe Tan /* Try to fetch and process more Invalidation Descriptors */
vtd_fetch_inv_desc(IntelIOMMUState * s)2856ed7b8fbcSLe Tan static void vtd_fetch_inv_desc(IntelIOMMUState *s)
2857ed7b8fbcSLe Tan {
2858a4544c45SLiu Yi L     int qi_shift;
2859a4544c45SLiu Yi L 
2860a4544c45SLiu Yi L     /* Refer to 10.4.23 of VT-d spec 3.0 */
2861a4544c45SLiu Yi L     qi_shift = s->iq_dw ? VTD_IQH_QH_SHIFT_5 : VTD_IQH_QH_SHIFT_4;
2862a4544c45SLiu Yi L 
28637feb51b7SPeter Xu     trace_vtd_inv_qi_fetch();
28647feb51b7SPeter Xu 
2865ed7b8fbcSLe Tan     if (s->iq_tail >= s->iq_size) {
2866ed7b8fbcSLe Tan         /* Detects an invalid Tail pointer */
28674e4abd11SPeter Xu         error_report_once("%s: detected invalid QI tail "
28684e4abd11SPeter Xu                           "(tail=0x%x, size=0x%x)",
28694e4abd11SPeter Xu                           __func__, s->iq_tail, s->iq_size);
2870ed7b8fbcSLe Tan         vtd_handle_inv_queue_error(s);
2871ed7b8fbcSLe Tan         return;
2872ed7b8fbcSLe Tan     }
2873ed7b8fbcSLe Tan     while (s->iq_head != s->iq_tail) {
2874ed7b8fbcSLe Tan         if (!vtd_process_inv_desc(s)) {
2875ed7b8fbcSLe Tan             /* Invalidation Queue Errors */
2876ed7b8fbcSLe Tan             vtd_handle_inv_queue_error(s);
2877ed7b8fbcSLe Tan             break;
2878ed7b8fbcSLe Tan         }
2879ed7b8fbcSLe Tan         /* Must update the IQH_REG in time */
2880ed7b8fbcSLe Tan         vtd_set_quad_raw(s, DMAR_IQH_REG,
2881a4544c45SLiu Yi L                          (((uint64_t)(s->iq_head)) << qi_shift) &
2882ed7b8fbcSLe Tan                          VTD_IQH_QH_MASK);
2883ed7b8fbcSLe Tan     }
2884ed7b8fbcSLe Tan }
2885ed7b8fbcSLe Tan 
2886ed7b8fbcSLe Tan /* Handle write to Invalidation Queue Tail Register */
vtd_handle_iqt_write(IntelIOMMUState * s)2887ed7b8fbcSLe Tan static void vtd_handle_iqt_write(IntelIOMMUState *s)
2888ed7b8fbcSLe Tan {
2889ed7b8fbcSLe Tan     uint64_t val = vtd_get_quad_raw(s, DMAR_IQT_REG);
2890ed7b8fbcSLe Tan 
2891c0c1d351SLiu, Yi L     if (s->iq_dw && (val & VTD_IQT_QT_256_RSV_BIT)) {
2892c0c1d351SLiu, Yi L         error_report_once("%s: RSV bit is set: val=0x%"PRIx64,
2893c0c1d351SLiu, Yi L                           __func__, val);
2894e70e83f5SZhenzhong Duan         vtd_handle_inv_queue_error(s);
2895c0c1d351SLiu, Yi L         return;
2896c0c1d351SLiu, Yi L     }
2897c0c1d351SLiu, Yi L     s->iq_tail = VTD_IQT_QT(s->iq_dw, val);
28987feb51b7SPeter Xu     trace_vtd_inv_qi_tail(s->iq_tail);
28997feb51b7SPeter Xu 
2900ed7b8fbcSLe Tan     if (s->qi_enabled && !(vtd_get_long_raw(s, DMAR_FSTS_REG) & VTD_FSTS_IQE)) {
2901ed7b8fbcSLe Tan         /* Process Invalidation Queue here */
2902ed7b8fbcSLe Tan         vtd_fetch_inv_desc(s);
2903ed7b8fbcSLe Tan     }
2904ed7b8fbcSLe Tan }
2905ed7b8fbcSLe Tan 
vtd_handle_fsts_write(IntelIOMMUState * s)29061da12ec4SLe Tan static void vtd_handle_fsts_write(IntelIOMMUState *s)
29071da12ec4SLe Tan {
29081da12ec4SLe Tan     uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG);
29091da12ec4SLe Tan     uint32_t fectl_reg = vtd_get_long_raw(s, DMAR_FECTL_REG);
29101da12ec4SLe Tan     uint32_t status_fields = VTD_FSTS_PFO | VTD_FSTS_PPF | VTD_FSTS_IQE;
29111da12ec4SLe Tan 
29121da12ec4SLe Tan     if ((fectl_reg & VTD_FECTL_IP) && !(fsts_reg & status_fields)) {
29131da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
29147feb51b7SPeter Xu         trace_vtd_fsts_clear_ip();
29151da12ec4SLe Tan     }
2916ed7b8fbcSLe Tan     /* FIXME: when IQE is Clear, should we try to fetch some Invalidation
2917ed7b8fbcSLe Tan      * Descriptors if there are any when Queued Invalidation is enabled?
2918ed7b8fbcSLe Tan      */
29191da12ec4SLe Tan }
29201da12ec4SLe Tan 
vtd_handle_fectl_write(IntelIOMMUState * s)29211da12ec4SLe Tan static void vtd_handle_fectl_write(IntelIOMMUState *s)
29221da12ec4SLe Tan {
29231da12ec4SLe Tan     uint32_t fectl_reg;
29241da12ec4SLe Tan     /* FIXME: when software clears the IM field, check the IP field. But do we
29251da12ec4SLe Tan      * need to compare the old value and the new value to conclude that
29261da12ec4SLe Tan      * software clears the IM field? Or just check if the IM field is zero?
29271da12ec4SLe Tan      */
29281da12ec4SLe Tan     fectl_reg = vtd_get_long_raw(s, DMAR_FECTL_REG);
29297feb51b7SPeter Xu 
29307feb51b7SPeter Xu     trace_vtd_reg_write_fectl(fectl_reg);
29317feb51b7SPeter Xu 
29321da12ec4SLe Tan     if ((fectl_reg & VTD_FECTL_IP) && !(fectl_reg & VTD_FECTL_IM)) {
29331da12ec4SLe Tan         vtd_generate_interrupt(s, DMAR_FEADDR_REG, DMAR_FEDATA_REG);
29341da12ec4SLe Tan         vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0);
29351da12ec4SLe Tan     }
29361da12ec4SLe Tan }
29371da12ec4SLe Tan 
vtd_handle_ics_write(IntelIOMMUState * s)2938ed7b8fbcSLe Tan static void vtd_handle_ics_write(IntelIOMMUState *s)
2939ed7b8fbcSLe Tan {
2940ed7b8fbcSLe Tan     uint32_t ics_reg = vtd_get_long_raw(s, DMAR_ICS_REG);
2941ed7b8fbcSLe Tan     uint32_t iectl_reg = vtd_get_long_raw(s, DMAR_IECTL_REG);
2942ed7b8fbcSLe Tan 
2943ed7b8fbcSLe Tan     if ((iectl_reg & VTD_IECTL_IP) && !(ics_reg & VTD_ICS_IWC)) {
29447feb51b7SPeter Xu         trace_vtd_reg_ics_clear_ip();
2945ed7b8fbcSLe Tan         vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
2946ed7b8fbcSLe Tan     }
2947ed7b8fbcSLe Tan }
2948ed7b8fbcSLe Tan 
vtd_handle_iectl_write(IntelIOMMUState * s)2949ed7b8fbcSLe Tan static void vtd_handle_iectl_write(IntelIOMMUState *s)
2950ed7b8fbcSLe Tan {
2951ed7b8fbcSLe Tan     uint32_t iectl_reg;
2952ed7b8fbcSLe Tan     /* FIXME: when software clears the IM field, check the IP field. But do we
2953ed7b8fbcSLe Tan      * need to compare the old value and the new value to conclude that
2954ed7b8fbcSLe Tan      * software clears the IM field? Or just check if the IM field is zero?
2955ed7b8fbcSLe Tan      */
2956ed7b8fbcSLe Tan     iectl_reg = vtd_get_long_raw(s, DMAR_IECTL_REG);
29577feb51b7SPeter Xu 
29587feb51b7SPeter Xu     trace_vtd_reg_write_iectl(iectl_reg);
29597feb51b7SPeter Xu 
2960ed7b8fbcSLe Tan     if ((iectl_reg & VTD_IECTL_IP) && !(iectl_reg & VTD_IECTL_IM)) {
2961ed7b8fbcSLe Tan         vtd_generate_interrupt(s, DMAR_IEADDR_REG, DMAR_IEDATA_REG);
2962ed7b8fbcSLe Tan         vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0);
2963ed7b8fbcSLe Tan     }
2964ed7b8fbcSLe Tan }
2965ed7b8fbcSLe Tan 
vtd_mem_read(void * opaque,hwaddr addr,unsigned size)29661da12ec4SLe Tan static uint64_t vtd_mem_read(void *opaque, hwaddr addr, unsigned size)
29671da12ec4SLe Tan {
29681da12ec4SLe Tan     IntelIOMMUState *s = opaque;
29691da12ec4SLe Tan     uint64_t val;
29701da12ec4SLe Tan 
29717feb51b7SPeter Xu     trace_vtd_reg_read(addr, size);
29727feb51b7SPeter Xu 
29731da12ec4SLe Tan     if (addr + size > DMAR_REG_SIZE) {
29741376211fSPeter Xu         error_report_once("%s: MMIO over range: addr=0x%" PRIx64
297573beb01eSPeter Xu                           " size=0x%x", __func__, addr, size);
29761da12ec4SLe Tan         return (uint64_t)-1;
29771da12ec4SLe Tan     }
29781da12ec4SLe Tan 
29791da12ec4SLe Tan     switch (addr) {
29801da12ec4SLe Tan     /* Root Table Address Register, 64-bit */
29811da12ec4SLe Tan     case DMAR_RTADDR_REG:
29828fdee711SYi Sun         val = vtd_get_quad_raw(s, DMAR_RTADDR_REG);
29831da12ec4SLe Tan         if (size == 4) {
29848fdee711SYi Sun             val = val & ((1ULL << 32) - 1);
29851da12ec4SLe Tan         }
29861da12ec4SLe Tan         break;
29871da12ec4SLe Tan 
29881da12ec4SLe Tan     case DMAR_RTADDR_REG_HI:
29891da12ec4SLe Tan         assert(size == 4);
29908fdee711SYi Sun         val = vtd_get_quad_raw(s, DMAR_RTADDR_REG) >> 32;
29911da12ec4SLe Tan         break;
29921da12ec4SLe Tan 
2993ed7b8fbcSLe Tan     /* Invalidation Queue Address Register, 64-bit */
2994ed7b8fbcSLe Tan     case DMAR_IQA_REG:
299551545775Syeeli         val = s->iq |
299651545775Syeeli               (vtd_get_quad(s, DMAR_IQA_REG) &
299751545775Syeeli               (VTD_IQA_QS | VTD_IQA_DW_MASK));
2998ed7b8fbcSLe Tan         if (size == 4) {
2999ed7b8fbcSLe Tan             val = val & ((1ULL << 32) - 1);
3000ed7b8fbcSLe Tan         }
3001ed7b8fbcSLe Tan         break;
3002ed7b8fbcSLe Tan 
3003ed7b8fbcSLe Tan     case DMAR_IQA_REG_HI:
3004ed7b8fbcSLe Tan         assert(size == 4);
3005ed7b8fbcSLe Tan         val = s->iq >> 32;
3006ed7b8fbcSLe Tan         break;
3007ed7b8fbcSLe Tan 
30081da12ec4SLe Tan     default:
30091da12ec4SLe Tan         if (size == 4) {
30101da12ec4SLe Tan             val = vtd_get_long(s, addr);
30111da12ec4SLe Tan         } else {
30121da12ec4SLe Tan             val = vtd_get_quad(s, addr);
30131da12ec4SLe Tan         }
30141da12ec4SLe Tan     }
30157feb51b7SPeter Xu 
30161da12ec4SLe Tan     return val;
30171da12ec4SLe Tan }
30181da12ec4SLe Tan 
vtd_mem_write(void * opaque,hwaddr addr,uint64_t val,unsigned size)30191da12ec4SLe Tan static void vtd_mem_write(void *opaque, hwaddr addr,
30201da12ec4SLe Tan                           uint64_t val, unsigned size)
30211da12ec4SLe Tan {
30221da12ec4SLe Tan     IntelIOMMUState *s = opaque;
30231da12ec4SLe Tan 
30247feb51b7SPeter Xu     trace_vtd_reg_write(addr, size, val);
30257feb51b7SPeter Xu 
30261da12ec4SLe Tan     if (addr + size > DMAR_REG_SIZE) {
30271376211fSPeter Xu         error_report_once("%s: MMIO over range: addr=0x%" PRIx64
302873beb01eSPeter Xu                           " size=0x%x", __func__, addr, size);
30291da12ec4SLe Tan         return;
30301da12ec4SLe Tan     }
30311da12ec4SLe Tan 
30321da12ec4SLe Tan     switch (addr) {
30331da12ec4SLe Tan     /* Global Command Register, 32-bit */
30341da12ec4SLe Tan     case DMAR_GCMD_REG:
30351da12ec4SLe Tan         vtd_set_long(s, addr, val);
30361da12ec4SLe Tan         vtd_handle_gcmd_write(s);
30371da12ec4SLe Tan         break;
30381da12ec4SLe Tan 
30391da12ec4SLe Tan     /* Context Command Register, 64-bit */
30401da12ec4SLe Tan     case DMAR_CCMD_REG:
30411da12ec4SLe Tan         if (size == 4) {
30421da12ec4SLe Tan             vtd_set_long(s, addr, val);
30431da12ec4SLe Tan         } else {
30441da12ec4SLe Tan             vtd_set_quad(s, addr, val);
30451da12ec4SLe Tan             vtd_handle_ccmd_write(s);
30461da12ec4SLe Tan         }
30471da12ec4SLe Tan         break;
30481da12ec4SLe Tan 
30491da12ec4SLe Tan     case DMAR_CCMD_REG_HI:
30501da12ec4SLe Tan         assert(size == 4);
30511da12ec4SLe Tan         vtd_set_long(s, addr, val);
30521da12ec4SLe Tan         vtd_handle_ccmd_write(s);
30531da12ec4SLe Tan         break;
30541da12ec4SLe Tan 
30551da12ec4SLe Tan     /* IOTLB Invalidation Register, 64-bit */
30561da12ec4SLe Tan     case DMAR_IOTLB_REG:
30571da12ec4SLe Tan         if (size == 4) {
30581da12ec4SLe Tan             vtd_set_long(s, addr, val);
30591da12ec4SLe Tan         } else {
30601da12ec4SLe Tan             vtd_set_quad(s, addr, val);
30611da12ec4SLe Tan             vtd_handle_iotlb_write(s);
30621da12ec4SLe Tan         }
30631da12ec4SLe Tan         break;
30641da12ec4SLe Tan 
30651da12ec4SLe Tan     case DMAR_IOTLB_REG_HI:
30661da12ec4SLe Tan         assert(size == 4);
30671da12ec4SLe Tan         vtd_set_long(s, addr, val);
30681da12ec4SLe Tan         vtd_handle_iotlb_write(s);
30691da12ec4SLe Tan         break;
30701da12ec4SLe Tan 
3071b5a280c0SLe Tan     /* Invalidate Address Register, 64-bit */
3072b5a280c0SLe Tan     case DMAR_IVA_REG:
3073b5a280c0SLe Tan         if (size == 4) {
3074b5a280c0SLe Tan             vtd_set_long(s, addr, val);
3075b5a280c0SLe Tan         } else {
3076b5a280c0SLe Tan             vtd_set_quad(s, addr, val);
3077b5a280c0SLe Tan         }
3078b5a280c0SLe Tan         break;
3079b5a280c0SLe Tan 
3080b5a280c0SLe Tan     case DMAR_IVA_REG_HI:
3081b5a280c0SLe Tan         assert(size == 4);
3082b5a280c0SLe Tan         vtd_set_long(s, addr, val);
3083b5a280c0SLe Tan         break;
3084b5a280c0SLe Tan 
30851da12ec4SLe Tan     /* Fault Status Register, 32-bit */
30861da12ec4SLe Tan     case DMAR_FSTS_REG:
30871da12ec4SLe Tan         assert(size == 4);
30881da12ec4SLe Tan         vtd_set_long(s, addr, val);
30891da12ec4SLe Tan         vtd_handle_fsts_write(s);
30901da12ec4SLe Tan         break;
30911da12ec4SLe Tan 
30921da12ec4SLe Tan     /* Fault Event Control Register, 32-bit */
30931da12ec4SLe Tan     case DMAR_FECTL_REG:
30941da12ec4SLe Tan         assert(size == 4);
30951da12ec4SLe Tan         vtd_set_long(s, addr, val);
30961da12ec4SLe Tan         vtd_handle_fectl_write(s);
30971da12ec4SLe Tan         break;
30981da12ec4SLe Tan 
30991da12ec4SLe Tan     /* Fault Event Data Register, 32-bit */
31001da12ec4SLe Tan     case DMAR_FEDATA_REG:
31011da12ec4SLe Tan         assert(size == 4);
31021da12ec4SLe Tan         vtd_set_long(s, addr, val);
31031da12ec4SLe Tan         break;
31041da12ec4SLe Tan 
31051da12ec4SLe Tan     /* Fault Event Address Register, 32-bit */
31061da12ec4SLe Tan     case DMAR_FEADDR_REG:
3107b7a7bb35SJan Kiszka         if (size == 4) {
31081da12ec4SLe Tan             vtd_set_long(s, addr, val);
3109b7a7bb35SJan Kiszka         } else {
3110b7a7bb35SJan Kiszka             /*
3111b7a7bb35SJan Kiszka              * While the register is 32-bit only, some guests (Xen...) write to
3112b7a7bb35SJan Kiszka              * it with 64-bit.
3113b7a7bb35SJan Kiszka              */
3114b7a7bb35SJan Kiszka             vtd_set_quad(s, addr, val);
3115b7a7bb35SJan Kiszka         }
31161da12ec4SLe Tan         break;
31171da12ec4SLe Tan 
31181da12ec4SLe Tan     /* Fault Event Upper Address Register, 32-bit */
31191da12ec4SLe Tan     case DMAR_FEUADDR_REG:
31201da12ec4SLe Tan         assert(size == 4);
31211da12ec4SLe Tan         vtd_set_long(s, addr, val);
31221da12ec4SLe Tan         break;
31231da12ec4SLe Tan 
31241da12ec4SLe Tan     /* Protected Memory Enable Register, 32-bit */
31251da12ec4SLe Tan     case DMAR_PMEN_REG:
31261da12ec4SLe Tan         assert(size == 4);
31271da12ec4SLe Tan         vtd_set_long(s, addr, val);
31281da12ec4SLe Tan         break;
31291da12ec4SLe Tan 
31301da12ec4SLe Tan     /* Root Table Address Register, 64-bit */
31311da12ec4SLe Tan     case DMAR_RTADDR_REG:
31321da12ec4SLe Tan         if (size == 4) {
31331da12ec4SLe Tan             vtd_set_long(s, addr, val);
31341da12ec4SLe Tan         } else {
31351da12ec4SLe Tan             vtd_set_quad(s, addr, val);
31361da12ec4SLe Tan         }
31371da12ec4SLe Tan         break;
31381da12ec4SLe Tan 
31391da12ec4SLe Tan     case DMAR_RTADDR_REG_HI:
31401da12ec4SLe Tan         assert(size == 4);
31411da12ec4SLe Tan         vtd_set_long(s, addr, val);
31421da12ec4SLe Tan         break;
31431da12ec4SLe Tan 
3144ed7b8fbcSLe Tan     /* Invalidation Queue Tail Register, 64-bit */
3145ed7b8fbcSLe Tan     case DMAR_IQT_REG:
3146ed7b8fbcSLe Tan         if (size == 4) {
3147ed7b8fbcSLe Tan             vtd_set_long(s, addr, val);
3148ed7b8fbcSLe Tan         } else {
3149ed7b8fbcSLe Tan             vtd_set_quad(s, addr, val);
3150ed7b8fbcSLe Tan         }
3151ed7b8fbcSLe Tan         vtd_handle_iqt_write(s);
3152ed7b8fbcSLe Tan         break;
3153ed7b8fbcSLe Tan 
3154ed7b8fbcSLe Tan     case DMAR_IQT_REG_HI:
3155ed7b8fbcSLe Tan         assert(size == 4);
3156ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3157ed7b8fbcSLe Tan         /* 19:63 of IQT_REG is RsvdZ, do nothing here */
3158ed7b8fbcSLe Tan         break;
3159ed7b8fbcSLe Tan 
3160ed7b8fbcSLe Tan     /* Invalidation Queue Address Register, 64-bit */
3161ed7b8fbcSLe Tan     case DMAR_IQA_REG:
3162ed7b8fbcSLe Tan         if (size == 4) {
3163ed7b8fbcSLe Tan             vtd_set_long(s, addr, val);
3164ed7b8fbcSLe Tan         } else {
3165ed7b8fbcSLe Tan             vtd_set_quad(s, addr, val);
3166ed7b8fbcSLe Tan         }
3167147a372eSJason Wang         vtd_update_iq_dw(s);
3168ed7b8fbcSLe Tan         break;
3169ed7b8fbcSLe Tan 
3170ed7b8fbcSLe Tan     case DMAR_IQA_REG_HI:
3171ed7b8fbcSLe Tan         assert(size == 4);
3172ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3173ed7b8fbcSLe Tan         break;
3174ed7b8fbcSLe Tan 
3175ed7b8fbcSLe Tan     /* Invalidation Completion Status Register, 32-bit */
3176ed7b8fbcSLe Tan     case DMAR_ICS_REG:
3177ed7b8fbcSLe Tan         assert(size == 4);
3178ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3179ed7b8fbcSLe Tan         vtd_handle_ics_write(s);
3180ed7b8fbcSLe Tan         break;
3181ed7b8fbcSLe Tan 
3182ed7b8fbcSLe Tan     /* Invalidation Event Control Register, 32-bit */
3183ed7b8fbcSLe Tan     case DMAR_IECTL_REG:
3184ed7b8fbcSLe Tan         assert(size == 4);
3185ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3186ed7b8fbcSLe Tan         vtd_handle_iectl_write(s);
3187ed7b8fbcSLe Tan         break;
3188ed7b8fbcSLe Tan 
3189ed7b8fbcSLe Tan     /* Invalidation Event Data Register, 32-bit */
3190ed7b8fbcSLe Tan     case DMAR_IEDATA_REG:
3191ed7b8fbcSLe Tan         assert(size == 4);
3192ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3193ed7b8fbcSLe Tan         break;
3194ed7b8fbcSLe Tan 
3195ed7b8fbcSLe Tan     /* Invalidation Event Address Register, 32-bit */
3196ed7b8fbcSLe Tan     case DMAR_IEADDR_REG:
3197ed7b8fbcSLe Tan         assert(size == 4);
3198ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3199ed7b8fbcSLe Tan         break;
3200ed7b8fbcSLe Tan 
3201ed7b8fbcSLe Tan     /* Invalidation Event Upper Address Register, 32-bit */
3202ed7b8fbcSLe Tan     case DMAR_IEUADDR_REG:
3203ed7b8fbcSLe Tan         assert(size == 4);
3204ed7b8fbcSLe Tan         vtd_set_long(s, addr, val);
3205ed7b8fbcSLe Tan         break;
3206ed7b8fbcSLe Tan 
32071da12ec4SLe Tan     /* Fault Recording Registers, 128-bit */
32081da12ec4SLe Tan     case DMAR_FRCD_REG_0_0:
32091da12ec4SLe Tan         if (size == 4) {
32101da12ec4SLe Tan             vtd_set_long(s, addr, val);
32111da12ec4SLe Tan         } else {
32121da12ec4SLe Tan             vtd_set_quad(s, addr, val);
32131da12ec4SLe Tan         }
32141da12ec4SLe Tan         break;
32151da12ec4SLe Tan 
32161da12ec4SLe Tan     case DMAR_FRCD_REG_0_1:
32171da12ec4SLe Tan         assert(size == 4);
32181da12ec4SLe Tan         vtd_set_long(s, addr, val);
32191da12ec4SLe Tan         break;
32201da12ec4SLe Tan 
32211da12ec4SLe Tan     case DMAR_FRCD_REG_0_2:
32221da12ec4SLe Tan         if (size == 4) {
32231da12ec4SLe Tan             vtd_set_long(s, addr, val);
32241da12ec4SLe Tan         } else {
32251da12ec4SLe Tan             vtd_set_quad(s, addr, val);
32261da12ec4SLe Tan             /* May clear bit 127 (Fault), update PPF */
32271da12ec4SLe Tan             vtd_update_fsts_ppf(s);
32281da12ec4SLe Tan         }
32291da12ec4SLe Tan         break;
32301da12ec4SLe Tan 
32311da12ec4SLe Tan     case DMAR_FRCD_REG_0_3:
32321da12ec4SLe Tan         assert(size == 4);
32331da12ec4SLe Tan         vtd_set_long(s, addr, val);
32341da12ec4SLe Tan         /* May clear bit 127 (Fault), update PPF */
32351da12ec4SLe Tan         vtd_update_fsts_ppf(s);
32361da12ec4SLe Tan         break;
32371da12ec4SLe Tan 
3238a5861439SPeter Xu     case DMAR_IRTA_REG:
3239a5861439SPeter Xu         if (size == 4) {
3240a5861439SPeter Xu             vtd_set_long(s, addr, val);
3241a5861439SPeter Xu         } else {
3242a5861439SPeter Xu             vtd_set_quad(s, addr, val);
3243a5861439SPeter Xu         }
3244a5861439SPeter Xu         break;
3245a5861439SPeter Xu 
3246a5861439SPeter Xu     case DMAR_IRTA_REG_HI:
3247a5861439SPeter Xu         assert(size == 4);
3248a5861439SPeter Xu         vtd_set_long(s, addr, val);
3249a5861439SPeter Xu         break;
3250a5861439SPeter Xu 
32511da12ec4SLe Tan     default:
32521da12ec4SLe Tan         if (size == 4) {
32531da12ec4SLe Tan             vtd_set_long(s, addr, val);
32541da12ec4SLe Tan         } else {
32551da12ec4SLe Tan             vtd_set_quad(s, addr, val);
32561da12ec4SLe Tan         }
32571da12ec4SLe Tan     }
32581da12ec4SLe Tan }
32591da12ec4SLe Tan 
vtd_iommu_translate(IOMMUMemoryRegion * iommu,hwaddr addr,IOMMUAccessFlags flag,int iommu_idx)32603df9d748SAlexey Kardashevskiy static IOMMUTLBEntry vtd_iommu_translate(IOMMUMemoryRegion *iommu, hwaddr addr,
32612c91bcf2SPeter Maydell                                          IOMMUAccessFlags flag, int iommu_idx)
32621da12ec4SLe Tan {
32631da12ec4SLe Tan     VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu);
32641da12ec4SLe Tan     IntelIOMMUState *s = vtd_as->iommu_state;
3265b9313021SPeter Xu     IOMMUTLBEntry iotlb = {
3266b9313021SPeter Xu         /* We'll fill in the rest later. */
32671da12ec4SLe Tan         .target_as = &address_space_memory,
32681da12ec4SLe Tan     };
3269b9313021SPeter Xu     bool success;
32701da12ec4SLe Tan 
3271b9313021SPeter Xu     if (likely(s->dmar_enabled)) {
3272b9313021SPeter Xu         success = vtd_do_iommu_translate(vtd_as, vtd_as->bus, vtd_as->devfn,
3273b9313021SPeter Xu                                          addr, flag & IOMMU_WO, &iotlb);
3274b9313021SPeter Xu     } else {
32751da12ec4SLe Tan         /* DMAR disabled, passthrough, use 4k-page*/
3276b9313021SPeter Xu         iotlb.iova = addr & VTD_PAGE_MASK_4K;
3277b9313021SPeter Xu         iotlb.translated_addr = addr & VTD_PAGE_MASK_4K;
3278b9313021SPeter Xu         iotlb.addr_mask = ~VTD_PAGE_MASK_4K;
3279b9313021SPeter Xu         iotlb.perm = IOMMU_RW;
3280b9313021SPeter Xu         success = true;
32811da12ec4SLe Tan     }
32821da12ec4SLe Tan 
3283b9313021SPeter Xu     if (likely(success)) {
32847feb51b7SPeter Xu         trace_vtd_dmar_translate(pci_bus_num(vtd_as->bus),
32857feb51b7SPeter Xu                                  VTD_PCI_SLOT(vtd_as->devfn),
32867feb51b7SPeter Xu                                  VTD_PCI_FUNC(vtd_as->devfn),
3287b9313021SPeter Xu                                  iotlb.iova, iotlb.translated_addr,
3288b9313021SPeter Xu                                  iotlb.addr_mask);
3289b9313021SPeter Xu     } else {
32904e4abd11SPeter Xu         error_report_once("%s: detected translation failure "
32914e4abd11SPeter Xu                           "(dev=%02x:%02x:%02x, iova=0x%" PRIx64 ")",
32924e4abd11SPeter Xu                           __func__, pci_bus_num(vtd_as->bus),
3293b9313021SPeter Xu                           VTD_PCI_SLOT(vtd_as->devfn),
3294b9313021SPeter Xu                           VTD_PCI_FUNC(vtd_as->devfn),
3295662b4b69SPeter Xu                           addr);
3296b9313021SPeter Xu     }
32977feb51b7SPeter Xu 
3298b9313021SPeter Xu     return iotlb;
32991da12ec4SLe Tan }
33001da12ec4SLe Tan 
vtd_iommu_notify_flag_changed(IOMMUMemoryRegion * iommu,IOMMUNotifierFlag old,IOMMUNotifierFlag new,Error ** errp)3301549d4005SEric Auger static int vtd_iommu_notify_flag_changed(IOMMUMemoryRegion *iommu,
33025bf3d319SPeter Xu                                          IOMMUNotifierFlag old,
3303549d4005SEric Auger                                          IOMMUNotifierFlag new,
3304549d4005SEric Auger                                          Error **errp)
33053cb3b154SAlex Williamson {
33063cb3b154SAlex Williamson     VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu);
3307dd4d607eSPeter Xu     IntelIOMMUState *s = vtd_as->iommu_state;
330809adb0e0SJason Wang     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
33093cb3b154SAlex Williamson 
3310b8ffd7d6SJason Wang     /* TODO: add support for VFIO and vhost users */
3311b8ffd7d6SJason Wang     if (s->snoop_control) {
3312250227f4SJason Wang         error_setg_errno(errp, ENOTSUP,
3313b8ffd7d6SJason Wang                          "Snoop Control with vhost or VFIO is not supported");
3314b8ffd7d6SJason Wang         return -ENOTSUP;
3315b8ffd7d6SJason Wang     }
3316b8d78277SJason Wang     if (!s->caching_mode && (new & IOMMU_NOTIFIER_MAP)) {
3317b8d78277SJason Wang         error_setg_errno(errp, ENOTSUP,
3318b8d78277SJason Wang                          "device %02x.%02x.%x requires caching mode",
3319b8d78277SJason Wang                          pci_bus_num(vtd_as->bus), PCI_SLOT(vtd_as->devfn),
3320b8d78277SJason Wang                          PCI_FUNC(vtd_as->devfn));
3321b8d78277SJason Wang         return -ENOTSUP;
3322b8d78277SJason Wang     }
332309adb0e0SJason Wang     if (!x86_iommu->dt_supported && (new & IOMMU_NOTIFIER_DEVIOTLB_UNMAP)) {
332409adb0e0SJason Wang         error_setg_errno(errp, ENOTSUP,
332509adb0e0SJason Wang                          "device %02x.%02x.%x requires device IOTLB mode",
332609adb0e0SJason Wang                          pci_bus_num(vtd_as->bus), PCI_SLOT(vtd_as->devfn),
332709adb0e0SJason Wang                          PCI_FUNC(vtd_as->devfn));
332809adb0e0SJason Wang         return -ENOTSUP;
332909adb0e0SJason Wang     }
3330b8ffd7d6SJason Wang 
33314f8a62a9SPeter Xu     /* Update per-address-space notifier flags */
33324f8a62a9SPeter Xu     vtd_as->notifier_flags = new;
33334f8a62a9SPeter Xu 
3334dd4d607eSPeter Xu     if (old == IOMMU_NOTIFIER_NONE) {
3335b4a4ba0dSPeter Xu         QLIST_INSERT_HEAD(&s->vtd_as_with_notifiers, vtd_as, next);
3336b4a4ba0dSPeter Xu     } else if (new == IOMMU_NOTIFIER_NONE) {
3337b4a4ba0dSPeter Xu         QLIST_REMOVE(vtd_as, next);
3338dd4d607eSPeter Xu     }
3339549d4005SEric Auger     return 0;
33403cb3b154SAlex Williamson }
33413cb3b154SAlex Williamson 
vtd_post_load(void * opaque,int version_id)3342552a1e01SPeter Xu static int vtd_post_load(void *opaque, int version_id)
3343552a1e01SPeter Xu {
3344552a1e01SPeter Xu     IntelIOMMUState *iommu = opaque;
3345552a1e01SPeter Xu 
3346552a1e01SPeter Xu     /*
33472811af3bSPeter Xu      * We don't need to migrate the root_scalable because we can
33482811af3bSPeter Xu      * simply do the calculation after the loading is complete.  We
33492811af3bSPeter Xu      * can actually do similar things with root, dmar_enabled, etc.
33502811af3bSPeter Xu      * however since we've had them already so we'd better keep them
33512811af3bSPeter Xu      * for compatibility of migration.
33522811af3bSPeter Xu      */
33532811af3bSPeter Xu     vtd_update_scalable_state(iommu);
33542811af3bSPeter Xu 
3355147a372eSJason Wang     vtd_update_iq_dw(iommu);
3356147a372eSJason Wang 
3357ceb05895SJason Wang     /*
3358ceb05895SJason Wang      * Memory regions are dynamically turned on/off depending on
3359ceb05895SJason Wang      * context entry configurations from the guest. After migration,
3360ceb05895SJason Wang      * we need to make sure the memory regions are still correct.
3361ceb05895SJason Wang      */
3362ceb05895SJason Wang     vtd_switch_address_space_all(iommu);
3363ceb05895SJason Wang 
3364552a1e01SPeter Xu     return 0;
3365552a1e01SPeter Xu }
3366552a1e01SPeter Xu 
33671da12ec4SLe Tan static const VMStateDescription vtd_vmstate = {
33681da12ec4SLe Tan     .name = "iommu-intel",
33698cdcf3c1SPeter Xu     .version_id = 1,
33708cdcf3c1SPeter Xu     .minimum_version_id = 1,
33718cdcf3c1SPeter Xu     .priority = MIG_PRI_IOMMU,
3372552a1e01SPeter Xu     .post_load = vtd_post_load,
33739231a017SRichard Henderson     .fields = (const VMStateField[]) {
33748cdcf3c1SPeter Xu         VMSTATE_UINT64(root, IntelIOMMUState),
33758cdcf3c1SPeter Xu         VMSTATE_UINT64(intr_root, IntelIOMMUState),
33768cdcf3c1SPeter Xu         VMSTATE_UINT64(iq, IntelIOMMUState),
33778cdcf3c1SPeter Xu         VMSTATE_UINT32(intr_size, IntelIOMMUState),
33788cdcf3c1SPeter Xu         VMSTATE_UINT16(iq_head, IntelIOMMUState),
33798cdcf3c1SPeter Xu         VMSTATE_UINT16(iq_tail, IntelIOMMUState),
33808cdcf3c1SPeter Xu         VMSTATE_UINT16(iq_size, IntelIOMMUState),
33818cdcf3c1SPeter Xu         VMSTATE_UINT16(next_frcd_reg, IntelIOMMUState),
33828cdcf3c1SPeter Xu         VMSTATE_UINT8_ARRAY(csr, IntelIOMMUState, DMAR_REG_SIZE),
33838cdcf3c1SPeter Xu         VMSTATE_UINT8(iq_last_desc_type, IntelIOMMUState),
338481fb1e64SPeter Xu         VMSTATE_UNUSED(1),      /* bool root_extended is obsolete by VT-d */
33858cdcf3c1SPeter Xu         VMSTATE_BOOL(dmar_enabled, IntelIOMMUState),
33868cdcf3c1SPeter Xu         VMSTATE_BOOL(qi_enabled, IntelIOMMUState),
33878cdcf3c1SPeter Xu         VMSTATE_BOOL(intr_enabled, IntelIOMMUState),
33888cdcf3c1SPeter Xu         VMSTATE_BOOL(intr_eime, IntelIOMMUState),
33898cdcf3c1SPeter Xu         VMSTATE_END_OF_LIST()
33908cdcf3c1SPeter Xu     }
33911da12ec4SLe Tan };
33921da12ec4SLe Tan 
33931da12ec4SLe Tan static const MemoryRegionOps vtd_mem_ops = {
33941da12ec4SLe Tan     .read = vtd_mem_read,
33951da12ec4SLe Tan     .write = vtd_mem_write,
33961da12ec4SLe Tan     .endianness = DEVICE_LITTLE_ENDIAN,
33971da12ec4SLe Tan     .impl = {
33981da12ec4SLe Tan         .min_access_size = 4,
33991da12ec4SLe Tan         .max_access_size = 8,
34001da12ec4SLe Tan     },
34011da12ec4SLe Tan     .valid = {
34021da12ec4SLe Tan         .min_access_size = 4,
34031da12ec4SLe Tan         .max_access_size = 8,
34041da12ec4SLe Tan     },
34051da12ec4SLe Tan };
34061da12ec4SLe Tan 
34071da12ec4SLe Tan static Property vtd_properties[] = {
34081da12ec4SLe Tan     DEFINE_PROP_UINT32("version", IntelIOMMUState, version, 0),
3409e6b6af05SRadim Krčmář     DEFINE_PROP_ON_OFF_AUTO("eim", IntelIOMMUState, intr_eim,
3410e6b6af05SRadim Krčmář                             ON_OFF_AUTO_AUTO),
3411fb506e70SRadim Krčmář     DEFINE_PROP_BOOL("x-buggy-eim", IntelIOMMUState, buggy_eim, false),
34124b49b586SPeter Xu     DEFINE_PROP_UINT8("aw-bits", IntelIOMMUState, aw_bits,
341337f51384SPrasad Singamsetty                       VTD_HOST_ADDRESS_WIDTH),
34143b40f0e5SAviv Ben-David     DEFINE_PROP_BOOL("caching-mode", IntelIOMMUState, caching_mode, FALSE),
34154a4f219eSYi Sun     DEFINE_PROP_BOOL("x-scalable-mode", IntelIOMMUState, scalable_mode, FALSE),
3416b8ffd7d6SJason Wang     DEFINE_PROP_BOOL("snoop-control", IntelIOMMUState, snoop_control, false),
34171b2b1237SJason Wang     DEFINE_PROP_BOOL("x-pasid-mode", IntelIOMMUState, pasid, false),
3418ccc23bb0SPeter Xu     DEFINE_PROP_BOOL("dma-drain", IntelIOMMUState, dma_drain, true),
34198646d9c7SDavid Woodhouse     DEFINE_PROP_BOOL("dma-translation", IntelIOMMUState, dma_translation, true),
34206ce12bd2SZhenzhong Duan     DEFINE_PROP_BOOL("stale-tm", IntelIOMMUState, stale_tm, false),
34211da12ec4SLe Tan     DEFINE_PROP_END_OF_LIST(),
34221da12ec4SLe Tan };
34231da12ec4SLe Tan 
3424651e4cefSPeter Xu /* Read IRTE entry with specific index */
vtd_irte_get(IntelIOMMUState * iommu,uint16_t index,VTD_IR_TableEntry * entry,uint16_t sid,bool do_fault)3425c7016bf7SDavid Woodhouse static bool vtd_irte_get(IntelIOMMUState *iommu, uint16_t index,
3426c7016bf7SDavid Woodhouse                          VTD_IR_TableEntry *entry, uint16_t sid,
3427c7016bf7SDavid Woodhouse                          bool do_fault)
3428651e4cefSPeter Xu {
3429ede9c94aSPeter Xu     static const uint16_t vtd_svt_mask[VTD_SQ_MAX] = \
3430ede9c94aSPeter Xu         {0xffff, 0xfffb, 0xfff9, 0xfff8};
3431651e4cefSPeter Xu     dma_addr_t addr = 0x00;
3432ede9c94aSPeter Xu     uint16_t mask, source_id;
3433ede9c94aSPeter Xu     uint8_t bus, bus_max, bus_min;
3434651e4cefSPeter Xu 
34353c507c26SJan Kiszka     if (index >= iommu->intr_size) {
34363c507c26SJan Kiszka         error_report_once("%s: index too large: ind=0x%x",
34373c507c26SJan Kiszka                           __func__, index);
3438c7016bf7SDavid Woodhouse         if (do_fault) {
3439c7016bf7SDavid Woodhouse             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_INDEX_OVER, index);
3440c7016bf7SDavid Woodhouse         }
3441c7016bf7SDavid Woodhouse         return false;
34423c507c26SJan Kiszka     }
34433c507c26SJan Kiszka 
3444651e4cefSPeter Xu     addr = iommu->intr_root + index * sizeof(*entry);
3445ba06fe8aSPhilippe Mathieu-Daudé     if (dma_memory_read(&address_space_memory, addr,
3446ba06fe8aSPhilippe Mathieu-Daudé                         entry, sizeof(*entry), MEMTXATTRS_UNSPECIFIED)) {
34471376211fSPeter Xu         error_report_once("%s: read failed: ind=0x%x addr=0x%" PRIx64,
34481376211fSPeter Xu                           __func__, index, addr);
3449c7016bf7SDavid Woodhouse         if (do_fault) {
3450c7016bf7SDavid Woodhouse             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_ROOT_INVAL, index);
3451c7016bf7SDavid Woodhouse         }
3452c7016bf7SDavid Woodhouse         return false;
3453651e4cefSPeter Xu     }
3454651e4cefSPeter Xu 
3455642ba896SThomas Huth     entry->data[0] = le64_to_cpu(entry->data[0]);
3456642ba896SThomas Huth     entry->data[1] = le64_to_cpu(entry->data[1]);
3457642ba896SThomas Huth 
3458642ba896SThomas Huth     trace_vtd_ir_irte_get(index, entry->data[1], entry->data[0]);
34597feb51b7SPeter Xu 
3460c7016bf7SDavid Woodhouse     /*
3461c7016bf7SDavid Woodhouse      * The remaining potential fault conditions are "qualified" by the
3462c7016bf7SDavid Woodhouse      * Fault Processing Disable bit in the IRTE. Even "not present".
3463c7016bf7SDavid Woodhouse      * So just clear the do_fault flag if PFD is set, which will
3464c7016bf7SDavid Woodhouse      * prevent faults being raised.
3465c7016bf7SDavid Woodhouse      */
3466c7016bf7SDavid Woodhouse     if (entry->irte.fault_disable) {
3467c7016bf7SDavid Woodhouse         do_fault = false;
3468c7016bf7SDavid Woodhouse     }
3469c7016bf7SDavid Woodhouse 
3470bc38ee10SMichael S. Tsirkin     if (!entry->irte.present) {
34714e4abd11SPeter Xu         error_report_once("%s: detected non-present IRTE "
34724e4abd11SPeter Xu                           "(index=%u, high=0x%" PRIx64 ", low=0x%" PRIx64 ")",
3473642ba896SThomas Huth                           __func__, index, entry->data[1], entry->data[0]);
3474c7016bf7SDavid Woodhouse         if (do_fault) {
3475c7016bf7SDavid Woodhouse             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_ENTRY_P, index);
3476c7016bf7SDavid Woodhouse         }
3477c7016bf7SDavid Woodhouse         return false;
3478651e4cefSPeter Xu     }
3479651e4cefSPeter Xu 
3480bc38ee10SMichael S. Tsirkin     if (entry->irte.__reserved_0 || entry->irte.__reserved_1 ||
3481bc38ee10SMichael S. Tsirkin         entry->irte.__reserved_2) {
34824e4abd11SPeter Xu         error_report_once("%s: detected non-zero reserved IRTE "
34834e4abd11SPeter Xu                           "(index=%u, high=0x%" PRIx64 ", low=0x%" PRIx64 ")",
3484642ba896SThomas Huth                           __func__, index, entry->data[1], entry->data[0]);
3485c7016bf7SDavid Woodhouse         if (do_fault) {
3486c7016bf7SDavid Woodhouse             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_IRTE_RSVD, index);
3487c7016bf7SDavid Woodhouse         }
3488c7016bf7SDavid Woodhouse         return false;
3489651e4cefSPeter Xu     }
3490651e4cefSPeter Xu 
3491ede9c94aSPeter Xu     if (sid != X86_IOMMU_SID_INVALID) {
3492ede9c94aSPeter Xu         /* Validate IRTE SID */
3493642ba896SThomas Huth         source_id = entry->irte.source_id;
3494bc38ee10SMichael S. Tsirkin         switch (entry->irte.sid_vtype) {
3495ede9c94aSPeter Xu         case VTD_SVT_NONE:
3496ede9c94aSPeter Xu             break;
3497ede9c94aSPeter Xu 
3498ede9c94aSPeter Xu         case VTD_SVT_ALL:
3499bc38ee10SMichael S. Tsirkin             mask = vtd_svt_mask[entry->irte.sid_q];
3500ede9c94aSPeter Xu             if ((source_id & mask) != (sid & mask)) {
35014e4abd11SPeter Xu                 error_report_once("%s: invalid IRTE SID "
35024e4abd11SPeter Xu                                   "(index=%u, sid=%u, source_id=%u)",
35034e4abd11SPeter Xu                                   __func__, index, sid, source_id);
3504c7016bf7SDavid Woodhouse                 if (do_fault) {
3505c7016bf7SDavid Woodhouse                     vtd_report_ir_fault(iommu, sid, VTD_FR_IR_SID_ERR, index);
3506c7016bf7SDavid Woodhouse                 }
3507c7016bf7SDavid Woodhouse                 return false;
3508ede9c94aSPeter Xu             }
3509ede9c94aSPeter Xu             break;
3510ede9c94aSPeter Xu 
3511ede9c94aSPeter Xu         case VTD_SVT_BUS:
3512ede9c94aSPeter Xu             bus_max = source_id >> 8;
3513ede9c94aSPeter Xu             bus_min = source_id & 0xff;
3514ede9c94aSPeter Xu             bus = sid >> 8;
3515ede9c94aSPeter Xu             if (bus > bus_max || bus < bus_min) {
35164e4abd11SPeter Xu                 error_report_once("%s: invalid SVT_BUS "
35174e4abd11SPeter Xu                                   "(index=%u, bus=%u, min=%u, max=%u)",
35184e4abd11SPeter Xu                                   __func__, index, bus, bus_min, bus_max);
3519c7016bf7SDavid Woodhouse                 if (do_fault) {
3520c7016bf7SDavid Woodhouse                     vtd_report_ir_fault(iommu, sid, VTD_FR_IR_SID_ERR, index);
3521c7016bf7SDavid Woodhouse                 }
3522c7016bf7SDavid Woodhouse                 return false;
3523ede9c94aSPeter Xu             }
3524ede9c94aSPeter Xu             break;
3525ede9c94aSPeter Xu 
3526ede9c94aSPeter Xu         default:
35274e4abd11SPeter Xu             error_report_once("%s: detected invalid IRTE SVT "
35284e4abd11SPeter Xu                               "(index=%u, type=%d)", __func__,
35294e4abd11SPeter Xu                               index, entry->irte.sid_vtype);
3530ede9c94aSPeter Xu             /* Take this as verification failure. */
3531c7016bf7SDavid Woodhouse             if (do_fault) {
3532c7016bf7SDavid Woodhouse                 vtd_report_ir_fault(iommu, sid, VTD_FR_IR_SID_ERR, index);
3533c7016bf7SDavid Woodhouse             }
3534c7016bf7SDavid Woodhouse             return false;
3535ede9c94aSPeter Xu         }
3536ede9c94aSPeter Xu     }
3537651e4cefSPeter Xu 
3538c7016bf7SDavid Woodhouse     return true;
3539651e4cefSPeter Xu }
3540651e4cefSPeter Xu 
3541651e4cefSPeter Xu /* Fetch IRQ information of specific IR index */
vtd_remap_irq_get(IntelIOMMUState * iommu,uint16_t index,X86IOMMUIrq * irq,uint16_t sid,bool do_fault)3542c7016bf7SDavid Woodhouse static bool vtd_remap_irq_get(IntelIOMMUState *iommu, uint16_t index,
3543c7016bf7SDavid Woodhouse                               X86IOMMUIrq *irq, uint16_t sid, bool do_fault)
3544651e4cefSPeter Xu {
3545bc38ee10SMichael S. Tsirkin     VTD_IR_TableEntry irte = {};
3546651e4cefSPeter Xu 
3547c7016bf7SDavid Woodhouse     if (!vtd_irte_get(iommu, index, &irte, sid, do_fault)) {
3548c7016bf7SDavid Woodhouse         return false;
3549651e4cefSPeter Xu     }
3550651e4cefSPeter Xu 
3551bc38ee10SMichael S. Tsirkin     irq->trigger_mode = irte.irte.trigger_mode;
3552bc38ee10SMichael S. Tsirkin     irq->vector = irte.irte.vector;
3553bc38ee10SMichael S. Tsirkin     irq->delivery_mode = irte.irte.delivery_mode;
3554642ba896SThomas Huth     irq->dest = irte.irte.dest_id;
355528589311SJan Kiszka     if (!iommu->intr_eime) {
3556651e4cefSPeter Xu #define  VTD_IR_APIC_DEST_MASK         (0xff00ULL)
3557651e4cefSPeter Xu #define  VTD_IR_APIC_DEST_SHIFT        (8)
355828589311SJan Kiszka         irq->dest = (irq->dest & VTD_IR_APIC_DEST_MASK) >>
3559651e4cefSPeter Xu             VTD_IR_APIC_DEST_SHIFT;
356028589311SJan Kiszka     }
3561bc38ee10SMichael S. Tsirkin     irq->dest_mode = irte.irte.dest_mode;
3562bc38ee10SMichael S. Tsirkin     irq->redir_hint = irte.irte.redir_hint;
3563651e4cefSPeter Xu 
35647feb51b7SPeter Xu     trace_vtd_ir_remap(index, irq->trigger_mode, irq->vector,
35657feb51b7SPeter Xu                        irq->delivery_mode, irq->dest, irq->dest_mode);
3566651e4cefSPeter Xu 
3567c7016bf7SDavid Woodhouse     return true;
3568651e4cefSPeter Xu }
3569651e4cefSPeter Xu 
3570651e4cefSPeter Xu /* Interrupt remapping for MSI/MSI-X entry */
vtd_interrupt_remap_msi(IntelIOMMUState * iommu,MSIMessage * origin,MSIMessage * translated,uint16_t sid,bool do_fault)3571651e4cefSPeter Xu static int vtd_interrupt_remap_msi(IntelIOMMUState *iommu,
3572651e4cefSPeter Xu                                    MSIMessage *origin,
3573ede9c94aSPeter Xu                                    MSIMessage *translated,
3574c7016bf7SDavid Woodhouse                                    uint16_t sid, bool do_fault)
3575651e4cefSPeter Xu {
3576651e4cefSPeter Xu     VTD_IR_MSIAddress addr;
3577651e4cefSPeter Xu     uint16_t index;
357835c24501SSingh, Brijesh     X86IOMMUIrq irq = {};
3579651e4cefSPeter Xu 
3580651e4cefSPeter Xu     assert(origin && translated);
3581651e4cefSPeter Xu 
35827feb51b7SPeter Xu     trace_vtd_ir_remap_msi_req(origin->address, origin->data);
35837feb51b7SPeter Xu 
3584651e4cefSPeter Xu     if (!iommu || !iommu->intr_enabled) {
3585e7a3b91fSPeter Xu         memcpy(translated, origin, sizeof(*origin));
3586e7a3b91fSPeter Xu         goto out;
3587651e4cefSPeter Xu     }
3588651e4cefSPeter Xu 
3589651e4cefSPeter Xu     if (origin->address & VTD_MSI_ADDR_HI_MASK) {
35901376211fSPeter Xu         error_report_once("%s: MSI address high 32 bits non-zero detected: "
35911376211fSPeter Xu                           "address=0x%" PRIx64, __func__, origin->address);
3592c7016bf7SDavid Woodhouse         if (do_fault) {
3593c7016bf7SDavid Woodhouse             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_REQ_RSVD, 0);
3594c7016bf7SDavid Woodhouse         }
3595c7016bf7SDavid Woodhouse         return -EINVAL;
3596651e4cefSPeter Xu     }
3597651e4cefSPeter Xu 
3598651e4cefSPeter Xu     addr.data = origin->address & VTD_MSI_ADDR_LO_MASK;
35991a43713bSPeter Xu     if (addr.addr.__head != 0xfee) {
36001376211fSPeter Xu         error_report_once("%s: MSI address low 32 bit invalid: 0x%" PRIx32,
36011376211fSPeter Xu                           __func__, addr.data);
3602c7016bf7SDavid Woodhouse         if (do_fault) {
3603c7016bf7SDavid Woodhouse             vtd_report_ir_fault(iommu, sid, VTD_FR_IR_REQ_RSVD, 0);
3604c7016bf7SDavid Woodhouse         }
3605c7016bf7SDavid Woodhouse         return -EINVAL;
3606651e4cefSPeter Xu     }
3607651e4cefSPeter Xu 
3608651e4cefSPeter Xu     /* This is compatible mode. */
3609bc38ee10SMichael S. Tsirkin     if (addr.addr.int_mode != VTD_IR_INT_FORMAT_REMAP) {
3610e7a3b91fSPeter Xu         memcpy(translated, origin, sizeof(*origin));
3611e7a3b91fSPeter Xu         goto out;
3612651e4cefSPeter Xu     }
3613651e4cefSPeter Xu 
3614fcd80274SThomas Huth     index = addr.addr.index_h << 15 | addr.addr.index_l;
3615651e4cefSPeter Xu 
3616651e4cefSPeter Xu #define  VTD_IR_MSI_DATA_SUBHANDLE       (0x0000ffff)
3617651e4cefSPeter Xu #define  VTD_IR_MSI_DATA_RESERVED        (0xffff0000)
3618651e4cefSPeter Xu 
3619bc38ee10SMichael S. Tsirkin     if (addr.addr.sub_valid) {
3620651e4cefSPeter Xu         /* See VT-d spec 5.1.2.2 and 5.1.3 on subhandle */
3621651e4cefSPeter Xu         index += origin->data & VTD_IR_MSI_DATA_SUBHANDLE;
3622651e4cefSPeter Xu     }
3623651e4cefSPeter Xu 
3624c7016bf7SDavid Woodhouse     if (!vtd_remap_irq_get(iommu, index, &irq, sid, do_fault)) {
3625c7016bf7SDavid Woodhouse         return -EINVAL;
3626651e4cefSPeter Xu     }
3627651e4cefSPeter Xu 
3628bc38ee10SMichael S. Tsirkin     if (addr.addr.sub_valid) {
36297feb51b7SPeter Xu         trace_vtd_ir_remap_type("MSI");
3630651e4cefSPeter Xu         if (origin->data & VTD_IR_MSI_DATA_RESERVED) {
36314e4abd11SPeter Xu             error_report_once("%s: invalid IR MSI "
36324e4abd11SPeter Xu                               "(sid=%u, address=0x%" PRIx64
36334e4abd11SPeter Xu                               ", data=0x%" PRIx32 ")",
36344e4abd11SPeter Xu                               __func__, sid, origin->address, origin->data);
3635c7016bf7SDavid Woodhouse             if (do_fault) {
3636c7016bf7SDavid Woodhouse                 vtd_report_ir_fault(iommu, sid, VTD_FR_IR_REQ_RSVD, 0);
3637c7016bf7SDavid Woodhouse             }
3638c7016bf7SDavid Woodhouse             return -EINVAL;
3639651e4cefSPeter Xu         }
3640651e4cefSPeter Xu     } else {
3641651e4cefSPeter Xu         uint8_t vector = origin->data & 0xff;
3642dea651a9SFeng Wu         uint8_t trigger_mode = (origin->data >> MSI_DATA_TRIGGER_SHIFT) & 0x1;
3643dea651a9SFeng Wu 
36447feb51b7SPeter Xu         trace_vtd_ir_remap_type("IOAPIC");
3645651e4cefSPeter Xu         /* IOAPIC entry vector should be aligned with IRTE vector
3646651e4cefSPeter Xu          * (see vt-d spec 5.1.5.1). */
3647651e4cefSPeter Xu         if (vector != irq.vector) {
36487feb51b7SPeter Xu             trace_vtd_warn_ir_vector(sid, index, vector, irq.vector);
3649651e4cefSPeter Xu         }
3650dea651a9SFeng Wu 
3651dea651a9SFeng Wu         /* The Trigger Mode field must match the Trigger Mode in the IRTE.
3652dea651a9SFeng Wu          * (see vt-d spec 5.1.5.1). */
3653dea651a9SFeng Wu         if (trigger_mode != irq.trigger_mode) {
36547feb51b7SPeter Xu             trace_vtd_warn_ir_trigger(sid, index, trigger_mode,
36557feb51b7SPeter Xu                                       irq.trigger_mode);
3656dea651a9SFeng Wu         }
3657651e4cefSPeter Xu     }
3658651e4cefSPeter Xu 
3659651e4cefSPeter Xu     /*
3660651e4cefSPeter Xu      * We'd better keep the last two bits, assuming that guest OS
3661651e4cefSPeter Xu      * might modify it. Keep it does not hurt after all.
3662651e4cefSPeter Xu      */
3663bc38ee10SMichael S. Tsirkin     irq.msi_addr_last_bits = addr.addr.__not_care;
3664651e4cefSPeter Xu 
366535c24501SSingh, Brijesh     /* Translate X86IOMMUIrq to MSI message */
366635c24501SSingh, Brijesh     x86_iommu_irq_to_msi_message(&irq, translated);
3667651e4cefSPeter Xu 
3668e7a3b91fSPeter Xu out:
36697feb51b7SPeter Xu     trace_vtd_ir_remap_msi(origin->address, origin->data,
3670651e4cefSPeter Xu                            translated->address, translated->data);
3671651e4cefSPeter Xu     return 0;
3672651e4cefSPeter Xu }
3673651e4cefSPeter Xu 
vtd_int_remap(X86IOMMUState * iommu,MSIMessage * src,MSIMessage * dst,uint16_t sid)36748b5ed7dfSPeter Xu static int vtd_int_remap(X86IOMMUState *iommu, MSIMessage *src,
36758b5ed7dfSPeter Xu                          MSIMessage *dst, uint16_t sid)
36768b5ed7dfSPeter Xu {
3677ede9c94aSPeter Xu     return vtd_interrupt_remap_msi(INTEL_IOMMU_DEVICE(iommu),
3678c7016bf7SDavid Woodhouse                                    src, dst, sid, false);
36798b5ed7dfSPeter Xu }
36808b5ed7dfSPeter Xu 
vtd_mem_ir_read(void * opaque,hwaddr addr,uint64_t * data,unsigned size,MemTxAttrs attrs)3681651e4cefSPeter Xu static MemTxResult vtd_mem_ir_read(void *opaque, hwaddr addr,
3682651e4cefSPeter Xu                                    uint64_t *data, unsigned size,
3683651e4cefSPeter Xu                                    MemTxAttrs attrs)
3684651e4cefSPeter Xu {
3685651e4cefSPeter Xu     return MEMTX_OK;
3686651e4cefSPeter Xu }
3687651e4cefSPeter Xu 
vtd_mem_ir_write(void * opaque,hwaddr addr,uint64_t value,unsigned size,MemTxAttrs attrs)3688651e4cefSPeter Xu static MemTxResult vtd_mem_ir_write(void *opaque, hwaddr addr,
3689651e4cefSPeter Xu                                     uint64_t value, unsigned size,
3690651e4cefSPeter Xu                                     MemTxAttrs attrs)
3691651e4cefSPeter Xu {
3692651e4cefSPeter Xu     int ret = 0;
369309cd058aSMichael S. Tsirkin     MSIMessage from = {}, to = {};
3694ede9c94aSPeter Xu     uint16_t sid = X86_IOMMU_SID_INVALID;
3695651e4cefSPeter Xu 
3696651e4cefSPeter Xu     from.address = (uint64_t) addr + VTD_INTERRUPT_ADDR_FIRST;
3697651e4cefSPeter Xu     from.data = (uint32_t) value;
3698651e4cefSPeter Xu 
3699ede9c94aSPeter Xu     if (!attrs.unspecified) {
3700ede9c94aSPeter Xu         /* We have explicit Source ID */
3701ede9c94aSPeter Xu         sid = attrs.requester_id;
3702ede9c94aSPeter Xu     }
3703ede9c94aSPeter Xu 
3704c7016bf7SDavid Woodhouse     ret = vtd_interrupt_remap_msi(opaque, &from, &to, sid, true);
3705651e4cefSPeter Xu     if (ret) {
3706651e4cefSPeter Xu         /* Drop this interrupt */
3707651e4cefSPeter Xu         return MEMTX_ERROR;
3708651e4cefSPeter Xu     }
3709651e4cefSPeter Xu 
3710eaaaf8abSPaolo Bonzini     apic_get_class(NULL)->send_msi(&to);
3711651e4cefSPeter Xu 
3712651e4cefSPeter Xu     return MEMTX_OK;
3713651e4cefSPeter Xu }
3714651e4cefSPeter Xu 
3715651e4cefSPeter Xu static const MemoryRegionOps vtd_mem_ir_ops = {
3716651e4cefSPeter Xu     .read_with_attrs = vtd_mem_ir_read,
3717651e4cefSPeter Xu     .write_with_attrs = vtd_mem_ir_write,
3718651e4cefSPeter Xu     .endianness = DEVICE_LITTLE_ENDIAN,
3719651e4cefSPeter Xu     .impl = {
3720651e4cefSPeter Xu         .min_access_size = 4,
3721651e4cefSPeter Xu         .max_access_size = 4,
3722651e4cefSPeter Xu     },
3723651e4cefSPeter Xu     .valid = {
3724651e4cefSPeter Xu         .min_access_size = 4,
3725651e4cefSPeter Xu         .max_access_size = 4,
3726651e4cefSPeter Xu     },
3727651e4cefSPeter Xu };
37287df953bdSKnut Omang 
vtd_report_ir_illegal_access(VTDAddressSpace * vtd_as,hwaddr addr,bool is_write)37291b2b1237SJason Wang static void vtd_report_ir_illegal_access(VTDAddressSpace *vtd_as,
37301b2b1237SJason Wang                                          hwaddr addr, bool is_write)
37311b2b1237SJason Wang {
37321b2b1237SJason Wang     IntelIOMMUState *s = vtd_as->iommu_state;
37331b2b1237SJason Wang     uint8_t bus_n = pci_bus_num(vtd_as->bus);
37341b2b1237SJason Wang     uint16_t sid = PCI_BUILD_BDF(bus_n, vtd_as->devfn);
37351b2b1237SJason Wang     bool is_fpd_set = false;
37361b2b1237SJason Wang     VTDContextEntry ce;
37371b2b1237SJason Wang 
37381b2b1237SJason Wang     assert(vtd_as->pasid != PCI_NO_PASID);
37391b2b1237SJason Wang 
37401b2b1237SJason Wang     /* Try out best to fetch FPD, we can't do anything more */
37411b2b1237SJason Wang     if (vtd_dev_to_context_entry(s, bus_n, vtd_as->devfn, &ce) == 0) {
37421b2b1237SJason Wang         is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;
37431b2b1237SJason Wang         if (!is_fpd_set && s->root_scalable) {
37441b2b1237SJason Wang             vtd_ce_get_pasid_fpd(s, &ce, &is_fpd_set, vtd_as->pasid);
37451b2b1237SJason Wang         }
37461b2b1237SJason Wang     }
37471b2b1237SJason Wang 
37481b2b1237SJason Wang     vtd_report_fault(s, VTD_FR_SM_INTERRUPT_ADDR,
37491b2b1237SJason Wang                      is_fpd_set, sid, addr, is_write,
37501b2b1237SJason Wang                      true, vtd_as->pasid);
37511b2b1237SJason Wang }
37521b2b1237SJason Wang 
vtd_mem_ir_fault_read(void * opaque,hwaddr addr,uint64_t * data,unsigned size,MemTxAttrs attrs)37531b2b1237SJason Wang static MemTxResult vtd_mem_ir_fault_read(void *opaque, hwaddr addr,
37541b2b1237SJason Wang                                          uint64_t *data, unsigned size,
37551b2b1237SJason Wang                                          MemTxAttrs attrs)
37561b2b1237SJason Wang {
37571b2b1237SJason Wang     vtd_report_ir_illegal_access(opaque, addr, false);
37581b2b1237SJason Wang 
37591b2b1237SJason Wang     return MEMTX_ERROR;
37601b2b1237SJason Wang }
37611b2b1237SJason Wang 
vtd_mem_ir_fault_write(void * opaque,hwaddr addr,uint64_t value,unsigned size,MemTxAttrs attrs)37621b2b1237SJason Wang static MemTxResult vtd_mem_ir_fault_write(void *opaque, hwaddr addr,
37631b2b1237SJason Wang                                           uint64_t value, unsigned size,
37641b2b1237SJason Wang                                           MemTxAttrs attrs)
37651b2b1237SJason Wang {
37661b2b1237SJason Wang     vtd_report_ir_illegal_access(opaque, addr, true);
37671b2b1237SJason Wang 
37681b2b1237SJason Wang     return MEMTX_ERROR;
37691b2b1237SJason Wang }
37701b2b1237SJason Wang 
37711b2b1237SJason Wang static const MemoryRegionOps vtd_mem_ir_fault_ops = {
37721b2b1237SJason Wang     .read_with_attrs = vtd_mem_ir_fault_read,
37731b2b1237SJason Wang     .write_with_attrs = vtd_mem_ir_fault_write,
37741b2b1237SJason Wang     .endianness = DEVICE_LITTLE_ENDIAN,
37751b2b1237SJason Wang     .impl = {
37761b2b1237SJason Wang         .min_access_size = 1,
37771b2b1237SJason Wang         .max_access_size = 8,
37781b2b1237SJason Wang     },
37791b2b1237SJason Wang     .valid = {
37801b2b1237SJason Wang         .min_access_size = 1,
37811b2b1237SJason Wang         .max_access_size = 8,
37821b2b1237SJason Wang     },
37831b2b1237SJason Wang };
37841b2b1237SJason Wang 
vtd_find_add_as(IntelIOMMUState * s,PCIBus * bus,int devfn,unsigned int pasid)37851b2b1237SJason Wang VTDAddressSpace *vtd_find_add_as(IntelIOMMUState *s, PCIBus *bus,
37861b2b1237SJason Wang                                  int devfn, unsigned int pasid)
37877df953bdSKnut Omang {
3788da8d439cSJason Wang     /*
3789da8d439cSJason Wang      * We can't simply use sid here since the bus number might not be
3790da8d439cSJason Wang      * initialized by the guest.
3791da8d439cSJason Wang      */
3792da8d439cSJason Wang     struct vtd_as_key key = {
3793da8d439cSJason Wang         .bus = bus,
3794da8d439cSJason Wang         .devfn = devfn,
37951b2b1237SJason Wang         .pasid = pasid,
3796da8d439cSJason Wang     };
37977df953bdSKnut Omang     VTDAddressSpace *vtd_dev_as;
3798e0a3c8ccSJason Wang     char name[128];
37997df953bdSKnut Omang 
3800da8d439cSJason Wang     vtd_dev_as = g_hash_table_lookup(s->vtd_address_spaces, &key);
38017df953bdSKnut Omang     if (!vtd_dev_as) {
3802da8d439cSJason Wang         struct vtd_as_key *new_key = g_malloc(sizeof(*new_key));
3803da8d439cSJason Wang 
3804da8d439cSJason Wang         new_key->bus = bus;
3805da8d439cSJason Wang         new_key->devfn = devfn;
38061b2b1237SJason Wang         new_key->pasid = pasid;
3807da8d439cSJason Wang 
38081b2b1237SJason Wang         if (pasid == PCI_NO_PASID) {
38094b519ef1SPeter Xu             snprintf(name, sizeof(name), "vtd-%02x.%x", PCI_SLOT(devfn),
38104b519ef1SPeter Xu                      PCI_FUNC(devfn));
38111b2b1237SJason Wang         } else {
38121b2b1237SJason Wang             snprintf(name, sizeof(name), "vtd-%02x.%x-pasid-%x", PCI_SLOT(devfn),
38131b2b1237SJason Wang                      PCI_FUNC(devfn), pasid);
38141b2b1237SJason Wang         }
38151b2b1237SJason Wang 
3816da8d439cSJason Wang         vtd_dev_as = g_new0(VTDAddressSpace, 1);
38177df953bdSKnut Omang 
38187df953bdSKnut Omang         vtd_dev_as->bus = bus;
38197df953bdSKnut Omang         vtd_dev_as->devfn = (uint8_t)devfn;
38201b2b1237SJason Wang         vtd_dev_as->pasid = pasid;
38217df953bdSKnut Omang         vtd_dev_as->iommu_state = s;
38227df953bdSKnut Omang         vtd_dev_as->context_cache_entry.context_cache_gen = 0;
382363b88968SPeter Xu         vtd_dev_as->iova_tree = iova_tree_new();
3824558e0024SPeter Xu 
38254b519ef1SPeter Xu         memory_region_init(&vtd_dev_as->root, OBJECT(s), name, UINT64_MAX);
38264b519ef1SPeter Xu         address_space_init(&vtd_dev_as->as, &vtd_dev_as->root, "vtd-root");
38274b519ef1SPeter Xu 
3828558e0024SPeter Xu         /*
38294b519ef1SPeter Xu          * Build the DMAR-disabled container with aliases to the
38304b519ef1SPeter Xu          * shared MRs.  Note that aliasing to a shared memory region
38314b519ef1SPeter Xu          * could help the memory API to detect same FlatViews so we
38324b519ef1SPeter Xu          * can have devices to share the same FlatView when DMAR is
38334b519ef1SPeter Xu          * disabled (either by not providing "intel_iommu=on" or with
38344b519ef1SPeter Xu          * "iommu=pt").  It will greatly reduce the total number of
38354b519ef1SPeter Xu          * FlatViews of the system hence VM runs faster.
3836558e0024SPeter Xu          */
38374b519ef1SPeter Xu         memory_region_init_alias(&vtd_dev_as->nodmar, OBJECT(s),
38384b519ef1SPeter Xu                                  "vtd-nodmar", &s->mr_nodmar, 0,
38394b519ef1SPeter Xu                                  memory_region_size(&s->mr_nodmar));
38404b519ef1SPeter Xu 
38414b519ef1SPeter Xu         /*
38424b519ef1SPeter Xu          * Build the per-device DMAR-enabled container.
38434b519ef1SPeter Xu          *
38444b519ef1SPeter Xu          * TODO: currently we have per-device IOMMU memory region only
38454b519ef1SPeter Xu          * because we have per-device IOMMU notifiers for devices.  If
38464b519ef1SPeter Xu          * one day we can abstract the IOMMU notifiers out of the
38474b519ef1SPeter Xu          * memory regions then we can also share the same memory
38484b519ef1SPeter Xu          * region here just like what we've done above with the nodmar
38494b519ef1SPeter Xu          * region.
38504b519ef1SPeter Xu          */
38514b519ef1SPeter Xu         strcat(name, "-dmar");
38521221a474SAlexey Kardashevskiy         memory_region_init_iommu(&vtd_dev_as->iommu, sizeof(vtd_dev_as->iommu),
38531221a474SAlexey Kardashevskiy                                  TYPE_INTEL_IOMMU_MEMORY_REGION, OBJECT(s),
38544b519ef1SPeter Xu                                  name, UINT64_MAX);
38554b519ef1SPeter Xu         memory_region_init_alias(&vtd_dev_as->iommu_ir, OBJECT(s), "vtd-ir",
38564b519ef1SPeter Xu                                  &s->mr_ir, 0, memory_region_size(&s->mr_ir));
38574b519ef1SPeter Xu         memory_region_add_subregion_overlap(MEMORY_REGION(&vtd_dev_as->iommu),
3858558e0024SPeter Xu                                             VTD_INTERRUPT_ADDR_FIRST,
38594b519ef1SPeter Xu                                             &vtd_dev_as->iommu_ir, 1);
38604b519ef1SPeter Xu 
38614b519ef1SPeter Xu         /*
38621b2b1237SJason Wang          * This region is used for catching fault to access interrupt
38631b2b1237SJason Wang          * range via passthrough + PASID. See also
38641b2b1237SJason Wang          * vtd_switch_address_space(). We can't use alias since we
38651b2b1237SJason Wang          * need to know the sid which is valid for MSI who uses
38661b2b1237SJason Wang          * bus_master_as (see msi_send_message()).
38671b2b1237SJason Wang          */
38681b2b1237SJason Wang         memory_region_init_io(&vtd_dev_as->iommu_ir_fault, OBJECT(s),
38691b2b1237SJason Wang                               &vtd_mem_ir_fault_ops, vtd_dev_as, "vtd-no-ir",
38701b2b1237SJason Wang                               VTD_INTERRUPT_ADDR_SIZE);
38711b2b1237SJason Wang         /*
38721b2b1237SJason Wang          * Hook to root since when PT is enabled vtd_dev_as->iommu
38731b2b1237SJason Wang          * will be disabled.
38741b2b1237SJason Wang          */
38751b2b1237SJason Wang         memory_region_add_subregion_overlap(MEMORY_REGION(&vtd_dev_as->root),
38761b2b1237SJason Wang                                             VTD_INTERRUPT_ADDR_FIRST,
38771b2b1237SJason Wang                                             &vtd_dev_as->iommu_ir_fault, 2);
38781b2b1237SJason Wang 
38791b2b1237SJason Wang         /*
38804b519ef1SPeter Xu          * Hook both the containers under the root container, we
38814b519ef1SPeter Xu          * switch between DMAR & noDMAR by enable/disable
38824b519ef1SPeter Xu          * corresponding sub-containers
38834b519ef1SPeter Xu          */
3884558e0024SPeter Xu         memory_region_add_subregion_overlap(&vtd_dev_as->root, 0,
38853df9d748SAlexey Kardashevskiy                                             MEMORY_REGION(&vtd_dev_as->iommu),
38864b519ef1SPeter Xu                                             0);
38874b519ef1SPeter Xu         memory_region_add_subregion_overlap(&vtd_dev_as->root, 0,
38884b519ef1SPeter Xu                                             &vtd_dev_as->nodmar, 0);
38894b519ef1SPeter Xu 
3890558e0024SPeter Xu         vtd_switch_address_space(vtd_dev_as);
3891da8d439cSJason Wang 
3892da8d439cSJason Wang         g_hash_table_insert(s->vtd_address_spaces, new_key, vtd_dev_as);
38937df953bdSKnut Omang     }
38947df953bdSKnut Omang     return vtd_dev_as;
38957df953bdSKnut Omang }
38967df953bdSKnut Omang 
vtd_check_hiod(IntelIOMMUState * s,HostIOMMUDevice * hiod,Error ** errp)389777f6efc0SZhenzhong Duan static bool vtd_check_hiod(IntelIOMMUState *s, HostIOMMUDevice *hiod,
389877f6efc0SZhenzhong Duan                            Error **errp)
389977f6efc0SZhenzhong Duan {
390077f6efc0SZhenzhong Duan     HostIOMMUDeviceClass *hiodc = HOST_IOMMU_DEVICE_GET_CLASS(hiod);
390177f6efc0SZhenzhong Duan     int ret;
390277f6efc0SZhenzhong Duan 
390377f6efc0SZhenzhong Duan     if (!hiodc->get_cap) {
390477f6efc0SZhenzhong Duan         error_setg(errp, ".get_cap() not implemented");
390577f6efc0SZhenzhong Duan         return false;
390677f6efc0SZhenzhong Duan     }
390777f6efc0SZhenzhong Duan 
390877f6efc0SZhenzhong Duan     /* Common checks */
390977f6efc0SZhenzhong Duan     ret = hiodc->get_cap(hiod, HOST_IOMMU_DEVICE_CAP_AW_BITS, errp);
391077f6efc0SZhenzhong Duan     if (ret < 0) {
391177f6efc0SZhenzhong Duan         return false;
391277f6efc0SZhenzhong Duan     }
391377f6efc0SZhenzhong Duan     if (s->aw_bits > ret) {
391477f6efc0SZhenzhong Duan         error_setg(errp, "aw-bits %d > host aw-bits %d", s->aw_bits, ret);
391577f6efc0SZhenzhong Duan         return false;
391677f6efc0SZhenzhong Duan     }
391777f6efc0SZhenzhong Duan 
391877f6efc0SZhenzhong Duan     return true;
391977f6efc0SZhenzhong Duan }
392077f6efc0SZhenzhong Duan 
vtd_dev_set_iommu_device(PCIBus * bus,void * opaque,int devfn,HostIOMMUDevice * hiod,Error ** errp)3921a20910caSYi Liu static bool vtd_dev_set_iommu_device(PCIBus *bus, void *opaque, int devfn,
3922a20910caSYi Liu                                      HostIOMMUDevice *hiod, Error **errp)
3923a20910caSYi Liu {
3924a20910caSYi Liu     IntelIOMMUState *s = opaque;
3925a20910caSYi Liu     struct vtd_as_key key = {
3926a20910caSYi Liu         .bus = bus,
3927a20910caSYi Liu         .devfn = devfn,
3928a20910caSYi Liu     };
3929a20910caSYi Liu     struct vtd_as_key *new_key;
3930a20910caSYi Liu 
3931a20910caSYi Liu     assert(hiod);
3932a20910caSYi Liu 
3933a20910caSYi Liu     vtd_iommu_lock(s);
3934a20910caSYi Liu 
3935a20910caSYi Liu     if (g_hash_table_lookup(s->vtd_host_iommu_dev, &key)) {
3936a20910caSYi Liu         error_setg(errp, "Host IOMMU device already exist");
3937a20910caSYi Liu         vtd_iommu_unlock(s);
3938a20910caSYi Liu         return false;
3939a20910caSYi Liu     }
3940a20910caSYi Liu 
394177f6efc0SZhenzhong Duan     if (!vtd_check_hiod(s, hiod, errp)) {
394277f6efc0SZhenzhong Duan         vtd_iommu_unlock(s);
394377f6efc0SZhenzhong Duan         return false;
394477f6efc0SZhenzhong Duan     }
394577f6efc0SZhenzhong Duan 
3946a20910caSYi Liu     new_key = g_malloc(sizeof(*new_key));
3947a20910caSYi Liu     new_key->bus = bus;
3948a20910caSYi Liu     new_key->devfn = devfn;
3949a20910caSYi Liu 
3950a20910caSYi Liu     object_ref(hiod);
3951a20910caSYi Liu     g_hash_table_insert(s->vtd_host_iommu_dev, new_key, hiod);
3952a20910caSYi Liu 
3953a20910caSYi Liu     vtd_iommu_unlock(s);
3954a20910caSYi Liu 
3955a20910caSYi Liu     return true;
3956a20910caSYi Liu }
3957a20910caSYi Liu 
vtd_dev_unset_iommu_device(PCIBus * bus,void * opaque,int devfn)3958a20910caSYi Liu static void vtd_dev_unset_iommu_device(PCIBus *bus, void *opaque, int devfn)
3959a20910caSYi Liu {
3960a20910caSYi Liu     IntelIOMMUState *s = opaque;
3961a20910caSYi Liu     struct vtd_as_key key = {
3962a20910caSYi Liu         .bus = bus,
3963a20910caSYi Liu         .devfn = devfn,
3964a20910caSYi Liu     };
3965a20910caSYi Liu 
3966a20910caSYi Liu     vtd_iommu_lock(s);
3967a20910caSYi Liu 
3968a20910caSYi Liu     if (!g_hash_table_lookup(s->vtd_host_iommu_dev, &key)) {
3969a20910caSYi Liu         vtd_iommu_unlock(s);
3970a20910caSYi Liu         return;
3971a20910caSYi Liu     }
3972a20910caSYi Liu 
3973a20910caSYi Liu     g_hash_table_remove(s->vtd_host_iommu_dev, &key);
3974a20910caSYi Liu 
3975a20910caSYi Liu     vtd_iommu_unlock(s);
3976a20910caSYi Liu }
3977a20910caSYi Liu 
3978dd4d607eSPeter Xu /* Unmap the whole range in the notifier's scope. */
vtd_address_space_unmap(VTDAddressSpace * as,IOMMUNotifier * n)3979dd4d607eSPeter Xu static void vtd_address_space_unmap(VTDAddressSpace *as, IOMMUNotifier *n)
3980dd4d607eSPeter Xu {
3981a082739eSPeter Xu     hwaddr total, remain;
3982dd4d607eSPeter Xu     hwaddr start = n->start;
3983dd4d607eSPeter Xu     hwaddr end = n->end;
398437f51384SPrasad Singamsetty     IntelIOMMUState *s = as->iommu_state;
398563b88968SPeter Xu     DMAMap map;
3986dd4d607eSPeter Xu 
3987dd4d607eSPeter Xu     /*
3988dd4d607eSPeter Xu      * Note: all the codes in this function has a assumption that IOVA
3989dd4d607eSPeter Xu      * bits are no more than VTD_MGAW bits (which is restricted by
3990dd4d607eSPeter Xu      * VT-d spec), otherwise we need to consider overflow of 64 bits.
3991dd4d607eSPeter Xu      */
3992dd4d607eSPeter Xu 
3993d6d10793SYan Zhao     if (end > VTD_ADDRESS_SIZE(s->aw_bits) - 1) {
3994dd4d607eSPeter Xu         /*
3995dd4d607eSPeter Xu          * Don't need to unmap regions that is bigger than the whole
3996dd4d607eSPeter Xu          * VT-d supported address space size
3997dd4d607eSPeter Xu          */
3998d6d10793SYan Zhao         end = VTD_ADDRESS_SIZE(s->aw_bits) - 1;
3999dd4d607eSPeter Xu     }
4000dd4d607eSPeter Xu 
4001dd4d607eSPeter Xu     assert(start <= end);
4002a082739eSPeter Xu     total = remain = end - start + 1;
4003dd4d607eSPeter Xu 
40049a4bb839SPeter Xu     while (remain >= VTD_PAGE_SIZE) {
40055039caf3SEugenio Pérez         IOMMUTLBEvent event;
4006f14fb6c2SEric Auger         uint64_t mask = dma_aligned_pow2_mask(start, end, s->aw_bits);
4007f14fb6c2SEric Auger         uint64_t size = mask + 1;
4008dd4d607eSPeter Xu 
4009f14fb6c2SEric Auger         assert(size);
40109a4bb839SPeter Xu 
40115039caf3SEugenio Pérez         event.type = IOMMU_NOTIFIER_UNMAP;
40125039caf3SEugenio Pérez         event.entry.iova = start;
4013f14fb6c2SEric Auger         event.entry.addr_mask = mask;
40145039caf3SEugenio Pérez         event.entry.target_as = &address_space_memory;
40155039caf3SEugenio Pérez         event.entry.perm = IOMMU_NONE;
4016dd4d607eSPeter Xu         /* This field is meaningless for unmap */
40175039caf3SEugenio Pérez         event.entry.translated_addr = 0;
40189a4bb839SPeter Xu 
40195039caf3SEugenio Pérez         memory_region_notify_iommu_one(n, &event);
40209a4bb839SPeter Xu 
4021f14fb6c2SEric Auger         start += size;
4022f14fb6c2SEric Auger         remain -= size;
40239a4bb839SPeter Xu     }
40249a4bb839SPeter Xu 
40259a4bb839SPeter Xu     assert(!remain);
4026dd4d607eSPeter Xu 
4027dd4d607eSPeter Xu     trace_vtd_as_unmap_whole(pci_bus_num(as->bus),
4028dd4d607eSPeter Xu                              VTD_PCI_SLOT(as->devfn),
4029dd4d607eSPeter Xu                              VTD_PCI_FUNC(as->devfn),
4030a082739eSPeter Xu                              n->start, total);
4031dd4d607eSPeter Xu 
40329a4bb839SPeter Xu     map.iova = n->start;
4033a082739eSPeter Xu     map.size = total - 1; /* Inclusive */
403469292a8eSEugenio Pérez     iova_tree_remove(as->iova_tree, map);
4035dd4d607eSPeter Xu }
4036dd4d607eSPeter Xu 
vtd_address_space_unmap_all(IntelIOMMUState * s)4037dd4d607eSPeter Xu static void vtd_address_space_unmap_all(IntelIOMMUState *s)
4038dd4d607eSPeter Xu {
4039dd4d607eSPeter Xu     VTDAddressSpace *vtd_as;
4040dd4d607eSPeter Xu     IOMMUNotifier *n;
4041dd4d607eSPeter Xu 
4042b4a4ba0dSPeter Xu     QLIST_FOREACH(vtd_as, &s->vtd_as_with_notifiers, next) {
4043dd4d607eSPeter Xu         IOMMU_NOTIFIER_FOREACH(n, &vtd_as->iommu) {
4044dd4d607eSPeter Xu             vtd_address_space_unmap(vtd_as, n);
4045dd4d607eSPeter Xu         }
4046dd4d607eSPeter Xu     }
4047dd4d607eSPeter Xu }
4048dd4d607eSPeter Xu 
vtd_address_space_refresh_all(IntelIOMMUState * s)40492cc9ddccSPeter Xu static void vtd_address_space_refresh_all(IntelIOMMUState *s)
40502cc9ddccSPeter Xu {
40512cc9ddccSPeter Xu     vtd_address_space_unmap_all(s);
40522cc9ddccSPeter Xu     vtd_switch_address_space_all(s);
40532cc9ddccSPeter Xu }
40542cc9ddccSPeter Xu 
vtd_replay_hook(const IOMMUTLBEvent * event,void * private)4055fc9ad5cfSPhilippe Mathieu-Daudé static int vtd_replay_hook(const IOMMUTLBEvent *event, void *private)
4056f06a696dSPeter Xu {
40575039caf3SEugenio Pérez     memory_region_notify_iommu_one(private, event);
4058f06a696dSPeter Xu     return 0;
4059f06a696dSPeter Xu }
4060f06a696dSPeter Xu 
vtd_iommu_replay(IOMMUMemoryRegion * iommu_mr,IOMMUNotifier * n)40613df9d748SAlexey Kardashevskiy static void vtd_iommu_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n)
4062f06a696dSPeter Xu {
40633df9d748SAlexey Kardashevskiy     VTDAddressSpace *vtd_as = container_of(iommu_mr, VTDAddressSpace, iommu);
4064f06a696dSPeter Xu     IntelIOMMUState *s = vtd_as->iommu_state;
4065f06a696dSPeter Xu     uint8_t bus_n = pci_bus_num(vtd_as->bus);
4066f06a696dSPeter Xu     VTDContextEntry ce;
4067e80c1e4cSZhenzhong Duan     DMAMap map = { .iova = 0, .size = HWADDR_MAX };
4068f06a696dSPeter Xu 
4069e80c1e4cSZhenzhong Duan     /* replay is protected by BQL, page walk will re-setup it safely */
4070e80c1e4cSZhenzhong Duan     iova_tree_remove(vtd_as->iova_tree, map);
4071dd4d607eSPeter Xu 
4072dd4d607eSPeter Xu     if (vtd_dev_to_context_entry(s, bus_n, vtd_as->devfn, &ce) == 0) {
4073fb43cf73SLiu, Yi L         trace_vtd_replay_ce_valid(s->root_scalable ? "scalable mode" :
4074fb43cf73SLiu, Yi L                                   "legacy mode",
4075fb43cf73SLiu, Yi L                                   bus_n, PCI_SLOT(vtd_as->devfn),
4076f06a696dSPeter Xu                                   PCI_FUNC(vtd_as->devfn),
40771b2b1237SJason Wang                                   vtd_get_domain_id(s, &ce, vtd_as->pasid),
4078f06a696dSPeter Xu                                   ce.hi, ce.lo);
4079ce735ff0SZhenzhong Duan         if (n->notifier_flags & IOMMU_NOTIFIER_MAP) {
40804f8a62a9SPeter Xu             /* This is required only for MAP typed notifiers */
4081fe215b0cSPeter Xu             vtd_page_walk_info info = {
4082fe215b0cSPeter Xu                 .hook_fn = vtd_replay_hook,
4083fe215b0cSPeter Xu                 .private = (void *)n,
4084fe215b0cSPeter Xu                 .notify_unmap = false,
4085fe215b0cSPeter Xu                 .aw = s->aw_bits,
40862f764fa8SPeter Xu                 .as = vtd_as,
40871b2b1237SJason Wang                 .domain_id = vtd_get_domain_id(s, &ce, vtd_as->pasid),
4088fe215b0cSPeter Xu             };
4089fe215b0cSPeter Xu 
4090b1ab8f9cSPeter Maydell             vtd_page_walk(s, &ce, 0, ~0ULL, &info, vtd_as->pasid);
40914f8a62a9SPeter Xu         }
4092f06a696dSPeter Xu     } else {
4093f06a696dSPeter Xu         trace_vtd_replay_ce_invalid(bus_n, PCI_SLOT(vtd_as->devfn),
4094f06a696dSPeter Xu                                     PCI_FUNC(vtd_as->devfn));
4095f06a696dSPeter Xu     }
4096f06a696dSPeter Xu 
4097f06a696dSPeter Xu     return;
4098f06a696dSPeter Xu }
4099f06a696dSPeter Xu 
vtd_cap_init(IntelIOMMUState * s)4100d5fd978dSZhenzhong Duan static void vtd_cap_init(IntelIOMMUState *s)
41011da12ec4SLe Tan {
4102d54bd7f8SPeter Xu     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
4103d54bd7f8SPeter Xu 
410492e5d85eSPrasad Singamsetty     s->cap = VTD_CAP_FRO | VTD_CAP_NFR | VTD_CAP_ND |
410592e5d85eSPrasad Singamsetty              VTD_CAP_MAMV | VTD_CAP_PSI | VTD_CAP_SLLPS |
41068646d9c7SDavid Woodhouse              VTD_CAP_MGAW(s->aw_bits);
4107ccc23bb0SPeter Xu     if (s->dma_drain) {
4108ccc23bb0SPeter Xu         s->cap |= VTD_CAP_DRAIN;
4109ccc23bb0SPeter Xu     }
41108646d9c7SDavid Woodhouse     if (s->dma_translation) {
41118646d9c7SDavid Woodhouse             if (s->aw_bits >= VTD_HOST_AW_39BIT) {
41128646d9c7SDavid Woodhouse                     s->cap |= VTD_CAP_SAGAW_39bit;
41138646d9c7SDavid Woodhouse             }
41148646d9c7SDavid Woodhouse             if (s->aw_bits >= VTD_HOST_AW_48BIT) {
411537f51384SPrasad Singamsetty                     s->cap |= VTD_CAP_SAGAW_48bit;
411637f51384SPrasad Singamsetty             }
41178646d9c7SDavid Woodhouse     }
4118ed7b8fbcSLe Tan     s->ecap = VTD_ECAP_QI | VTD_ECAP_IRO;
41191da12ec4SLe Tan 
4120a924b3d8SPeter Xu     if (x86_iommu_ir_supported(x86_iommu)) {
4121e6b6af05SRadim Krčmář         s->ecap |= VTD_ECAP_IR | VTD_ECAP_MHMV;
4122e6b6af05SRadim Krčmář         if (s->intr_eim == ON_OFF_AUTO_ON) {
4123e6b6af05SRadim Krčmář             s->ecap |= VTD_ECAP_EIM;
4124e6b6af05SRadim Krčmář         }
4125e6b6af05SRadim Krčmář         assert(s->intr_eim != ON_OFF_AUTO_AUTO);
4126d54bd7f8SPeter Xu     }
4127d54bd7f8SPeter Xu 
4128554f5e16SJason Wang     if (x86_iommu->dt_supported) {
4129554f5e16SJason Wang         s->ecap |= VTD_ECAP_DT;
4130554f5e16SJason Wang     }
4131554f5e16SJason Wang 
4132dbaabb25SPeter Xu     if (x86_iommu->pt_supported) {
4133dbaabb25SPeter Xu         s->ecap |= VTD_ECAP_PT;
4134dbaabb25SPeter Xu     }
4135dbaabb25SPeter Xu 
41363b40f0e5SAviv Ben-David     if (s->caching_mode) {
41373b40f0e5SAviv Ben-David         s->cap |= VTD_CAP_CM;
41383b40f0e5SAviv Ben-David     }
41393b40f0e5SAviv Ben-David 
41404a4f219eSYi Sun     /* TODO: read cap/ecap from host to decide which cap to be exposed. */
41414a4f219eSYi Sun     if (s->scalable_mode) {
41424a4f219eSYi Sun         s->ecap |= VTD_ECAP_SMTS | VTD_ECAP_SRS | VTD_ECAP_SLTS;
41434a4f219eSYi Sun     }
41444a4f219eSYi Sun 
4145b8ffd7d6SJason Wang     if (s->snoop_control) {
4146b8ffd7d6SJason Wang         s->ecap |= VTD_ECAP_SC;
4147b8ffd7d6SJason Wang     }
4148b8ffd7d6SJason Wang 
41491b2b1237SJason Wang     if (s->pasid) {
41501b2b1237SJason Wang         s->ecap |= VTD_ECAP_PASID;
41511b2b1237SJason Wang     }
4152d5fd978dSZhenzhong Duan }
4153d5fd978dSZhenzhong Duan 
4154d5fd978dSZhenzhong Duan /*
4155d5fd978dSZhenzhong Duan  * Do the initialization. It will also be called when reset, so pay
4156d5fd978dSZhenzhong Duan  * attention when adding new initialization stuff.
4157d5fd978dSZhenzhong Duan  */
vtd_init(IntelIOMMUState * s)4158d5fd978dSZhenzhong Duan static void vtd_init(IntelIOMMUState *s)
4159d5fd978dSZhenzhong Duan {
4160d5fd978dSZhenzhong Duan     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
4161d5fd978dSZhenzhong Duan 
4162d5fd978dSZhenzhong Duan     memset(s->csr, 0, DMAR_REG_SIZE);
4163d5fd978dSZhenzhong Duan     memset(s->wmask, 0, DMAR_REG_SIZE);
4164d5fd978dSZhenzhong Duan     memset(s->w1cmask, 0, DMAR_REG_SIZE);
4165d5fd978dSZhenzhong Duan     memset(s->womask, 0, DMAR_REG_SIZE);
4166d5fd978dSZhenzhong Duan 
4167d5fd978dSZhenzhong Duan     s->root = 0;
4168d5fd978dSZhenzhong Duan     s->root_scalable = false;
4169d5fd978dSZhenzhong Duan     s->dmar_enabled = false;
4170d5fd978dSZhenzhong Duan     s->intr_enabled = false;
4171d5fd978dSZhenzhong Duan     s->iq_head = 0;
4172d5fd978dSZhenzhong Duan     s->iq_tail = 0;
4173d5fd978dSZhenzhong Duan     s->iq = 0;
4174d5fd978dSZhenzhong Duan     s->iq_size = 0;
4175d5fd978dSZhenzhong Duan     s->qi_enabled = false;
4176d5fd978dSZhenzhong Duan     s->iq_last_desc_type = VTD_INV_DESC_NONE;
4177d5fd978dSZhenzhong Duan     s->iq_dw = false;
4178d5fd978dSZhenzhong Duan     s->next_frcd_reg = 0;
4179d5fd978dSZhenzhong Duan 
4180d5fd978dSZhenzhong Duan     vtd_cap_init(s);
4181d5fd978dSZhenzhong Duan 
4182d5fd978dSZhenzhong Duan     /*
4183d5fd978dSZhenzhong Duan      * Rsvd field masks for spte
4184d5fd978dSZhenzhong Duan      */
4185d5fd978dSZhenzhong Duan     vtd_spte_rsvd[0] = ~0ULL;
4186d5fd978dSZhenzhong Duan     vtd_spte_rsvd[1] = VTD_SPTE_PAGE_L1_RSVD_MASK(s->aw_bits,
41876ce12bd2SZhenzhong Duan                                         x86_iommu->dt_supported && s->stale_tm);
4188d5fd978dSZhenzhong Duan     vtd_spte_rsvd[2] = VTD_SPTE_PAGE_L2_RSVD_MASK(s->aw_bits);
4189d5fd978dSZhenzhong Duan     vtd_spte_rsvd[3] = VTD_SPTE_PAGE_L3_RSVD_MASK(s->aw_bits);
4190d5fd978dSZhenzhong Duan     vtd_spte_rsvd[4] = VTD_SPTE_PAGE_L4_RSVD_MASK(s->aw_bits);
4191d5fd978dSZhenzhong Duan 
4192d5fd978dSZhenzhong Duan     vtd_spte_rsvd_large[2] = VTD_SPTE_LPAGE_L2_RSVD_MASK(s->aw_bits,
41936ce12bd2SZhenzhong Duan                                         x86_iommu->dt_supported && s->stale_tm);
4194d5fd978dSZhenzhong Duan     vtd_spte_rsvd_large[3] = VTD_SPTE_LPAGE_L3_RSVD_MASK(s->aw_bits,
41956ce12bd2SZhenzhong Duan                                         x86_iommu->dt_supported && s->stale_tm);
4196d5fd978dSZhenzhong Duan 
4197d5fd978dSZhenzhong Duan     if (s->scalable_mode || s->snoop_control) {
4198d5fd978dSZhenzhong Duan         vtd_spte_rsvd[1] &= ~VTD_SPTE_SNP;
4199d5fd978dSZhenzhong Duan         vtd_spte_rsvd_large[2] &= ~VTD_SPTE_SNP;
4200d5fd978dSZhenzhong Duan         vtd_spte_rsvd_large[3] &= ~VTD_SPTE_SNP;
4201d5fd978dSZhenzhong Duan     }
42021b2b1237SJason Wang 
420306aba4caSPeter Xu     vtd_reset_caches(s);
4204d92fa2dcSLe Tan 
42051da12ec4SLe Tan     /* Define registers with default values and bit semantics */
42061da12ec4SLe Tan     vtd_define_long(s, DMAR_VER_REG, 0x10UL, 0, 0);
42071da12ec4SLe Tan     vtd_define_quad(s, DMAR_CAP_REG, s->cap, 0, 0);
42081da12ec4SLe Tan     vtd_define_quad(s, DMAR_ECAP_REG, s->ecap, 0, 0);
42091da12ec4SLe Tan     vtd_define_long(s, DMAR_GCMD_REG, 0, 0xff800000UL, 0);
42101da12ec4SLe Tan     vtd_define_long_wo(s, DMAR_GCMD_REG, 0xff800000UL);
42111da12ec4SLe Tan     vtd_define_long(s, DMAR_GSTS_REG, 0, 0, 0);
4212fb43cf73SLiu, Yi L     vtd_define_quad(s, DMAR_RTADDR_REG, 0, 0xfffffffffffffc00ULL, 0);
42131da12ec4SLe Tan     vtd_define_quad(s, DMAR_CCMD_REG, 0, 0xe0000003ffffffffULL, 0);
42141da12ec4SLe Tan     vtd_define_quad_wo(s, DMAR_CCMD_REG, 0x3ffff0000ULL);
42151da12ec4SLe Tan 
42161da12ec4SLe Tan     /* Advanced Fault Logging not supported */
42171da12ec4SLe Tan     vtd_define_long(s, DMAR_FSTS_REG, 0, 0, 0x11UL);
42181da12ec4SLe Tan     vtd_define_long(s, DMAR_FECTL_REG, 0x80000000UL, 0x80000000UL, 0);
42191da12ec4SLe Tan     vtd_define_long(s, DMAR_FEDATA_REG, 0, 0x0000ffffUL, 0);
42201da12ec4SLe Tan     vtd_define_long(s, DMAR_FEADDR_REG, 0, 0xfffffffcUL, 0);
42211da12ec4SLe Tan 
42221da12ec4SLe Tan     /* Treated as RsvdZ when EIM in ECAP_REG is not supported
42231da12ec4SLe Tan      * vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0xffffffffUL, 0);
42241da12ec4SLe Tan      */
42251da12ec4SLe Tan     vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0, 0);
42261da12ec4SLe Tan 
42271da12ec4SLe Tan     /* Treated as RO for implementations that PLMR and PHMR fields reported
42281da12ec4SLe Tan      * as Clear in the CAP_REG.
42291da12ec4SLe Tan      * vtd_define_long(s, DMAR_PMEN_REG, 0, 0x80000000UL, 0);
42301da12ec4SLe Tan      */
42311da12ec4SLe Tan     vtd_define_long(s, DMAR_PMEN_REG, 0, 0, 0);
42321da12ec4SLe Tan 
4233ed7b8fbcSLe Tan     vtd_define_quad(s, DMAR_IQH_REG, 0, 0, 0);
4234ed7b8fbcSLe Tan     vtd_define_quad(s, DMAR_IQT_REG, 0, 0x7fff0ULL, 0);
4235c0c1d351SLiu, Yi L     vtd_define_quad(s, DMAR_IQA_REG, 0, 0xfffffffffffff807ULL, 0);
4236ed7b8fbcSLe Tan     vtd_define_long(s, DMAR_ICS_REG, 0, 0, 0x1UL);
4237ed7b8fbcSLe Tan     vtd_define_long(s, DMAR_IECTL_REG, 0x80000000UL, 0x80000000UL, 0);
4238ed7b8fbcSLe Tan     vtd_define_long(s, DMAR_IEDATA_REG, 0, 0xffffffffUL, 0);
4239ed7b8fbcSLe Tan     vtd_define_long(s, DMAR_IEADDR_REG, 0, 0xfffffffcUL, 0);
4240ed7b8fbcSLe Tan     /* Treadted as RsvdZ when EIM in ECAP_REG is not supported */
4241ed7b8fbcSLe Tan     vtd_define_long(s, DMAR_IEUADDR_REG, 0, 0, 0);
4242ed7b8fbcSLe Tan 
42431da12ec4SLe Tan     /* IOTLB registers */
42441da12ec4SLe Tan     vtd_define_quad(s, DMAR_IOTLB_REG, 0, 0Xb003ffff00000000ULL, 0);
42451da12ec4SLe Tan     vtd_define_quad(s, DMAR_IVA_REG, 0, 0xfffffffffffff07fULL, 0);
42461da12ec4SLe Tan     vtd_define_quad_wo(s, DMAR_IVA_REG, 0xfffffffffffff07fULL);
42471da12ec4SLe Tan 
42481da12ec4SLe Tan     /* Fault Recording Registers, 128-bit */
42491da12ec4SLe Tan     vtd_define_quad(s, DMAR_FRCD_REG_0_0, 0, 0, 0);
42501da12ec4SLe Tan     vtd_define_quad(s, DMAR_FRCD_REG_0_2, 0, 0, 0x8000000000000000ULL);
4251a5861439SPeter Xu 
4252a5861439SPeter Xu     /*
425328589311SJan Kiszka      * Interrupt remapping registers.
4254a5861439SPeter Xu      */
425528589311SJan Kiszka     vtd_define_quad(s, DMAR_IRTA_REG, 0, 0xfffffffffffff80fULL, 0);
42561da12ec4SLe Tan }
42571da12ec4SLe Tan 
42581da12ec4SLe Tan /* Should not reset address_spaces when reset because devices will still use
42591da12ec4SLe Tan  * the address space they got at first (won't ask the bus again).
42601da12ec4SLe Tan  */
vtd_reset(DeviceState * dev)42611da12ec4SLe Tan static void vtd_reset(DeviceState *dev)
42621da12ec4SLe Tan {
42631da12ec4SLe Tan     IntelIOMMUState *s = INTEL_IOMMU_DEVICE(dev);
42641da12ec4SLe Tan 
42651da12ec4SLe Tan     vtd_init(s);
42662cc9ddccSPeter Xu     vtd_address_space_refresh_all(s);
42671da12ec4SLe Tan }
42681da12ec4SLe Tan 
vtd_host_dma_iommu(PCIBus * bus,void * opaque,int devfn)4269621d983aSMarcel Apfelbaum static AddressSpace *vtd_host_dma_iommu(PCIBus *bus, void *opaque, int devfn)
4270621d983aSMarcel Apfelbaum {
4271621d983aSMarcel Apfelbaum     IntelIOMMUState *s = opaque;
4272621d983aSMarcel Apfelbaum     VTDAddressSpace *vtd_as;
4273621d983aSMarcel Apfelbaum 
4274bf33cc75SPeter Xu     assert(0 <= devfn && devfn < PCI_DEVFN_MAX);
4275621d983aSMarcel Apfelbaum 
42761b2b1237SJason Wang     vtd_as = vtd_find_add_as(s, bus, devfn, PCI_NO_PASID);
4277621d983aSMarcel Apfelbaum     return &vtd_as->as;
4278621d983aSMarcel Apfelbaum }
4279621d983aSMarcel Apfelbaum 
4280ba7d12ebSYi Liu static PCIIOMMUOps vtd_iommu_ops = {
4281ba7d12ebSYi Liu     .get_address_space = vtd_host_dma_iommu,
4282a20910caSYi Liu     .set_iommu_device = vtd_dev_set_iommu_device,
4283a20910caSYi Liu     .unset_iommu_device = vtd_dev_unset_iommu_device,
4284ba7d12ebSYi Liu };
4285ba7d12ebSYi Liu 
vtd_decide_config(IntelIOMMUState * s,Error ** errp)4286e6b6af05SRadim Krčmář static bool vtd_decide_config(IntelIOMMUState *s, Error **errp)
42876333e93cSRadim Krčmář {
4288e6b6af05SRadim Krčmář     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
4289e6b6af05SRadim Krčmář 
4290a924b3d8SPeter Xu     if (s->intr_eim == ON_OFF_AUTO_ON && !x86_iommu_ir_supported(x86_iommu)) {
4291e6b6af05SRadim Krčmář         error_setg(errp, "eim=on cannot be selected without intremap=on");
4292e6b6af05SRadim Krčmář         return false;
4293e6b6af05SRadim Krčmář     }
4294e6b6af05SRadim Krčmář 
4295e6b6af05SRadim Krčmář     if (s->intr_eim == ON_OFF_AUTO_AUTO) {
4296fb506e70SRadim Krčmář         s->intr_eim = (kvm_irqchip_in_kernel() || s->buggy_eim)
4297a924b3d8SPeter Xu                       && x86_iommu_ir_supported(x86_iommu) ?
4298e6b6af05SRadim Krčmář                                               ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
4299e6b6af05SRadim Krčmář     }
4300fb506e70SRadim Krčmář     if (s->intr_eim == ON_OFF_AUTO_ON && !s->buggy_eim) {
43012cf16205SBui Quang Minh         if (kvm_irqchip_is_split() && !kvm_enable_x2apic()) {
430220ca4742SPeter Xu             error_setg(errp, "eim=on requires support on the KVM side"
430320ca4742SPeter Xu                              "(X2APIC_API, first shipped in v4.7)");
430420ca4742SPeter Xu             return false;
430520ca4742SPeter Xu         }
4306fb506e70SRadim Krčmář     }
4307e6b6af05SRadim Krčmář 
430837f51384SPrasad Singamsetty     /* Currently only address widths supported are 39 and 48 bits */
430937f51384SPrasad Singamsetty     if ((s->aw_bits != VTD_HOST_AW_39BIT) &&
431037f51384SPrasad Singamsetty         (s->aw_bits != VTD_HOST_AW_48BIT)) {
43112a345149SMenno Lageman         error_setg(errp, "Supported values for aw-bits are: %d, %d",
431237f51384SPrasad Singamsetty                    VTD_HOST_AW_39BIT, VTD_HOST_AW_48BIT);
431337f51384SPrasad Singamsetty         return false;
431437f51384SPrasad Singamsetty     }
431537f51384SPrasad Singamsetty 
43164a4f219eSYi Sun     if (s->scalable_mode && !s->dma_drain) {
43174a4f219eSYi Sun         error_setg(errp, "Need to set dma_drain for scalable mode");
43184a4f219eSYi Sun         return false;
43194a4f219eSYi Sun     }
43204a4f219eSYi Sun 
43211b2b1237SJason Wang     if (s->pasid && !s->scalable_mode) {
43221b2b1237SJason Wang         error_setg(errp, "Need to set scalable mode for PASID");
43231b2b1237SJason Wang         return false;
43241b2b1237SJason Wang     }
43251b2b1237SJason Wang 
43266333e93cSRadim Krčmář     return true;
43276333e93cSRadim Krčmář }
43286333e93cSRadim Krčmář 
vtd_machine_done_notify_one(Object * child,void * unused)432928cf553aSPeter Xu static int vtd_machine_done_notify_one(Object *child, void *unused)
433028cf553aSPeter Xu {
433128cf553aSPeter Xu     IntelIOMMUState *iommu = INTEL_IOMMU_DEVICE(x86_iommu_get_default());
433228cf553aSPeter Xu 
433328cf553aSPeter Xu     /*
433428cf553aSPeter Xu      * We hard-coded here because vfio-pci is the only special case
433528cf553aSPeter Xu      * here.  Let's be more elegant in the future when we can, but so
433628cf553aSPeter Xu      * far there seems to be no better way.
433728cf553aSPeter Xu      */
433828cf553aSPeter Xu     if (object_dynamic_cast(child, "vfio-pci") && !iommu->caching_mode) {
433928cf553aSPeter Xu         vtd_panic_require_caching_mode();
434028cf553aSPeter Xu     }
434128cf553aSPeter Xu 
434228cf553aSPeter Xu     return 0;
434328cf553aSPeter Xu }
434428cf553aSPeter Xu 
vtd_machine_done_hook(Notifier * notifier,void * unused)434528cf553aSPeter Xu static void vtd_machine_done_hook(Notifier *notifier, void *unused)
434628cf553aSPeter Xu {
434728cf553aSPeter Xu     object_child_foreach_recursive(object_get_root(),
434828cf553aSPeter Xu                                    vtd_machine_done_notify_one, NULL);
434928cf553aSPeter Xu }
435028cf553aSPeter Xu 
435128cf553aSPeter Xu static Notifier vtd_machine_done_notify = {
435228cf553aSPeter Xu     .notify = vtd_machine_done_hook,
435328cf553aSPeter Xu };
435428cf553aSPeter Xu 
vtd_realize(DeviceState * dev,Error ** errp)43551da12ec4SLe Tan static void vtd_realize(DeviceState *dev, Error **errp)
43561da12ec4SLe Tan {
4357ef0e8fc7SEduardo Habkost     MachineState *ms = MACHINE(qdev_get_machine());
435829396ed9SMohammed Gamal     PCMachineState *pcms = PC_MACHINE(ms);
4359f0bb276bSPaolo Bonzini     X86MachineState *x86ms = X86_MACHINE(ms);
4360b54a9d46SBernhard Beschow     PCIBus *bus = pcms->pcibus;
43611da12ec4SLe Tan     IntelIOMMUState *s = INTEL_IOMMU_DEVICE(dev);
43621b2b1237SJason Wang     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(s);
43631b2b1237SJason Wang 
43641b2b1237SJason Wang     if (s->pasid && x86_iommu->dt_supported) {
43651b2b1237SJason Wang         /*
43661b2b1237SJason Wang          * PASID-based-Device-TLB Invalidate Descriptor is not
43671b2b1237SJason Wang          * implemented and it requires support from vhost layer which
43681b2b1237SJason Wang          * needs to be implemented in the future.
43691b2b1237SJason Wang          */
43701b2b1237SJason Wang         error_setg(errp, "PASID based device IOTLB is not supported");
43711b2b1237SJason Wang         return;
43721b2b1237SJason Wang     }
43736333e93cSRadim Krčmář 
4374e6b6af05SRadim Krčmář     if (!vtd_decide_config(s, errp)) {
43756333e93cSRadim Krčmář         return;
43766333e93cSRadim Krčmář     }
43776333e93cSRadim Krčmář 
4378b4a4ba0dSPeter Xu     QLIST_INIT(&s->vtd_as_with_notifiers);
43791d9efa73SPeter Xu     qemu_mutex_init(&s->iommu_lock);
43801da12ec4SLe Tan     memory_region_init_io(&s->csrmem, OBJECT(s), &vtd_mem_ops, s,
43811da12ec4SLe Tan                           "intel_iommu", DMAR_REG_SIZE);
4382a540087fSPhilippe Mathieu-Daudé     memory_region_add_subregion(get_system_memory(),
4383a540087fSPhilippe Mathieu-Daudé                                 Q35_HOST_BRIDGE_IOMMU_ADDR, &s->csrmem);
43844b519ef1SPeter Xu 
43854b519ef1SPeter Xu     /* Create the shared memory regions by all devices */
43864b519ef1SPeter Xu     memory_region_init(&s->mr_nodmar, OBJECT(s), "vtd-nodmar",
43874b519ef1SPeter Xu                        UINT64_MAX);
43884b519ef1SPeter Xu     memory_region_init_io(&s->mr_ir, OBJECT(s), &vtd_mem_ir_ops,
43894b519ef1SPeter Xu                           s, "vtd-ir", VTD_INTERRUPT_ADDR_SIZE);
43904b519ef1SPeter Xu     memory_region_init_alias(&s->mr_sys_alias, OBJECT(s),
43914b519ef1SPeter Xu                              "vtd-sys-alias", get_system_memory(), 0,
43924b519ef1SPeter Xu                              memory_region_size(get_system_memory()));
43934b519ef1SPeter Xu     memory_region_add_subregion_overlap(&s->mr_nodmar, 0,
43944b519ef1SPeter Xu                                         &s->mr_sys_alias, 0);
43954b519ef1SPeter Xu     memory_region_add_subregion_overlap(&s->mr_nodmar,
43964b519ef1SPeter Xu                                         VTD_INTERRUPT_ADDR_FIRST,
43974b519ef1SPeter Xu                                         &s->mr_ir, 1);
4398b5a280c0SLe Tan     /* No corresponding destroy */
43991b2b1237SJason Wang     s->iotlb = g_hash_table_new_full(vtd_iotlb_hash, vtd_iotlb_equal,
4400b5a280c0SLe Tan                                      g_free, g_free);
4401da8d439cSJason Wang     s->vtd_address_spaces = g_hash_table_new_full(vtd_as_hash, vtd_as_equal,
44027df953bdSKnut Omang                                       g_free, g_free);
4403a20910caSYi Liu     s->vtd_host_iommu_dev = g_hash_table_new_full(vtd_hiod_hash, vtd_hiod_equal,
4404a20910caSYi Liu                                                   g_free, vtd_hiod_destroy);
44051da12ec4SLe Tan     vtd_init(s);
4406ba7d12ebSYi Liu     pci_setup_iommu(bus, &vtd_iommu_ops, dev);
4407cb135f59SPeter Xu     /* Pseudo address space under root PCI bus. */
4408f0bb276bSPaolo Bonzini     x86ms->ioapic_as = vtd_host_dma_iommu(bus, s, Q35_PSEUDO_DEVFN_IOAPIC);
440928cf553aSPeter Xu     qemu_add_machine_init_done_notifier(&vtd_machine_done_notify);
44101da12ec4SLe Tan }
44111da12ec4SLe Tan 
vtd_class_init(ObjectClass * klass,void * data)44121da12ec4SLe Tan static void vtd_class_init(ObjectClass *klass, void *data)
44131da12ec4SLe Tan {
44141da12ec4SLe Tan     DeviceClass *dc = DEVICE_CLASS(klass);
441530c60f77SEduardo Habkost     X86IOMMUClass *x86_class = X86_IOMMU_DEVICE_CLASS(klass);
44161da12ec4SLe Tan 
4417e3d08143SPeter Maydell     device_class_set_legacy_reset(dc, vtd_reset);
44181da12ec4SLe Tan     dc->vmsd = &vtd_vmstate;
44194f67d30bSMarc-André Lureau     device_class_set_props(dc, vtd_properties);
4420621d983aSMarcel Apfelbaum     dc->hotpluggable = false;
44211c7955c4SPeter Xu     x86_class->realize = vtd_realize;
44228b5ed7dfSPeter Xu     x86_class->int_remap = vtd_int_remap;
44238ab5700cSEduardo Habkost     /* Supported by the pc-q35-* machine types */
4424e4f4fb1eSEduardo Habkost     dc->user_creatable = true;
44251ec202c9SErnest Esene     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
44261ec202c9SErnest Esene     dc->desc = "Intel IOMMU (VT-d) DMA Remapping device";
44271da12ec4SLe Tan }
44281da12ec4SLe Tan 
44291da12ec4SLe Tan static const TypeInfo vtd_info = {
44301da12ec4SLe Tan     .name          = TYPE_INTEL_IOMMU_DEVICE,
44311c7955c4SPeter Xu     .parent        = TYPE_X86_IOMMU_DEVICE,
44321da12ec4SLe Tan     .instance_size = sizeof(IntelIOMMUState),
44331da12ec4SLe Tan     .class_init    = vtd_class_init,
44341da12ec4SLe Tan };
44351da12ec4SLe Tan 
vtd_iommu_memory_region_class_init(ObjectClass * klass,void * data)44361221a474SAlexey Kardashevskiy static void vtd_iommu_memory_region_class_init(ObjectClass *klass,
44371221a474SAlexey Kardashevskiy                                                      void *data)
44381221a474SAlexey Kardashevskiy {
44391221a474SAlexey Kardashevskiy     IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_CLASS(klass);
44401221a474SAlexey Kardashevskiy 
44411221a474SAlexey Kardashevskiy     imrc->translate = vtd_iommu_translate;
44421221a474SAlexey Kardashevskiy     imrc->notify_flag_changed = vtd_iommu_notify_flag_changed;
44431221a474SAlexey Kardashevskiy     imrc->replay = vtd_iommu_replay;
44441221a474SAlexey Kardashevskiy }
44451221a474SAlexey Kardashevskiy 
44461221a474SAlexey Kardashevskiy static const TypeInfo vtd_iommu_memory_region_info = {
44471221a474SAlexey Kardashevskiy     .parent = TYPE_IOMMU_MEMORY_REGION,
44481221a474SAlexey Kardashevskiy     .name = TYPE_INTEL_IOMMU_MEMORY_REGION,
44491221a474SAlexey Kardashevskiy     .class_init = vtd_iommu_memory_region_class_init,
44501221a474SAlexey Kardashevskiy };
44511221a474SAlexey Kardashevskiy 
vtd_register_types(void)44521da12ec4SLe Tan static void vtd_register_types(void)
44531da12ec4SLe Tan {
44541da12ec4SLe Tan     type_register_static(&vtd_info);
44551221a474SAlexey Kardashevskiy     type_register_static(&vtd_iommu_memory_region_info);
44561da12ec4SLe Tan }
44571da12ec4SLe Tan 
44581da12ec4SLe Tan type_init(vtd_register_types)
4459