2 * Copyright © 2006-2014 Intel Corporation.
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms and conditions of the GNU General Public License,
6 * version 2, as published by the Free Software Foundation.
8 * This program is distributed in the hope it will be useful, but WITHOUT
9 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13 * Authors: David Woodhouse <dwmw2@infradead.org>,
14 * Ashok Raj <ashok.raj@intel.com>,
15 * Shaohua Li <shaohua.li@intel.com>,
16 * Anil S Keshavamurthy <anil.s.keshavamurthy@intel.com>,
17 * Fenghua Yu <fenghua.yu@intel.com>
18 * Joerg Roedel <jroedel@suse.de>
21 #define pr_fmt(fmt) "DMAR: " fmt
23 #include <linux/init.h>
24 #include <linux/bitmap.h>
25 #include <linux/debugfs.h>
26 #include <linux/export.h>
27 #include <linux/slab.h>
28 #include <linux/irq.h>
29 #include <linux/interrupt.h>
30 #include <linux/spinlock.h>
31 #include <linux/pci.h>
32 #include <linux/dmar.h>
33 #include <linux/dma-mapping.h>
34 #include <linux/mempool.h>
35 #include <linux/memory.h>
36 #include <linux/cpu.h>
37 #include <linux/timer.h>
39 #include <linux/iova.h>
40 #include <linux/iommu.h>
41 #include <linux/intel-iommu.h>
42 #include <linux/syscore_ops.h>
43 #include <linux/tboot.h>
44 #include <linux/dmi.h>
45 #include <linux/pci-ats.h>
46 #include <linux/memblock.h>
47 #include <linux/dma-contiguous.h>
48 #include <linux/dma-direct.h>
49 #include <linux/crash_dump.h>
50 #include <asm/irq_remapping.h>
51 #include <asm/cacheflush.h>
52 #include <asm/iommu.h>
54 #include "irq_remapping.h"
55 #include "intel-pasid.h"
57 #define ROOT_SIZE VTD_PAGE_SIZE
58 #define CONTEXT_SIZE VTD_PAGE_SIZE
60 #define IS_GFX_DEVICE(pdev) ((pdev->class >> 16) == PCI_BASE_CLASS_DISPLAY)
61 #define IS_USB_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_SERIAL_USB)
62 #define IS_ISA_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_BRIDGE_ISA)
63 #define IS_AZALIA(pdev) ((pdev)->vendor == 0x8086 && (pdev)->device == 0x3a3e)
65 #define IOAPIC_RANGE_START (0xfee00000)
66 #define IOAPIC_RANGE_END (0xfeefffff)
67 #define IOVA_START_ADDR (0x1000)
69 #define DEFAULT_DOMAIN_ADDRESS_WIDTH 57
71 #define MAX_AGAW_WIDTH 64
72 #define MAX_AGAW_PFN_WIDTH (MAX_AGAW_WIDTH - VTD_PAGE_SHIFT)
74 #define __DOMAIN_MAX_PFN(gaw) ((((uint64_t)1) << (gaw-VTD_PAGE_SHIFT)) - 1)
75 #define __DOMAIN_MAX_ADDR(gaw) ((((uint64_t)1) << gaw) - 1)
77 /* We limit DOMAIN_MAX_PFN to fit in an unsigned long, and DOMAIN_MAX_ADDR
78 to match. That way, we can use 'unsigned long' for PFNs with impunity. */
79 #define DOMAIN_MAX_PFN(gaw) ((unsigned long) min_t(uint64_t, \
80 __DOMAIN_MAX_PFN(gaw), (unsigned long)-1))
81 #define DOMAIN_MAX_ADDR(gaw) (((uint64_t)__DOMAIN_MAX_PFN(gaw)) << VTD_PAGE_SHIFT)
83 /* IO virtual address start page frame number */
84 #define IOVA_START_PFN (1)
86 #define IOVA_PFN(addr) ((addr) >> PAGE_SHIFT)
88 /* page table handling */
89 #define LEVEL_STRIDE (9)
90 #define LEVEL_MASK (((u64)1 << LEVEL_STRIDE) - 1)
93 * This bitmap is used to advertise the page sizes our hardware support
94 * to the IOMMU core, which will then use this information to split
95 * physically contiguous memory regions it is mapping into page sizes
98 * Traditionally the IOMMU core just handed us the mappings directly,
99 * after making sure the size is an order of a 4KiB page and that the
100 * mapping has natural alignment.
102 * To retain this behavior, we currently advertise that we support
103 * all page sizes that are an order of 4KiB.
105 * If at some point we'd like to utilize the IOMMU core's new behavior,
106 * we could change this to advertise the real page sizes we support.
108 #define INTEL_IOMMU_PGSIZES (~0xFFFUL)
110 static inline int agaw_to_level(int agaw)
115 static inline int agaw_to_width(int agaw)
117 return min_t(int, 30 + agaw * LEVEL_STRIDE, MAX_AGAW_WIDTH);
120 static inline int width_to_agaw(int width)
122 return DIV_ROUND_UP(width - 30, LEVEL_STRIDE);
125 static inline unsigned int level_to_offset_bits(int level)
127 return (level - 1) * LEVEL_STRIDE;
130 static inline int pfn_level_offset(unsigned long pfn, int level)
132 return (pfn >> level_to_offset_bits(level)) & LEVEL_MASK;
135 static inline unsigned long level_mask(int level)
137 return -1UL << level_to_offset_bits(level);
140 static inline unsigned long level_size(int level)
142 return 1UL << level_to_offset_bits(level);
145 static inline unsigned long align_to_level(unsigned long pfn, int level)
147 return (pfn + level_size(level) - 1) & level_mask(level);
150 static inline unsigned long lvl_to_nr_pages(unsigned int lvl)
152 return 1 << min_t(int, (lvl - 1) * LEVEL_STRIDE, MAX_AGAW_PFN_WIDTH);
155 /* VT-d pages must always be _smaller_ than MM pages. Otherwise things
156 are never going to work. */
157 static inline unsigned long dma_to_mm_pfn(unsigned long dma_pfn)
159 return dma_pfn >> (PAGE_SHIFT - VTD_PAGE_SHIFT);
162 static inline unsigned long mm_to_dma_pfn(unsigned long mm_pfn)
164 return mm_pfn << (PAGE_SHIFT - VTD_PAGE_SHIFT);
166 static inline unsigned long page_to_dma_pfn(struct page *pg)
168 return mm_to_dma_pfn(page_to_pfn(pg));
170 static inline unsigned long virt_to_dma_pfn(void *p)
172 return page_to_dma_pfn(virt_to_page(p));
175 /* global iommu list, set NULL for ignored DMAR units */
176 static struct intel_iommu **g_iommus;
178 static void __init check_tylersburg_isoch(void);
179 static int rwbf_quirk;
182 * set to 1 to panic kernel if can't successfully enable VT-d
183 * (used when kernel is launched w/ TXT)
185 static int force_on = 0;
186 int intel_iommu_tboot_noforce;
191 * 12-63: Context Ptr (12 - (haw-1))
198 #define ROOT_ENTRY_NR (VTD_PAGE_SIZE/sizeof(struct root_entry))
201 * Take a root_entry and return the Lower Context Table Pointer (LCTP)
204 static phys_addr_t root_entry_lctp(struct root_entry *re)
209 return re->lo & VTD_PAGE_MASK;
213 * Take a root_entry and return the Upper Context Table Pointer (UCTP)
216 static phys_addr_t root_entry_uctp(struct root_entry *re)
221 return re->hi & VTD_PAGE_MASK;
226 * 1: fault processing disable
227 * 2-3: translation type
228 * 12-63: address space root
234 struct context_entry {
239 static inline void context_clear_pasid_enable(struct context_entry *context)
241 context->lo &= ~(1ULL << 11);
244 static inline bool context_pasid_enabled(struct context_entry *context)
246 return !!(context->lo & (1ULL << 11));
249 static inline void context_set_copied(struct context_entry *context)
251 context->hi |= (1ull << 3);
254 static inline bool context_copied(struct context_entry *context)
256 return !!(context->hi & (1ULL << 3));
259 static inline bool __context_present(struct context_entry *context)
261 return (context->lo & 1);
264 static inline bool context_present(struct context_entry *context)
266 return context_pasid_enabled(context) ?
267 __context_present(context) :
268 __context_present(context) && !context_copied(context);
271 static inline void context_set_present(struct context_entry *context)
276 static inline void context_set_fault_enable(struct context_entry *context)
278 context->lo &= (((u64)-1) << 2) | 1;
281 static inline void context_set_translation_type(struct context_entry *context,
284 context->lo &= (((u64)-1) << 4) | 3;
285 context->lo |= (value & 3) << 2;
288 static inline void context_set_address_root(struct context_entry *context,
291 context->lo &= ~VTD_PAGE_MASK;
292 context->lo |= value & VTD_PAGE_MASK;
295 static inline void context_set_address_width(struct context_entry *context,
298 context->hi |= value & 7;
301 static inline void context_set_domain_id(struct context_entry *context,
304 context->hi |= (value & ((1 << 16) - 1)) << 8;
307 static inline int context_domain_id(struct context_entry *c)
309 return((c->hi >> 8) & 0xffff);
312 static inline void context_clear_entry(struct context_entry *context)
325 * 12-63: Host physcial address
331 static inline void dma_clear_pte(struct dma_pte *pte)
336 static inline u64 dma_pte_addr(struct dma_pte *pte)
339 return pte->val & VTD_PAGE_MASK;
341 /* Must have a full atomic 64-bit read */
342 return __cmpxchg64(&pte->val, 0ULL, 0ULL) & VTD_PAGE_MASK;
346 static inline bool dma_pte_present(struct dma_pte *pte)
348 return (pte->val & 3) != 0;
351 static inline bool dma_pte_superpage(struct dma_pte *pte)
353 return (pte->val & DMA_PTE_LARGE_PAGE);
356 static inline int first_pte_in_page(struct dma_pte *pte)
358 return !((unsigned long)pte & ~VTD_PAGE_MASK);
362 * This domain is a statically identity mapping domain.
363 * 1. This domain creats a static 1:1 mapping to all usable memory.
364 * 2. It maps to each iommu if successful.
365 * 3. Each iommu mapps to this domain if successful.
367 static struct dmar_domain *si_domain;
368 static int hw_pass_through = 1;
371 * Domain represents a virtual machine, more than one devices
372 * across iommus may be owned in one domain, e.g. kvm guest.
374 #define DOMAIN_FLAG_VIRTUAL_MACHINE (1 << 0)
376 /* si_domain contains mulitple devices */
377 #define DOMAIN_FLAG_STATIC_IDENTITY (1 << 1)
379 #define for_each_domain_iommu(idx, domain) \
380 for (idx = 0; idx < g_num_of_iommus; idx++) \
381 if (domain->iommu_refcnt[idx])
383 struct dmar_rmrr_unit {
384 struct list_head list; /* list of rmrr units */
385 struct acpi_dmar_header *hdr; /* ACPI header */
386 u64 base_address; /* reserved base address*/
387 u64 end_address; /* reserved end address */
388 struct dmar_dev_scope *devices; /* target devices */
389 int devices_cnt; /* target device count */
390 struct iommu_resv_region *resv; /* reserved region handle */
393 struct dmar_atsr_unit {
394 struct list_head list; /* list of ATSR units */
395 struct acpi_dmar_header *hdr; /* ACPI header */
396 struct dmar_dev_scope *devices; /* target devices */
397 int devices_cnt; /* target device count */
398 u8 include_all:1; /* include all ports */
401 static LIST_HEAD(dmar_atsr_units);
402 static LIST_HEAD(dmar_rmrr_units);
404 #define for_each_rmrr_units(rmrr) \
405 list_for_each_entry(rmrr, &dmar_rmrr_units, list)
407 /* bitmap for indexing intel_iommus */
408 static int g_num_of_iommus;
410 static void domain_exit(struct dmar_domain *domain);
411 static void domain_remove_dev_info(struct dmar_domain *domain);
412 static void dmar_remove_one_dev_info(struct dmar_domain *domain,
414 static void __dmar_remove_one_dev_info(struct device_domain_info *info);
415 static void domain_context_clear(struct intel_iommu *iommu,
417 static int domain_detach_iommu(struct dmar_domain *domain,
418 struct intel_iommu *iommu);
420 #ifdef CONFIG_INTEL_IOMMU_DEFAULT_ON
421 int dmar_disabled = 0;
423 int dmar_disabled = 1;
424 #endif /*CONFIG_INTEL_IOMMU_DEFAULT_ON*/
426 int intel_iommu_enabled = 0;
427 EXPORT_SYMBOL_GPL(intel_iommu_enabled);
429 static int dmar_map_gfx = 1;
430 static int dmar_forcedac;
431 static int intel_iommu_strict;
432 static int intel_iommu_superpage = 1;
433 static int intel_iommu_ecs = 1;
434 static int intel_iommu_pasid28;
435 static int iommu_identity_mapping;
437 #define IDENTMAP_ALL 1
438 #define IDENTMAP_GFX 2
439 #define IDENTMAP_AZALIA 4
441 /* Broadwell and Skylake have broken ECS support — normal so-called "second
442 * level" translation of DMA requests-without-PASID doesn't actually happen
443 * unless you also set the NESTE bit in an extended context-entry. Which of
444 * course means that SVM doesn't work because it's trying to do nested
445 * translation of the physical addresses it finds in the process page tables,
446 * through the IOVA->phys mapping found in the "second level" page tables.
448 * The VT-d specification was retroactively changed to change the definition
449 * of the capability bits and pretend that Broadwell/Skylake never happened...
450 * but unfortunately the wrong bit was changed. It's ECS which is broken, but
451 * for some reason it was the PASID capability bit which was redefined (from
452 * bit 28 on BDW/SKL to bit 40 in future).
454 * So our test for ECS needs to eschew those implementations which set the old
455 * PASID capabiity bit 28, since those are the ones on which ECS is broken.
456 * Unless we are working around the 'pasid28' limitations, that is, by putting
457 * the device into passthrough mode for normal DMA and thus masking the bug.
459 #define ecs_enabled(iommu) (intel_iommu_ecs && ecap_ecs(iommu->ecap) && \
460 (intel_iommu_pasid28 || !ecap_broken_pasid(iommu->ecap)))
461 /* PASID support is thus enabled if ECS is enabled and *either* of the old
462 * or new capability bits are set. */
463 #define pasid_enabled(iommu) (ecs_enabled(iommu) && \
464 (ecap_pasid(iommu->ecap) || ecap_broken_pasid(iommu->ecap)))
466 int intel_iommu_gfx_mapped;
467 EXPORT_SYMBOL_GPL(intel_iommu_gfx_mapped);
469 #define DUMMY_DEVICE_DOMAIN_INFO ((struct device_domain_info *)(-1))
470 static DEFINE_SPINLOCK(device_domain_lock);
471 static LIST_HEAD(device_domain_list);
474 * Iterate over elements in device_domain_list and call the specified
475 * callback @fn against each element. This helper should only be used
476 * in the context where the device_domain_lock has already been holden.
478 int for_each_device_domain(int (*fn)(struct device_domain_info *info,
479 void *data), void *data)
482 struct device_domain_info *info;
484 assert_spin_locked(&device_domain_lock);
485 list_for_each_entry(info, &device_domain_list, global) {
486 ret = fn(info, data);
494 const struct iommu_ops intel_iommu_ops;
496 static bool translation_pre_enabled(struct intel_iommu *iommu)
498 return (iommu->flags & VTD_FLAG_TRANS_PRE_ENABLED);
501 static void clear_translation_pre_enabled(struct intel_iommu *iommu)
503 iommu->flags &= ~VTD_FLAG_TRANS_PRE_ENABLED;
506 static void init_translation_status(struct intel_iommu *iommu)
510 gsts = readl(iommu->reg + DMAR_GSTS_REG);
511 if (gsts & DMA_GSTS_TES)
512 iommu->flags |= VTD_FLAG_TRANS_PRE_ENABLED;
515 /* Convert generic 'struct iommu_domain to private struct dmar_domain */
516 static struct dmar_domain *to_dmar_domain(struct iommu_domain *dom)
518 return container_of(dom, struct dmar_domain, domain);
521 static int __init intel_iommu_setup(char *str)
526 if (!strncmp(str, "on", 2)) {
528 pr_info("IOMMU enabled\n");
529 } else if (!strncmp(str, "off", 3)) {
531 pr_info("IOMMU disabled\n");
532 } else if (!strncmp(str, "igfx_off", 8)) {
534 pr_info("Disable GFX device mapping\n");
535 } else if (!strncmp(str, "forcedac", 8)) {
536 pr_info("Forcing DAC for PCI devices\n");
538 } else if (!strncmp(str, "strict", 6)) {
539 pr_info("Disable batched IOTLB flush\n");
540 intel_iommu_strict = 1;
541 } else if (!strncmp(str, "sp_off", 6)) {
542 pr_info("Disable supported super page\n");
543 intel_iommu_superpage = 0;
544 } else if (!strncmp(str, "ecs_off", 7)) {
546 "Intel-IOMMU: disable extended context table support\n");
548 } else if (!strncmp(str, "pasid28", 7)) {
550 "Intel-IOMMU: enable pre-production PASID support\n");
551 intel_iommu_pasid28 = 1;
552 iommu_identity_mapping |= IDENTMAP_GFX;
553 } else if (!strncmp(str, "tboot_noforce", 13)) {
555 "Intel-IOMMU: not forcing on after tboot. This could expose security risk for tboot\n");
556 intel_iommu_tboot_noforce = 1;
559 str += strcspn(str, ",");
565 __setup("intel_iommu=", intel_iommu_setup);
567 static struct kmem_cache *iommu_domain_cache;
568 static struct kmem_cache *iommu_devinfo_cache;
570 static struct dmar_domain* get_iommu_domain(struct intel_iommu *iommu, u16 did)
572 struct dmar_domain **domains;
575 domains = iommu->domains[idx];
579 return domains[did & 0xff];
582 static void set_iommu_domain(struct intel_iommu *iommu, u16 did,
583 struct dmar_domain *domain)
585 struct dmar_domain **domains;
588 if (!iommu->domains[idx]) {
589 size_t size = 256 * sizeof(struct dmar_domain *);
590 iommu->domains[idx] = kzalloc(size, GFP_ATOMIC);
593 domains = iommu->domains[idx];
594 if (WARN_ON(!domains))
597 domains[did & 0xff] = domain;
600 void *alloc_pgtable_page(int node)
605 page = alloc_pages_node(node, GFP_ATOMIC | __GFP_ZERO, 0);
607 vaddr = page_address(page);
611 void free_pgtable_page(void *vaddr)
613 free_page((unsigned long)vaddr);
616 static inline void *alloc_domain_mem(void)
618 return kmem_cache_alloc(iommu_domain_cache, GFP_ATOMIC);
621 static void free_domain_mem(void *vaddr)
623 kmem_cache_free(iommu_domain_cache, vaddr);
626 static inline void * alloc_devinfo_mem(void)
628 return kmem_cache_alloc(iommu_devinfo_cache, GFP_ATOMIC);
631 static inline void free_devinfo_mem(void *vaddr)
633 kmem_cache_free(iommu_devinfo_cache, vaddr);
636 static inline int domain_type_is_vm(struct dmar_domain *domain)
638 return domain->flags & DOMAIN_FLAG_VIRTUAL_MACHINE;
641 static inline int domain_type_is_si(struct dmar_domain *domain)
643 return domain->flags & DOMAIN_FLAG_STATIC_IDENTITY;
646 static inline int domain_type_is_vm_or_si(struct dmar_domain *domain)
648 return domain->flags & (DOMAIN_FLAG_VIRTUAL_MACHINE |
649 DOMAIN_FLAG_STATIC_IDENTITY);
652 static inline int domain_pfn_supported(struct dmar_domain *domain,
655 int addr_width = agaw_to_width(domain->agaw) - VTD_PAGE_SHIFT;
657 return !(addr_width < BITS_PER_LONG && pfn >> addr_width);
660 static int __iommu_calculate_agaw(struct intel_iommu *iommu, int max_gaw)
665 sagaw = cap_sagaw(iommu->cap);
666 for (agaw = width_to_agaw(max_gaw);
668 if (test_bit(agaw, &sagaw))
676 * Calculate max SAGAW for each iommu.
678 int iommu_calculate_max_sagaw(struct intel_iommu *iommu)
680 return __iommu_calculate_agaw(iommu, MAX_AGAW_WIDTH);
684 * calculate agaw for each iommu.
685 * "SAGAW" may be different across iommus, use a default agaw, and
686 * get a supported less agaw for iommus that don't support the default agaw.
688 int iommu_calculate_agaw(struct intel_iommu *iommu)
690 return __iommu_calculate_agaw(iommu, DEFAULT_DOMAIN_ADDRESS_WIDTH);
693 /* This functionin only returns single iommu in a domain */
694 struct intel_iommu *domain_get_iommu(struct dmar_domain *domain)
698 /* si_domain and vm domain should not get here. */
699 BUG_ON(domain_type_is_vm_or_si(domain));
700 for_each_domain_iommu(iommu_id, domain)
703 if (iommu_id < 0 || iommu_id >= g_num_of_iommus)
706 return g_iommus[iommu_id];
709 static void domain_update_iommu_coherency(struct dmar_domain *domain)
711 struct dmar_drhd_unit *drhd;
712 struct intel_iommu *iommu;
716 domain->iommu_coherency = 1;
718 for_each_domain_iommu(i, domain) {
720 if (!ecap_coherent(g_iommus[i]->ecap)) {
721 domain->iommu_coherency = 0;
728 /* No hardware attached; use lowest common denominator */
730 for_each_active_iommu(iommu, drhd) {
731 if (!ecap_coherent(iommu->ecap)) {
732 domain->iommu_coherency = 0;
739 static int domain_update_iommu_snooping(struct intel_iommu *skip)
741 struct dmar_drhd_unit *drhd;
742 struct intel_iommu *iommu;
746 for_each_active_iommu(iommu, drhd) {
748 if (!ecap_sc_support(iommu->ecap)) {
759 static int domain_update_iommu_superpage(struct intel_iommu *skip)
761 struct dmar_drhd_unit *drhd;
762 struct intel_iommu *iommu;
765 if (!intel_iommu_superpage) {
769 /* set iommu_superpage to the smallest common denominator */
771 for_each_active_iommu(iommu, drhd) {
773 mask &= cap_super_page_val(iommu->cap);
783 /* Some capabilities may be different across iommus */
784 static void domain_update_iommu_cap(struct dmar_domain *domain)
786 domain_update_iommu_coherency(domain);
787 domain->iommu_snooping = domain_update_iommu_snooping(NULL);
788 domain->iommu_superpage = domain_update_iommu_superpage(NULL);
791 static inline struct context_entry *iommu_context_addr(struct intel_iommu *iommu,
792 u8 bus, u8 devfn, int alloc)
794 struct root_entry *root = &iommu->root_entry[bus];
795 struct context_entry *context;
799 if (ecs_enabled(iommu)) {
807 context = phys_to_virt(*entry & VTD_PAGE_MASK);
809 unsigned long phy_addr;
813 context = alloc_pgtable_page(iommu->node);
817 __iommu_flush_cache(iommu, (void *)context, CONTEXT_SIZE);
818 phy_addr = virt_to_phys((void *)context);
819 *entry = phy_addr | 1;
820 __iommu_flush_cache(iommu, entry, sizeof(*entry));
822 return &context[devfn];
825 static int iommu_dummy(struct device *dev)
827 return dev->archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO;
830 static struct intel_iommu *device_to_iommu(struct device *dev, u8 *bus, u8 *devfn)
832 struct dmar_drhd_unit *drhd = NULL;
833 struct intel_iommu *iommu;
835 struct pci_dev *ptmp, *pdev = NULL;
839 if (iommu_dummy(dev))
842 if (dev_is_pci(dev)) {
843 struct pci_dev *pf_pdev;
845 pdev = to_pci_dev(dev);
848 /* VMD child devices currently cannot be handled individually */
849 if (is_vmd(pdev->bus))
853 /* VFs aren't listed in scope tables; we need to look up
854 * the PF instead to find the IOMMU. */
855 pf_pdev = pci_physfn(pdev);
857 segment = pci_domain_nr(pdev->bus);
858 } else if (has_acpi_companion(dev))
859 dev = &ACPI_COMPANION(dev)->dev;
862 for_each_active_iommu(iommu, drhd) {
863 if (pdev && segment != drhd->segment)
866 for_each_active_dev_scope(drhd->devices,
867 drhd->devices_cnt, i, tmp) {
869 /* For a VF use its original BDF# not that of the PF
870 * which we used for the IOMMU lookup. Strictly speaking
871 * we could do this for all PCI devices; we only need to
872 * get the BDF# from the scope table for ACPI matches. */
873 if (pdev && pdev->is_virtfn)
876 *bus = drhd->devices[i].bus;
877 *devfn = drhd->devices[i].devfn;
881 if (!pdev || !dev_is_pci(tmp))
884 ptmp = to_pci_dev(tmp);
885 if (ptmp->subordinate &&
886 ptmp->subordinate->number <= pdev->bus->number &&
887 ptmp->subordinate->busn_res.end >= pdev->bus->number)
891 if (pdev && drhd->include_all) {
893 *bus = pdev->bus->number;
894 *devfn = pdev->devfn;
905 static void domain_flush_cache(struct dmar_domain *domain,
906 void *addr, int size)
908 if (!domain->iommu_coherency)
909 clflush_cache_range(addr, size);
912 static int device_context_mapped(struct intel_iommu *iommu, u8 bus, u8 devfn)
914 struct context_entry *context;
918 spin_lock_irqsave(&iommu->lock, flags);
919 context = iommu_context_addr(iommu, bus, devfn, 0);
921 ret = context_present(context);
922 spin_unlock_irqrestore(&iommu->lock, flags);
926 static void free_context_table(struct intel_iommu *iommu)
930 struct context_entry *context;
932 spin_lock_irqsave(&iommu->lock, flags);
933 if (!iommu->root_entry) {
936 for (i = 0; i < ROOT_ENTRY_NR; i++) {
937 context = iommu_context_addr(iommu, i, 0, 0);
939 free_pgtable_page(context);
941 if (!ecs_enabled(iommu))
944 context = iommu_context_addr(iommu, i, 0x80, 0);
946 free_pgtable_page(context);
949 free_pgtable_page(iommu->root_entry);
950 iommu->root_entry = NULL;
952 spin_unlock_irqrestore(&iommu->lock, flags);
955 static struct dma_pte *pfn_to_dma_pte(struct dmar_domain *domain,
956 unsigned long pfn, int *target_level)
958 struct dma_pte *parent, *pte = NULL;
959 int level = agaw_to_level(domain->agaw);
962 BUG_ON(!domain->pgd);
964 if (!domain_pfn_supported(domain, pfn))
965 /* Address beyond IOMMU's addressing capabilities. */
968 parent = domain->pgd;
973 offset = pfn_level_offset(pfn, level);
974 pte = &parent[offset];
975 if (!*target_level && (dma_pte_superpage(pte) || !dma_pte_present(pte)))
977 if (level == *target_level)
980 if (!dma_pte_present(pte)) {
983 tmp_page = alloc_pgtable_page(domain->nid);
988 domain_flush_cache(domain, tmp_page, VTD_PAGE_SIZE);
989 pteval = ((uint64_t)virt_to_dma_pfn(tmp_page) << VTD_PAGE_SHIFT) | DMA_PTE_READ | DMA_PTE_WRITE;
990 if (cmpxchg64(&pte->val, 0ULL, pteval))
991 /* Someone else set it while we were thinking; use theirs. */
992 free_pgtable_page(tmp_page);
994 domain_flush_cache(domain, pte, sizeof(*pte));
999 parent = phys_to_virt(dma_pte_addr(pte));
1004 *target_level = level;
1010 /* return address's pte at specific level */
1011 static struct dma_pte *dma_pfn_level_pte(struct dmar_domain *domain,
1013 int level, int *large_page)
1015 struct dma_pte *parent, *pte = NULL;
1016 int total = agaw_to_level(domain->agaw);
1019 parent = domain->pgd;
1020 while (level <= total) {
1021 offset = pfn_level_offset(pfn, total);
1022 pte = &parent[offset];
1026 if (!dma_pte_present(pte)) {
1027 *large_page = total;
1031 if (dma_pte_superpage(pte)) {
1032 *large_page = total;
1036 parent = phys_to_virt(dma_pte_addr(pte));
1042 /* clear last level pte, a tlb flush should be followed */
1043 static void dma_pte_clear_range(struct dmar_domain *domain,
1044 unsigned long start_pfn,
1045 unsigned long last_pfn)
1047 unsigned int large_page = 1;
1048 struct dma_pte *first_pte, *pte;
1050 BUG_ON(!domain_pfn_supported(domain, start_pfn));
1051 BUG_ON(!domain_pfn_supported(domain, last_pfn));
1052 BUG_ON(start_pfn > last_pfn);
1054 /* we don't need lock here; nobody else touches the iova range */
1057 first_pte = pte = dma_pfn_level_pte(domain, start_pfn, 1, &large_page);
1059 start_pfn = align_to_level(start_pfn + 1, large_page + 1);
1064 start_pfn += lvl_to_nr_pages(large_page);
1066 } while (start_pfn <= last_pfn && !first_pte_in_page(pte));
1068 domain_flush_cache(domain, first_pte,
1069 (void *)pte - (void *)first_pte);
1071 } while (start_pfn && start_pfn <= last_pfn);
1074 static void dma_pte_free_level(struct dmar_domain *domain, int level,
1075 int retain_level, struct dma_pte *pte,
1076 unsigned long pfn, unsigned long start_pfn,
1077 unsigned long last_pfn)
1079 pfn = max(start_pfn, pfn);
1080 pte = &pte[pfn_level_offset(pfn, level)];
1083 unsigned long level_pfn;
1084 struct dma_pte *level_pte;
1086 if (!dma_pte_present(pte) || dma_pte_superpage(pte))
1089 level_pfn = pfn & level_mask(level);
1090 level_pte = phys_to_virt(dma_pte_addr(pte));
1093 dma_pte_free_level(domain, level - 1, retain_level,
1094 level_pte, level_pfn, start_pfn,
1099 * Free the page table if we're below the level we want to
1100 * retain and the range covers the entire table.
1102 if (level < retain_level && !(start_pfn > level_pfn ||
1103 last_pfn < level_pfn + level_size(level) - 1)) {
1105 domain_flush_cache(domain, pte, sizeof(*pte));
1106 free_pgtable_page(level_pte);
1109 pfn += level_size(level);
1110 } while (!first_pte_in_page(++pte) && pfn <= last_pfn);
1114 * clear last level (leaf) ptes and free page table pages below the
1115 * level we wish to keep intact.
1117 static void dma_pte_free_pagetable(struct dmar_domain *domain,
1118 unsigned long start_pfn,
1119 unsigned long last_pfn,
1122 BUG_ON(!domain_pfn_supported(domain, start_pfn));
1123 BUG_ON(!domain_pfn_supported(domain, last_pfn));
1124 BUG_ON(start_pfn > last_pfn);
1126 dma_pte_clear_range(domain, start_pfn, last_pfn);
1128 /* We don't need lock here; nobody else touches the iova range */
1129 dma_pte_free_level(domain, agaw_to_level(domain->agaw), retain_level,
1130 domain->pgd, 0, start_pfn, last_pfn);
1133 if (start_pfn == 0 && last_pfn == DOMAIN_MAX_PFN(domain->gaw)) {
1134 free_pgtable_page(domain->pgd);
1139 /* When a page at a given level is being unlinked from its parent, we don't
1140 need to *modify* it at all. All we need to do is make a list of all the
1141 pages which can be freed just as soon as we've flushed the IOTLB and we
1142 know the hardware page-walk will no longer touch them.
1143 The 'pte' argument is the *parent* PTE, pointing to the page that is to
1145 static struct page *dma_pte_list_pagetables(struct dmar_domain *domain,
1146 int level, struct dma_pte *pte,
1147 struct page *freelist)
1151 pg = pfn_to_page(dma_pte_addr(pte) >> PAGE_SHIFT);
1152 pg->freelist = freelist;
1158 pte = page_address(pg);
1160 if (dma_pte_present(pte) && !dma_pte_superpage(pte))
1161 freelist = dma_pte_list_pagetables(domain, level - 1,
1164 } while (!first_pte_in_page(pte));
1169 static struct page *dma_pte_clear_level(struct dmar_domain *domain, int level,
1170 struct dma_pte *pte, unsigned long pfn,
1171 unsigned long start_pfn,
1172 unsigned long last_pfn,
1173 struct page *freelist)
1175 struct dma_pte *first_pte = NULL, *last_pte = NULL;
1177 pfn = max(start_pfn, pfn);
1178 pte = &pte[pfn_level_offset(pfn, level)];
1181 unsigned long level_pfn;
1183 if (!dma_pte_present(pte))
1186 level_pfn = pfn & level_mask(level);
1188 /* If range covers entire pagetable, free it */
1189 if (start_pfn <= level_pfn &&
1190 last_pfn >= level_pfn + level_size(level) - 1) {
1191 /* These suborbinate page tables are going away entirely. Don't
1192 bother to clear them; we're just going to *free* them. */
1193 if (level > 1 && !dma_pte_superpage(pte))
1194 freelist = dma_pte_list_pagetables(domain, level - 1, pte, freelist);
1200 } else if (level > 1) {
1201 /* Recurse down into a level that isn't *entirely* obsolete */
1202 freelist = dma_pte_clear_level(domain, level - 1,
1203 phys_to_virt(dma_pte_addr(pte)),
1204 level_pfn, start_pfn, last_pfn,
1208 pfn += level_size(level);
1209 } while (!first_pte_in_page(++pte) && pfn <= last_pfn);
1212 domain_flush_cache(domain, first_pte,
1213 (void *)++last_pte - (void *)first_pte);
1218 /* We can't just free the pages because the IOMMU may still be walking
1219 the page tables, and may have cached the intermediate levels. The
1220 pages can only be freed after the IOTLB flush has been done. */
1221 static struct page *domain_unmap(struct dmar_domain *domain,
1222 unsigned long start_pfn,
1223 unsigned long last_pfn)
1225 struct page *freelist = NULL;
1227 BUG_ON(!domain_pfn_supported(domain, start_pfn));
1228 BUG_ON(!domain_pfn_supported(domain, last_pfn));
1229 BUG_ON(start_pfn > last_pfn);
1231 /* we don't need lock here; nobody else touches the iova range */
1232 freelist = dma_pte_clear_level(domain, agaw_to_level(domain->agaw),
1233 domain->pgd, 0, start_pfn, last_pfn, NULL);
1236 if (start_pfn == 0 && last_pfn == DOMAIN_MAX_PFN(domain->gaw)) {
1237 struct page *pgd_page = virt_to_page(domain->pgd);
1238 pgd_page->freelist = freelist;
1239 freelist = pgd_page;
1247 static void dma_free_pagelist(struct page *freelist)
1251 while ((pg = freelist)) {
1252 freelist = pg->freelist;
1253 free_pgtable_page(page_address(pg));
1257 static void iova_entry_free(unsigned long data)
1259 struct page *freelist = (struct page *)data;
1261 dma_free_pagelist(freelist);
1264 /* iommu handling */
1265 static int iommu_alloc_root_entry(struct intel_iommu *iommu)
1267 struct root_entry *root;
1268 unsigned long flags;
1270 root = (struct root_entry *)alloc_pgtable_page(iommu->node);
1272 pr_err("Allocating root entry for %s failed\n",
1277 __iommu_flush_cache(iommu, root, ROOT_SIZE);
1279 spin_lock_irqsave(&iommu->lock, flags);
1280 iommu->root_entry = root;
1281 spin_unlock_irqrestore(&iommu->lock, flags);
1286 static void iommu_set_root_entry(struct intel_iommu *iommu)
1292 addr = virt_to_phys(iommu->root_entry);
1293 if (ecs_enabled(iommu))
1294 addr |= DMA_RTADDR_RTT;
1296 raw_spin_lock_irqsave(&iommu->register_lock, flag);
1297 dmar_writeq(iommu->reg + DMAR_RTADDR_REG, addr);
1299 writel(iommu->gcmd | DMA_GCMD_SRTP, iommu->reg + DMAR_GCMD_REG);
1301 /* Make sure hardware complete it */
1302 IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
1303 readl, (sts & DMA_GSTS_RTPS), sts);
1305 raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1308 static void iommu_flush_write_buffer(struct intel_iommu *iommu)
1313 if (!rwbf_quirk && !cap_rwbf(iommu->cap))
1316 raw_spin_lock_irqsave(&iommu->register_lock, flag);
1317 writel(iommu->gcmd | DMA_GCMD_WBF, iommu->reg + DMAR_GCMD_REG);
1319 /* Make sure hardware complete it */
1320 IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
1321 readl, (!(val & DMA_GSTS_WBFS)), val);
1323 raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1326 /* return value determine if we need a write buffer flush */
1327 static void __iommu_flush_context(struct intel_iommu *iommu,
1328 u16 did, u16 source_id, u8 function_mask,
1335 case DMA_CCMD_GLOBAL_INVL:
1336 val = DMA_CCMD_GLOBAL_INVL;
1338 case DMA_CCMD_DOMAIN_INVL:
1339 val = DMA_CCMD_DOMAIN_INVL|DMA_CCMD_DID(did);
1341 case DMA_CCMD_DEVICE_INVL:
1342 val = DMA_CCMD_DEVICE_INVL|DMA_CCMD_DID(did)
1343 | DMA_CCMD_SID(source_id) | DMA_CCMD_FM(function_mask);
1348 val |= DMA_CCMD_ICC;
1350 raw_spin_lock_irqsave(&iommu->register_lock, flag);
1351 dmar_writeq(iommu->reg + DMAR_CCMD_REG, val);
1353 /* Make sure hardware complete it */
1354 IOMMU_WAIT_OP(iommu, DMAR_CCMD_REG,
1355 dmar_readq, (!(val & DMA_CCMD_ICC)), val);
1357 raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1360 /* return value determine if we need a write buffer flush */
1361 static void __iommu_flush_iotlb(struct intel_iommu *iommu, u16 did,
1362 u64 addr, unsigned int size_order, u64 type)
1364 int tlb_offset = ecap_iotlb_offset(iommu->ecap);
1365 u64 val = 0, val_iva = 0;
1369 case DMA_TLB_GLOBAL_FLUSH:
1370 /* global flush doesn't need set IVA_REG */
1371 val = DMA_TLB_GLOBAL_FLUSH|DMA_TLB_IVT;
1373 case DMA_TLB_DSI_FLUSH:
1374 val = DMA_TLB_DSI_FLUSH|DMA_TLB_IVT|DMA_TLB_DID(did);
1376 case DMA_TLB_PSI_FLUSH:
1377 val = DMA_TLB_PSI_FLUSH|DMA_TLB_IVT|DMA_TLB_DID(did);
1378 /* IH bit is passed in as part of address */
1379 val_iva = size_order | addr;
1384 /* Note: set drain read/write */
1387 * This is probably to be super secure.. Looks like we can
1388 * ignore it without any impact.
1390 if (cap_read_drain(iommu->cap))
1391 val |= DMA_TLB_READ_DRAIN;
1393 if (cap_write_drain(iommu->cap))
1394 val |= DMA_TLB_WRITE_DRAIN;
1396 raw_spin_lock_irqsave(&iommu->register_lock, flag);
1397 /* Note: Only uses first TLB reg currently */
1399 dmar_writeq(iommu->reg + tlb_offset, val_iva);
1400 dmar_writeq(iommu->reg + tlb_offset + 8, val);
1402 /* Make sure hardware complete it */
1403 IOMMU_WAIT_OP(iommu, tlb_offset + 8,
1404 dmar_readq, (!(val & DMA_TLB_IVT)), val);
1406 raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1408 /* check IOTLB invalidation granularity */
1409 if (DMA_TLB_IAIG(val) == 0)
1410 pr_err("Flush IOTLB failed\n");
1411 if (DMA_TLB_IAIG(val) != DMA_TLB_IIRG(type))
1412 pr_debug("TLB flush request %Lx, actual %Lx\n",
1413 (unsigned long long)DMA_TLB_IIRG(type),
1414 (unsigned long long)DMA_TLB_IAIG(val));
1417 static struct device_domain_info *
1418 iommu_support_dev_iotlb (struct dmar_domain *domain, struct intel_iommu *iommu,
1421 struct device_domain_info *info;
1423 assert_spin_locked(&device_domain_lock);
1428 list_for_each_entry(info, &domain->devices, link)
1429 if (info->iommu == iommu && info->bus == bus &&
1430 info->devfn == devfn) {
1431 if (info->ats_supported && info->dev)
1439 static void domain_update_iotlb(struct dmar_domain *domain)
1441 struct device_domain_info *info;
1442 bool has_iotlb_device = false;
1444 assert_spin_locked(&device_domain_lock);
1446 list_for_each_entry(info, &domain->devices, link) {
1447 struct pci_dev *pdev;
1449 if (!info->dev || !dev_is_pci(info->dev))
1452 pdev = to_pci_dev(info->dev);
1453 if (pdev->ats_enabled) {
1454 has_iotlb_device = true;
1459 domain->has_iotlb_device = has_iotlb_device;
1462 static void iommu_enable_dev_iotlb(struct device_domain_info *info)
1464 struct pci_dev *pdev;
1466 assert_spin_locked(&device_domain_lock);
1468 if (!info || !dev_is_pci(info->dev))
1471 pdev = to_pci_dev(info->dev);
1472 /* For IOMMU that supports device IOTLB throttling (DIT), we assign
1473 * PFSID to the invalidation desc of a VF such that IOMMU HW can gauge
1474 * queue depth at PF level. If DIT is not set, PFSID will be treated as
1475 * reserved, which should be set to 0.
1477 if (!ecap_dit(info->iommu->ecap))
1480 struct pci_dev *pf_pdev;
1482 /* pdev will be returned if device is not a vf */
1483 pf_pdev = pci_physfn(pdev);
1484 info->pfsid = PCI_DEVID(pf_pdev->bus->number, pf_pdev->devfn);
1487 #ifdef CONFIG_INTEL_IOMMU_SVM
1488 /* The PCIe spec, in its wisdom, declares that the behaviour of
1489 the device if you enable PASID support after ATS support is
1490 undefined. So always enable PASID support on devices which
1491 have it, even if we can't yet know if we're ever going to
1493 if (info->pasid_supported && !pci_enable_pasid(pdev, info->pasid_supported & ~1))
1494 info->pasid_enabled = 1;
1496 if (info->pri_supported && !pci_reset_pri(pdev) && !pci_enable_pri(pdev, 32))
1497 info->pri_enabled = 1;
1499 if (info->ats_supported && !pci_enable_ats(pdev, VTD_PAGE_SHIFT)) {
1500 info->ats_enabled = 1;
1501 domain_update_iotlb(info->domain);
1502 info->ats_qdep = pci_ats_queue_depth(pdev);
1506 static void iommu_disable_dev_iotlb(struct device_domain_info *info)
1508 struct pci_dev *pdev;
1510 assert_spin_locked(&device_domain_lock);
1512 if (!dev_is_pci(info->dev))
1515 pdev = to_pci_dev(info->dev);
1517 if (info->ats_enabled) {
1518 pci_disable_ats(pdev);
1519 info->ats_enabled = 0;
1520 domain_update_iotlb(info->domain);
1522 #ifdef CONFIG_INTEL_IOMMU_SVM
1523 if (info->pri_enabled) {
1524 pci_disable_pri(pdev);
1525 info->pri_enabled = 0;
1527 if (info->pasid_enabled) {
1528 pci_disable_pasid(pdev);
1529 info->pasid_enabled = 0;
1534 static void iommu_flush_dev_iotlb(struct dmar_domain *domain,
1535 u64 addr, unsigned mask)
1538 unsigned long flags;
1539 struct device_domain_info *info;
1541 if (!domain->has_iotlb_device)
1544 spin_lock_irqsave(&device_domain_lock, flags);
1545 list_for_each_entry(info, &domain->devices, link) {
1546 if (!info->ats_enabled)
1549 sid = info->bus << 8 | info->devfn;
1550 qdep = info->ats_qdep;
1551 qi_flush_dev_iotlb(info->iommu, sid, info->pfsid,
1554 spin_unlock_irqrestore(&device_domain_lock, flags);
1557 static void iommu_flush_iotlb_psi(struct intel_iommu *iommu,
1558 struct dmar_domain *domain,
1559 unsigned long pfn, unsigned int pages,
1562 unsigned int mask = ilog2(__roundup_pow_of_two(pages));
1563 uint64_t addr = (uint64_t)pfn << VTD_PAGE_SHIFT;
1564 u16 did = domain->iommu_did[iommu->seq_id];
1571 * Fallback to domain selective flush if no PSI support or the size is
1573 * PSI requires page size to be 2 ^ x, and the base address is naturally
1574 * aligned to the size
1576 if (!cap_pgsel_inv(iommu->cap) || mask > cap_max_amask_val(iommu->cap))
1577 iommu->flush.flush_iotlb(iommu, did, 0, 0,
1580 iommu->flush.flush_iotlb(iommu, did, addr | ih, mask,
1584 * In caching mode, changes of pages from non-present to present require
1585 * flush. However, device IOTLB doesn't need to be flushed in this case.
1587 if (!cap_caching_mode(iommu->cap) || !map)
1588 iommu_flush_dev_iotlb(domain, addr, mask);
1591 /* Notification for newly created mappings */
1592 static inline void __mapping_notify_one(struct intel_iommu *iommu,
1593 struct dmar_domain *domain,
1594 unsigned long pfn, unsigned int pages)
1596 /* It's a non-present to present mapping. Only flush if caching mode */
1597 if (cap_caching_mode(iommu->cap))
1598 iommu_flush_iotlb_psi(iommu, domain, pfn, pages, 0, 1);
1600 iommu_flush_write_buffer(iommu);
1603 static void iommu_flush_iova(struct iova_domain *iovad)
1605 struct dmar_domain *domain;
1608 domain = container_of(iovad, struct dmar_domain, iovad);
1610 for_each_domain_iommu(idx, domain) {
1611 struct intel_iommu *iommu = g_iommus[idx];
1612 u16 did = domain->iommu_did[iommu->seq_id];
1614 iommu->flush.flush_iotlb(iommu, did, 0, 0, DMA_TLB_DSI_FLUSH);
1616 if (!cap_caching_mode(iommu->cap))
1617 iommu_flush_dev_iotlb(get_iommu_domain(iommu, did),
1618 0, MAX_AGAW_PFN_WIDTH);
1622 static void iommu_disable_protect_mem_regions(struct intel_iommu *iommu)
1625 unsigned long flags;
1627 raw_spin_lock_irqsave(&iommu->register_lock, flags);
1628 pmen = readl(iommu->reg + DMAR_PMEN_REG);
1629 pmen &= ~DMA_PMEN_EPM;
1630 writel(pmen, iommu->reg + DMAR_PMEN_REG);
1632 /* wait for the protected region status bit to clear */
1633 IOMMU_WAIT_OP(iommu, DMAR_PMEN_REG,
1634 readl, !(pmen & DMA_PMEN_PRS), pmen);
1636 raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
1639 static void iommu_enable_translation(struct intel_iommu *iommu)
1642 unsigned long flags;
1644 raw_spin_lock_irqsave(&iommu->register_lock, flags);
1645 iommu->gcmd |= DMA_GCMD_TE;
1646 writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
1648 /* Make sure hardware complete it */
1649 IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
1650 readl, (sts & DMA_GSTS_TES), sts);
1652 raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
1655 static void iommu_disable_translation(struct intel_iommu *iommu)
1660 raw_spin_lock_irqsave(&iommu->register_lock, flag);
1661 iommu->gcmd &= ~DMA_GCMD_TE;
1662 writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
1664 /* Make sure hardware complete it */
1665 IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
1666 readl, (!(sts & DMA_GSTS_TES)), sts);
1668 raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1672 static int iommu_init_domains(struct intel_iommu *iommu)
1674 u32 ndomains, nlongs;
1677 ndomains = cap_ndoms(iommu->cap);
1678 pr_debug("%s: Number of Domains supported <%d>\n",
1679 iommu->name, ndomains);
1680 nlongs = BITS_TO_LONGS(ndomains);
1682 spin_lock_init(&iommu->lock);
1684 iommu->domain_ids = kcalloc(nlongs, sizeof(unsigned long), GFP_KERNEL);
1685 if (!iommu->domain_ids) {
1686 pr_err("%s: Allocating domain id array failed\n",
1691 size = (ALIGN(ndomains, 256) >> 8) * sizeof(struct dmar_domain **);
1692 iommu->domains = kzalloc(size, GFP_KERNEL);
1694 if (iommu->domains) {
1695 size = 256 * sizeof(struct dmar_domain *);
1696 iommu->domains[0] = kzalloc(size, GFP_KERNEL);
1699 if (!iommu->domains || !iommu->domains[0]) {
1700 pr_err("%s: Allocating domain array failed\n",
1702 kfree(iommu->domain_ids);
1703 kfree(iommu->domains);
1704 iommu->domain_ids = NULL;
1705 iommu->domains = NULL;
1712 * If Caching mode is set, then invalid translations are tagged
1713 * with domain-id 0, hence we need to pre-allocate it. We also
1714 * use domain-id 0 as a marker for non-allocated domain-id, so
1715 * make sure it is not used for a real domain.
1717 set_bit(0, iommu->domain_ids);
1722 static void disable_dmar_iommu(struct intel_iommu *iommu)
1724 struct device_domain_info *info, *tmp;
1725 unsigned long flags;
1727 if (!iommu->domains || !iommu->domain_ids)
1731 spin_lock_irqsave(&device_domain_lock, flags);
1732 list_for_each_entry_safe(info, tmp, &device_domain_list, global) {
1733 struct dmar_domain *domain;
1735 if (info->iommu != iommu)
1738 if (!info->dev || !info->domain)
1741 domain = info->domain;
1743 __dmar_remove_one_dev_info(info);
1745 if (!domain_type_is_vm_or_si(domain)) {
1747 * The domain_exit() function can't be called under
1748 * device_domain_lock, as it takes this lock itself.
1749 * So release the lock here and re-run the loop
1752 spin_unlock_irqrestore(&device_domain_lock, flags);
1753 domain_exit(domain);
1757 spin_unlock_irqrestore(&device_domain_lock, flags);
1759 if (iommu->gcmd & DMA_GCMD_TE)
1760 iommu_disable_translation(iommu);
1763 static void free_dmar_iommu(struct intel_iommu *iommu)
1765 if ((iommu->domains) && (iommu->domain_ids)) {
1766 int elems = ALIGN(cap_ndoms(iommu->cap), 256) >> 8;
1769 for (i = 0; i < elems; i++)
1770 kfree(iommu->domains[i]);
1771 kfree(iommu->domains);
1772 kfree(iommu->domain_ids);
1773 iommu->domains = NULL;
1774 iommu->domain_ids = NULL;
1777 g_iommus[iommu->seq_id] = NULL;
1779 /* free context mapping */
1780 free_context_table(iommu);
1782 #ifdef CONFIG_INTEL_IOMMU_SVM
1783 if (pasid_enabled(iommu)) {
1784 if (ecap_prs(iommu->ecap))
1785 intel_svm_finish_prq(iommu);
1786 intel_svm_exit(iommu);
1791 static struct dmar_domain *alloc_domain(int flags)
1793 struct dmar_domain *domain;
1795 domain = alloc_domain_mem();
1799 memset(domain, 0, sizeof(*domain));
1801 domain->flags = flags;
1802 domain->has_iotlb_device = false;
1803 INIT_LIST_HEAD(&domain->devices);
1808 /* Must be called with iommu->lock */
1809 static int domain_attach_iommu(struct dmar_domain *domain,
1810 struct intel_iommu *iommu)
1812 unsigned long ndomains;
1815 assert_spin_locked(&device_domain_lock);
1816 assert_spin_locked(&iommu->lock);
1818 domain->iommu_refcnt[iommu->seq_id] += 1;
1819 domain->iommu_count += 1;
1820 if (domain->iommu_refcnt[iommu->seq_id] == 1) {
1821 ndomains = cap_ndoms(iommu->cap);
1822 num = find_first_zero_bit(iommu->domain_ids, ndomains);
1824 if (num >= ndomains) {
1825 pr_err("%s: No free domain ids\n", iommu->name);
1826 domain->iommu_refcnt[iommu->seq_id] -= 1;
1827 domain->iommu_count -= 1;
1831 set_bit(num, iommu->domain_ids);
1832 set_iommu_domain(iommu, num, domain);
1834 domain->iommu_did[iommu->seq_id] = num;
1835 domain->nid = iommu->node;
1837 domain_update_iommu_cap(domain);
1843 static int domain_detach_iommu(struct dmar_domain *domain,
1844 struct intel_iommu *iommu)
1846 int num, count = INT_MAX;
1848 assert_spin_locked(&device_domain_lock);
1849 assert_spin_locked(&iommu->lock);
1851 domain->iommu_refcnt[iommu->seq_id] -= 1;
1852 count = --domain->iommu_count;
1853 if (domain->iommu_refcnt[iommu->seq_id] == 0) {
1854 num = domain->iommu_did[iommu->seq_id];
1855 clear_bit(num, iommu->domain_ids);
1856 set_iommu_domain(iommu, num, NULL);
1858 domain_update_iommu_cap(domain);
1859 domain->iommu_did[iommu->seq_id] = 0;
1865 static struct iova_domain reserved_iova_list;
1866 static struct lock_class_key reserved_rbtree_key;
1868 static int dmar_init_reserved_ranges(void)
1870 struct pci_dev *pdev = NULL;
1874 init_iova_domain(&reserved_iova_list, VTD_PAGE_SIZE, IOVA_START_PFN);
1876 lockdep_set_class(&reserved_iova_list.iova_rbtree_lock,
1877 &reserved_rbtree_key);
1879 /* IOAPIC ranges shouldn't be accessed by DMA */
1880 iova = reserve_iova(&reserved_iova_list, IOVA_PFN(IOAPIC_RANGE_START),
1881 IOVA_PFN(IOAPIC_RANGE_END));
1883 pr_err("Reserve IOAPIC range failed\n");
1887 /* Reserve all PCI MMIO to avoid peer-to-peer access */
1888 for_each_pci_dev(pdev) {
1891 for (i = 0; i < PCI_NUM_RESOURCES; i++) {
1892 r = &pdev->resource[i];
1893 if (!r->flags || !(r->flags & IORESOURCE_MEM))
1895 iova = reserve_iova(&reserved_iova_list,
1899 pr_err("Reserve iova failed\n");
1907 static void domain_reserve_special_ranges(struct dmar_domain *domain)
1909 copy_reserved_iova(&reserved_iova_list, &domain->iovad);
1912 static inline int guestwidth_to_adjustwidth(int gaw)
1915 int r = (gaw - 12) % 9;
1926 static int domain_init(struct dmar_domain *domain, struct intel_iommu *iommu,
1929 int adjust_width, agaw;
1930 unsigned long sagaw;
1933 init_iova_domain(&domain->iovad, VTD_PAGE_SIZE, IOVA_START_PFN);
1935 err = init_iova_flush_queue(&domain->iovad,
1936 iommu_flush_iova, iova_entry_free);
1940 domain_reserve_special_ranges(domain);
1942 /* calculate AGAW */
1943 if (guest_width > cap_mgaw(iommu->cap))
1944 guest_width = cap_mgaw(iommu->cap);
1945 domain->gaw = guest_width;
1946 adjust_width = guestwidth_to_adjustwidth(guest_width);
1947 agaw = width_to_agaw(adjust_width);
1948 sagaw = cap_sagaw(iommu->cap);
1949 if (!test_bit(agaw, &sagaw)) {
1950 /* hardware doesn't support it, choose a bigger one */
1951 pr_debug("Hardware doesn't support agaw %d\n", agaw);
1952 agaw = find_next_bit(&sagaw, 5, agaw);
1956 domain->agaw = agaw;
1958 if (ecap_coherent(iommu->ecap))
1959 domain->iommu_coherency = 1;
1961 domain->iommu_coherency = 0;
1963 if (ecap_sc_support(iommu->ecap))
1964 domain->iommu_snooping = 1;
1966 domain->iommu_snooping = 0;
1968 if (intel_iommu_superpage)
1969 domain->iommu_superpage = fls(cap_super_page_val(iommu->cap));
1971 domain->iommu_superpage = 0;
1973 domain->nid = iommu->node;
1975 /* always allocate the top pgd */
1976 domain->pgd = (struct dma_pte *)alloc_pgtable_page(domain->nid);
1979 __iommu_flush_cache(iommu, domain->pgd, PAGE_SIZE);
1983 static void domain_exit(struct dmar_domain *domain)
1985 struct page *freelist = NULL;
1987 /* Domain 0 is reserved, so dont process it */
1991 /* Remove associated devices and clear attached or cached domains */
1993 domain_remove_dev_info(domain);
1997 put_iova_domain(&domain->iovad);
1999 freelist = domain_unmap(domain, 0, DOMAIN_MAX_PFN(domain->gaw));
2001 dma_free_pagelist(freelist);
2003 free_domain_mem(domain);
2006 static int domain_context_mapping_one(struct dmar_domain *domain,
2007 struct intel_iommu *iommu,
2010 u16 did = domain->iommu_did[iommu->seq_id];
2011 int translation = CONTEXT_TT_MULTI_LEVEL;
2012 struct device_domain_info *info = NULL;
2013 struct context_entry *context;
2014 unsigned long flags;
2015 struct dma_pte *pgd;
2020 if (hw_pass_through && domain_type_is_si(domain))
2021 translation = CONTEXT_TT_PASS_THROUGH;
2023 pr_debug("Set context mapping for %02x:%02x.%d\n",
2024 bus, PCI_SLOT(devfn), PCI_FUNC(devfn));
2026 BUG_ON(!domain->pgd);
2028 spin_lock_irqsave(&device_domain_lock, flags);
2029 spin_lock(&iommu->lock);
2032 context = iommu_context_addr(iommu, bus, devfn, 1);
2037 if (context_present(context))
2041 * For kdump cases, old valid entries may be cached due to the
2042 * in-flight DMA and copied pgtable, but there is no unmapping
2043 * behaviour for them, thus we need an explicit cache flush for
2044 * the newly-mapped device. For kdump, at this point, the device
2045 * is supposed to finish reset at its driver probe stage, so no
2046 * in-flight DMA will exist, and we don't need to worry anymore
2049 if (context_copied(context)) {
2050 u16 did_old = context_domain_id(context);
2052 if (did_old < cap_ndoms(iommu->cap)) {
2053 iommu->flush.flush_context(iommu, did_old,
2054 (((u16)bus) << 8) | devfn,
2055 DMA_CCMD_MASK_NOBIT,
2056 DMA_CCMD_DEVICE_INVL);
2057 iommu->flush.flush_iotlb(iommu, did_old, 0, 0,
2064 context_clear_entry(context);
2065 context_set_domain_id(context, did);
2068 * Skip top levels of page tables for iommu which has less agaw
2069 * than default. Unnecessary for PT mode.
2071 if (translation != CONTEXT_TT_PASS_THROUGH) {
2072 for (agaw = domain->agaw; agaw != iommu->agaw; agaw--) {
2074 pgd = phys_to_virt(dma_pte_addr(pgd));
2075 if (!dma_pte_present(pgd))
2079 info = iommu_support_dev_iotlb(domain, iommu, bus, devfn);
2080 if (info && info->ats_supported)
2081 translation = CONTEXT_TT_DEV_IOTLB;
2083 translation = CONTEXT_TT_MULTI_LEVEL;
2085 context_set_address_root(context, virt_to_phys(pgd));
2086 context_set_address_width(context, iommu->agaw);
2089 * In pass through mode, AW must be programmed to
2090 * indicate the largest AGAW value supported by
2091 * hardware. And ASR is ignored by hardware.
2093 context_set_address_width(context, iommu->msagaw);
2096 context_set_translation_type(context, translation);
2097 context_set_fault_enable(context);
2098 context_set_present(context);
2099 domain_flush_cache(domain, context, sizeof(*context));
2102 * It's a non-present to present mapping. If hardware doesn't cache
2103 * non-present entry we only need to flush the write-buffer. If the
2104 * _does_ cache non-present entries, then it does so in the special
2105 * domain #0, which we have to flush:
2107 if (cap_caching_mode(iommu->cap)) {
2108 iommu->flush.flush_context(iommu, 0,
2109 (((u16)bus) << 8) | devfn,
2110 DMA_CCMD_MASK_NOBIT,
2111 DMA_CCMD_DEVICE_INVL);
2112 iommu->flush.flush_iotlb(iommu, did, 0, 0, DMA_TLB_DSI_FLUSH);
2114 iommu_flush_write_buffer(iommu);
2116 iommu_enable_dev_iotlb(info);
2121 spin_unlock(&iommu->lock);
2122 spin_unlock_irqrestore(&device_domain_lock, flags);
2127 struct domain_context_mapping_data {
2128 struct dmar_domain *domain;
2129 struct intel_iommu *iommu;
2132 static int domain_context_mapping_cb(struct pci_dev *pdev,
2133 u16 alias, void *opaque)
2135 struct domain_context_mapping_data *data = opaque;
2137 return domain_context_mapping_one(data->domain, data->iommu,
2138 PCI_BUS_NUM(alias), alias & 0xff);
2142 domain_context_mapping(struct dmar_domain *domain, struct device *dev)
2144 struct intel_iommu *iommu;
2146 struct domain_context_mapping_data data;
2148 iommu = device_to_iommu(dev, &bus, &devfn);
2152 if (!dev_is_pci(dev))
2153 return domain_context_mapping_one(domain, iommu, bus, devfn);
2155 data.domain = domain;
2158 return pci_for_each_dma_alias(to_pci_dev(dev),
2159 &domain_context_mapping_cb, &data);
2162 static int domain_context_mapped_cb(struct pci_dev *pdev,
2163 u16 alias, void *opaque)
2165 struct intel_iommu *iommu = opaque;
2167 return !device_context_mapped(iommu, PCI_BUS_NUM(alias), alias & 0xff);
2170 static int domain_context_mapped(struct device *dev)
2172 struct intel_iommu *iommu;
2175 iommu = device_to_iommu(dev, &bus, &devfn);
2179 if (!dev_is_pci(dev))
2180 return device_context_mapped(iommu, bus, devfn);
2182 return !pci_for_each_dma_alias(to_pci_dev(dev),
2183 domain_context_mapped_cb, iommu);
2186 /* Returns a number of VTD pages, but aligned to MM page size */
2187 static inline unsigned long aligned_nrpages(unsigned long host_addr,
2190 host_addr &= ~PAGE_MASK;
2191 return PAGE_ALIGN(host_addr + size) >> VTD_PAGE_SHIFT;
2194 /* Return largest possible superpage level for a given mapping */
2195 static inline int hardware_largepage_caps(struct dmar_domain *domain,
2196 unsigned long iov_pfn,
2197 unsigned long phy_pfn,
2198 unsigned long pages)
2200 int support, level = 1;
2201 unsigned long pfnmerge;
2203 support = domain->iommu_superpage;
2205 /* To use a large page, the virtual *and* physical addresses
2206 must be aligned to 2MiB/1GiB/etc. Lower bits set in either
2207 of them will mean we have to use smaller pages. So just
2208 merge them and check both at once. */
2209 pfnmerge = iov_pfn | phy_pfn;
2211 while (support && !(pfnmerge & ~VTD_STRIDE_MASK)) {
2212 pages >>= VTD_STRIDE_SHIFT;
2215 pfnmerge >>= VTD_STRIDE_SHIFT;
2222 static int __domain_mapping(struct dmar_domain *domain, unsigned long iov_pfn,
2223 struct scatterlist *sg, unsigned long phys_pfn,
2224 unsigned long nr_pages, int prot)
2226 struct dma_pte *first_pte = NULL, *pte = NULL;
2227 phys_addr_t uninitialized_var(pteval);
2228 unsigned long sg_res = 0;
2229 unsigned int largepage_lvl = 0;
2230 unsigned long lvl_pages = 0;
2232 BUG_ON(!domain_pfn_supported(domain, iov_pfn + nr_pages - 1));
2234 if ((prot & (DMA_PTE_READ|DMA_PTE_WRITE)) == 0)
2237 prot &= DMA_PTE_READ | DMA_PTE_WRITE | DMA_PTE_SNP;
2241 pteval = ((phys_addr_t)phys_pfn << VTD_PAGE_SHIFT) | prot;
2244 while (nr_pages > 0) {
2248 unsigned int pgoff = sg->offset & ~PAGE_MASK;
2250 sg_res = aligned_nrpages(sg->offset, sg->length);
2251 sg->dma_address = ((dma_addr_t)iov_pfn << VTD_PAGE_SHIFT) + pgoff;
2252 sg->dma_length = sg->length;
2253 pteval = (sg_phys(sg) - pgoff) | prot;
2254 phys_pfn = pteval >> VTD_PAGE_SHIFT;
2258 largepage_lvl = hardware_largepage_caps(domain, iov_pfn, phys_pfn, sg_res);
2260 first_pte = pte = pfn_to_dma_pte(domain, iov_pfn, &largepage_lvl);
2263 /* It is large page*/
2264 if (largepage_lvl > 1) {
2265 unsigned long nr_superpages, end_pfn;
2267 pteval |= DMA_PTE_LARGE_PAGE;
2268 lvl_pages = lvl_to_nr_pages(largepage_lvl);
2270 nr_superpages = sg_res / lvl_pages;
2271 end_pfn = iov_pfn + nr_superpages * lvl_pages - 1;
2274 * Ensure that old small page tables are
2275 * removed to make room for superpage(s).
2276 * We're adding new large pages, so make sure
2277 * we don't remove their parent tables.
2279 dma_pte_free_pagetable(domain, iov_pfn, end_pfn,
2282 pteval &= ~(uint64_t)DMA_PTE_LARGE_PAGE;
2286 /* We don't need lock here, nobody else
2287 * touches the iova range
2289 tmp = cmpxchg64_local(&pte->val, 0ULL, pteval);
2291 static int dumps = 5;
2292 pr_crit("ERROR: DMA PTE for vPFN 0x%lx already set (to %llx not %llx)\n",
2293 iov_pfn, tmp, (unsigned long long)pteval);
2296 debug_dma_dump_mappings(NULL);
2301 lvl_pages = lvl_to_nr_pages(largepage_lvl);
2303 BUG_ON(nr_pages < lvl_pages);
2304 BUG_ON(sg_res < lvl_pages);
2306 nr_pages -= lvl_pages;
2307 iov_pfn += lvl_pages;
2308 phys_pfn += lvl_pages;
2309 pteval += lvl_pages * VTD_PAGE_SIZE;
2310 sg_res -= lvl_pages;
2312 /* If the next PTE would be the first in a new page, then we
2313 need to flush the cache on the entries we've just written.
2314 And then we'll need to recalculate 'pte', so clear it and
2315 let it get set again in the if (!pte) block above.
2317 If we're done (!nr_pages) we need to flush the cache too.
2319 Also if we've been setting superpages, we may need to
2320 recalculate 'pte' and switch back to smaller pages for the
2321 end of the mapping, if the trailing size is not enough to
2322 use another superpage (i.e. sg_res < lvl_pages). */
2324 if (!nr_pages || first_pte_in_page(pte) ||
2325 (largepage_lvl > 1 && sg_res < lvl_pages)) {
2326 domain_flush_cache(domain, first_pte,
2327 (void *)pte - (void *)first_pte);
2331 if (!sg_res && nr_pages)
2337 static int domain_mapping(struct dmar_domain *domain, unsigned long iov_pfn,
2338 struct scatterlist *sg, unsigned long phys_pfn,
2339 unsigned long nr_pages, int prot)
2342 struct intel_iommu *iommu;
2344 /* Do the real mapping first */
2345 ret = __domain_mapping(domain, iov_pfn, sg, phys_pfn, nr_pages, prot);
2349 /* Notify about the new mapping */
2350 if (domain_type_is_vm(domain)) {
2351 /* VM typed domains can have more than one IOMMUs */
2353 for_each_domain_iommu(iommu_id, domain) {
2354 iommu = g_iommus[iommu_id];
2355 __mapping_notify_one(iommu, domain, iov_pfn, nr_pages);
2358 /* General domains only have one IOMMU */
2359 iommu = domain_get_iommu(domain);
2360 __mapping_notify_one(iommu, domain, iov_pfn, nr_pages);
2366 static inline int domain_sg_mapping(struct dmar_domain *domain, unsigned long iov_pfn,
2367 struct scatterlist *sg, unsigned long nr_pages,
2370 return domain_mapping(domain, iov_pfn, sg, 0, nr_pages, prot);
2373 static inline int domain_pfn_mapping(struct dmar_domain *domain, unsigned long iov_pfn,
2374 unsigned long phys_pfn, unsigned long nr_pages,
2377 return domain_mapping(domain, iov_pfn, NULL, phys_pfn, nr_pages, prot);
2380 static void domain_context_clear_one(struct intel_iommu *iommu, u8 bus, u8 devfn)
2382 unsigned long flags;
2383 struct context_entry *context;
2389 spin_lock_irqsave(&iommu->lock, flags);
2390 context = iommu_context_addr(iommu, bus, devfn, 0);
2392 spin_unlock_irqrestore(&iommu->lock, flags);
2395 did_old = context_domain_id(context);
2396 context_clear_entry(context);
2397 __iommu_flush_cache(iommu, context, sizeof(*context));
2398 spin_unlock_irqrestore(&iommu->lock, flags);
2399 iommu->flush.flush_context(iommu,
2401 (((u16)bus) << 8) | devfn,
2402 DMA_CCMD_MASK_NOBIT,
2403 DMA_CCMD_DEVICE_INVL);
2404 iommu->flush.flush_iotlb(iommu,
2411 static inline void unlink_domain_info(struct device_domain_info *info)
2413 assert_spin_locked(&device_domain_lock);
2414 list_del(&info->link);
2415 list_del(&info->global);
2417 info->dev->archdata.iommu = NULL;
2420 static void domain_remove_dev_info(struct dmar_domain *domain)
2422 struct device_domain_info *info, *tmp;
2423 unsigned long flags;
2425 spin_lock_irqsave(&device_domain_lock, flags);
2426 list_for_each_entry_safe(info, tmp, &domain->devices, link)
2427 __dmar_remove_one_dev_info(info);
2428 spin_unlock_irqrestore(&device_domain_lock, flags);
2433 * Note: we use struct device->archdata.iommu stores the info
2435 static struct dmar_domain *find_domain(struct device *dev)
2437 struct device_domain_info *info;
2439 /* No lock here, assumes no domain exit in normal case */
2440 info = dev->archdata.iommu;
2442 return info->domain;
2446 static inline struct device_domain_info *
2447 dmar_search_domain_by_dev_info(int segment, int bus, int devfn)
2449 struct device_domain_info *info;
2451 list_for_each_entry(info, &device_domain_list, global)
2452 if (info->iommu->segment == segment && info->bus == bus &&
2453 info->devfn == devfn)
2459 static struct dmar_domain *dmar_insert_one_dev_info(struct intel_iommu *iommu,
2462 struct dmar_domain *domain)
2464 struct dmar_domain *found = NULL;
2465 struct device_domain_info *info;
2466 unsigned long flags;
2469 info = alloc_devinfo_mem();
2474 info->devfn = devfn;
2475 info->ats_supported = info->pasid_supported = info->pri_supported = 0;
2476 info->ats_enabled = info->pasid_enabled = info->pri_enabled = 0;
2479 info->domain = domain;
2480 info->iommu = iommu;
2481 info->pasid_table = NULL;
2483 if (dev && dev_is_pci(dev)) {
2484 struct pci_dev *pdev = to_pci_dev(info->dev);
2486 if (!pci_ats_disabled() &&
2487 ecap_dev_iotlb_support(iommu->ecap) &&
2488 pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS) &&
2489 dmar_find_matched_atsr_unit(pdev))
2490 info->ats_supported = 1;
2492 if (ecs_enabled(iommu)) {
2493 if (pasid_enabled(iommu)) {
2494 int features = pci_pasid_features(pdev);
2496 info->pasid_supported = features | 1;
2499 if (info->ats_supported && ecap_prs(iommu->ecap) &&
2500 pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI))
2501 info->pri_supported = 1;
2505 spin_lock_irqsave(&device_domain_lock, flags);
2507 found = find_domain(dev);
2510 struct device_domain_info *info2;
2511 info2 = dmar_search_domain_by_dev_info(iommu->segment, bus, devfn);
2513 found = info2->domain;
2519 spin_unlock_irqrestore(&device_domain_lock, flags);
2520 free_devinfo_mem(info);
2521 /* Caller must free the original domain */
2525 spin_lock(&iommu->lock);
2526 ret = domain_attach_iommu(domain, iommu);
2527 spin_unlock(&iommu->lock);
2530 spin_unlock_irqrestore(&device_domain_lock, flags);
2531 free_devinfo_mem(info);
2535 list_add(&info->link, &domain->devices);
2536 list_add(&info->global, &device_domain_list);
2538 dev->archdata.iommu = info;
2540 if (dev && dev_is_pci(dev) && info->pasid_supported) {
2541 ret = intel_pasid_alloc_table(dev);
2543 pr_warn("No pasid table for %s, pasid disabled\n",
2545 info->pasid_supported = 0;
2548 spin_unlock_irqrestore(&device_domain_lock, flags);
2550 if (dev && domain_context_mapping(domain, dev)) {
2551 pr_err("Domain context map for %s failed\n", dev_name(dev));
2552 dmar_remove_one_dev_info(domain, dev);
2559 static int get_last_alias(struct pci_dev *pdev, u16 alias, void *opaque)
2561 *(u16 *)opaque = alias;
2565 static struct dmar_domain *find_or_alloc_domain(struct device *dev, int gaw)
2567 struct device_domain_info *info = NULL;
2568 struct dmar_domain *domain = NULL;
2569 struct intel_iommu *iommu;
2571 unsigned long flags;
2574 iommu = device_to_iommu(dev, &bus, &devfn);
2578 if (dev_is_pci(dev)) {
2579 struct pci_dev *pdev = to_pci_dev(dev);
2581 pci_for_each_dma_alias(pdev, get_last_alias, &dma_alias);
2583 spin_lock_irqsave(&device_domain_lock, flags);
2584 info = dmar_search_domain_by_dev_info(pci_domain_nr(pdev->bus),
2585 PCI_BUS_NUM(dma_alias),
2588 iommu = info->iommu;
2589 domain = info->domain;
2591 spin_unlock_irqrestore(&device_domain_lock, flags);
2593 /* DMA alias already has a domain, use it */
2598 /* Allocate and initialize new domain for the device */
2599 domain = alloc_domain(0);
2602 if (domain_init(domain, iommu, gaw)) {
2603 domain_exit(domain);
2612 static struct dmar_domain *set_domain_for_dev(struct device *dev,
2613 struct dmar_domain *domain)
2615 struct intel_iommu *iommu;
2616 struct dmar_domain *tmp;
2617 u16 req_id, dma_alias;
2620 iommu = device_to_iommu(dev, &bus, &devfn);
2624 req_id = ((u16)bus << 8) | devfn;
2626 if (dev_is_pci(dev)) {
2627 struct pci_dev *pdev = to_pci_dev(dev);
2629 pci_for_each_dma_alias(pdev, get_last_alias, &dma_alias);
2631 /* register PCI DMA alias device */
2632 if (req_id != dma_alias) {
2633 tmp = dmar_insert_one_dev_info(iommu, PCI_BUS_NUM(dma_alias),
2634 dma_alias & 0xff, NULL, domain);
2636 if (!tmp || tmp != domain)
2641 tmp = dmar_insert_one_dev_info(iommu, bus, devfn, dev, domain);
2642 if (!tmp || tmp != domain)
2648 static struct dmar_domain *get_domain_for_dev(struct device *dev, int gaw)
2650 struct dmar_domain *domain, *tmp;
2652 domain = find_domain(dev);
2656 domain = find_or_alloc_domain(dev, gaw);
2660 tmp = set_domain_for_dev(dev, domain);
2661 if (!tmp || domain != tmp) {
2662 domain_exit(domain);
2671 static int iommu_domain_identity_map(struct dmar_domain *domain,
2672 unsigned long long start,
2673 unsigned long long end)
2675 unsigned long first_vpfn = start >> VTD_PAGE_SHIFT;
2676 unsigned long last_vpfn = end >> VTD_PAGE_SHIFT;
2678 if (!reserve_iova(&domain->iovad, dma_to_mm_pfn(first_vpfn),
2679 dma_to_mm_pfn(last_vpfn))) {
2680 pr_err("Reserving iova failed\n");
2684 pr_debug("Mapping reserved region %llx-%llx\n", start, end);
2686 * RMRR range might have overlap with physical memory range,
2689 dma_pte_clear_range(domain, first_vpfn, last_vpfn);
2691 return __domain_mapping(domain, first_vpfn, NULL,
2692 first_vpfn, last_vpfn - first_vpfn + 1,
2693 DMA_PTE_READ|DMA_PTE_WRITE);
2696 static int domain_prepare_identity_map(struct device *dev,
2697 struct dmar_domain *domain,
2698 unsigned long long start,
2699 unsigned long long end)
2701 /* For _hardware_ passthrough, don't bother. But for software
2702 passthrough, we do it anyway -- it may indicate a memory
2703 range which is reserved in E820, so which didn't get set
2704 up to start with in si_domain */
2705 if (domain == si_domain && hw_pass_through) {
2706 pr_warn("Ignoring identity map for HW passthrough device %s [0x%Lx - 0x%Lx]\n",
2707 dev_name(dev), start, end);
2711 pr_info("Setting identity map for device %s [0x%Lx - 0x%Lx]\n",
2712 dev_name(dev), start, end);
2715 WARN(1, "Your BIOS is broken; RMRR ends before it starts!\n"
2716 "BIOS vendor: %s; Ver: %s; Product Version: %s\n",
2717 dmi_get_system_info(DMI_BIOS_VENDOR),
2718 dmi_get_system_info(DMI_BIOS_VERSION),
2719 dmi_get_system_info(DMI_PRODUCT_VERSION));
2723 if (end >> agaw_to_width(domain->agaw)) {
2724 WARN(1, "Your BIOS is broken; RMRR exceeds permitted address width (%d bits)\n"
2725 "BIOS vendor: %s; Ver: %s; Product Version: %s\n",
2726 agaw_to_width(domain->agaw),
2727 dmi_get_system_info(DMI_BIOS_VENDOR),
2728 dmi_get_system_info(DMI_BIOS_VERSION),
2729 dmi_get_system_info(DMI_PRODUCT_VERSION));
2733 return iommu_domain_identity_map(domain, start, end);
2736 static int iommu_prepare_identity_map(struct device *dev,
2737 unsigned long long start,
2738 unsigned long long end)
2740 struct dmar_domain *domain;
2743 domain = get_domain_for_dev(dev, DEFAULT_DOMAIN_ADDRESS_WIDTH);
2747 ret = domain_prepare_identity_map(dev, domain, start, end);
2749 domain_exit(domain);
2754 static inline int iommu_prepare_rmrr_dev(struct dmar_rmrr_unit *rmrr,
2757 if (dev->archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO)
2759 return iommu_prepare_identity_map(dev, rmrr->base_address,
2763 #ifdef CONFIG_INTEL_IOMMU_FLOPPY_WA
2764 static inline void iommu_prepare_isa(void)
2766 struct pci_dev *pdev;
2769 pdev = pci_get_class(PCI_CLASS_BRIDGE_ISA << 8, NULL);
2773 pr_info("Prepare 0-16MiB unity mapping for LPC\n");
2774 ret = iommu_prepare_identity_map(&pdev->dev, 0, 16*1024*1024 - 1);
2777 pr_err("Failed to create 0-16MiB identity map - floppy might not work\n");
2782 static inline void iommu_prepare_isa(void)
2786 #endif /* !CONFIG_INTEL_IOMMU_FLPY_WA */
2788 static int md_domain_init(struct dmar_domain *domain, int guest_width);
2790 static int __init si_domain_init(int hw)
2794 si_domain = alloc_domain(DOMAIN_FLAG_STATIC_IDENTITY);
2798 if (md_domain_init(si_domain, DEFAULT_DOMAIN_ADDRESS_WIDTH)) {
2799 domain_exit(si_domain);
2803 pr_debug("Identity mapping domain allocated\n");
2808 for_each_online_node(nid) {
2809 unsigned long start_pfn, end_pfn;
2812 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
2813 ret = iommu_domain_identity_map(si_domain,
2814 PFN_PHYS(start_pfn), PFN_PHYS(end_pfn));
2823 static int identity_mapping(struct device *dev)
2825 struct device_domain_info *info;
2827 if (likely(!iommu_identity_mapping))
2830 info = dev->archdata.iommu;
2831 if (info && info != DUMMY_DEVICE_DOMAIN_INFO)
2832 return (info->domain == si_domain);
2837 static int domain_add_dev_info(struct dmar_domain *domain, struct device *dev)
2839 struct dmar_domain *ndomain;
2840 struct intel_iommu *iommu;
2843 iommu = device_to_iommu(dev, &bus, &devfn);
2847 ndomain = dmar_insert_one_dev_info(iommu, bus, devfn, dev, domain);
2848 if (ndomain != domain)
2854 static bool device_has_rmrr(struct device *dev)
2856 struct dmar_rmrr_unit *rmrr;
2861 for_each_rmrr_units(rmrr) {
2863 * Return TRUE if this RMRR contains the device that
2866 for_each_active_dev_scope(rmrr->devices,
2867 rmrr->devices_cnt, i, tmp)
2878 * There are a couple cases where we need to restrict the functionality of
2879 * devices associated with RMRRs. The first is when evaluating a device for
2880 * identity mapping because problems exist when devices are moved in and out
2881 * of domains and their respective RMRR information is lost. This means that
2882 * a device with associated RMRRs will never be in a "passthrough" domain.
2883 * The second is use of the device through the IOMMU API. This interface
2884 * expects to have full control of the IOVA space for the device. We cannot
2885 * satisfy both the requirement that RMRR access is maintained and have an
2886 * unencumbered IOVA space. We also have no ability to quiesce the device's
2887 * use of the RMRR space or even inform the IOMMU API user of the restriction.
2888 * We therefore prevent devices associated with an RMRR from participating in
2889 * the IOMMU API, which eliminates them from device assignment.
2891 * In both cases we assume that PCI USB devices with RMRRs have them largely
2892 * for historical reasons and that the RMRR space is not actively used post
2893 * boot. This exclusion may change if vendors begin to abuse it.
2895 * The same exception is made for graphics devices, with the requirement that
2896 * any use of the RMRR regions will be torn down before assigning the device
2899 static bool device_is_rmrr_locked(struct device *dev)
2901 if (!device_has_rmrr(dev))
2904 if (dev_is_pci(dev)) {
2905 struct pci_dev *pdev = to_pci_dev(dev);
2907 if (IS_USB_DEVICE(pdev) || IS_GFX_DEVICE(pdev))
2914 static int iommu_should_identity_map(struct device *dev, int startup)
2917 if (dev_is_pci(dev)) {
2918 struct pci_dev *pdev = to_pci_dev(dev);
2920 if (device_is_rmrr_locked(dev))
2923 if ((iommu_identity_mapping & IDENTMAP_AZALIA) && IS_AZALIA(pdev))
2926 if ((iommu_identity_mapping & IDENTMAP_GFX) && IS_GFX_DEVICE(pdev))
2929 if (!(iommu_identity_mapping & IDENTMAP_ALL))
2933 * We want to start off with all devices in the 1:1 domain, and
2934 * take them out later if we find they can't access all of memory.
2936 * However, we can't do this for PCI devices behind bridges,
2937 * because all PCI devices behind the same bridge will end up
2938 * with the same source-id on their transactions.
2940 * Practically speaking, we can't change things around for these
2941 * devices at run-time, because we can't be sure there'll be no
2942 * DMA transactions in flight for any of their siblings.
2944 * So PCI devices (unless they're on the root bus) as well as
2945 * their parent PCI-PCI or PCIe-PCI bridges must be left _out_ of
2946 * the 1:1 domain, just in _case_ one of their siblings turns out
2947 * not to be able to map all of memory.
2949 if (!pci_is_pcie(pdev)) {
2950 if (!pci_is_root_bus(pdev->bus))
2952 if (pdev->class >> 8 == PCI_CLASS_BRIDGE_PCI)
2954 } else if (pci_pcie_type(pdev) == PCI_EXP_TYPE_PCI_BRIDGE)
2957 if (device_has_rmrr(dev))
2962 * At boot time, we don't yet know if devices will be 64-bit capable.
2963 * Assume that they will — if they turn out not to be, then we can
2964 * take them out of the 1:1 domain later.
2968 * If the device's dma_mask is less than the system's memory
2969 * size then this is not a candidate for identity mapping.
2971 u64 dma_mask = *dev->dma_mask;
2973 if (dev->coherent_dma_mask &&
2974 dev->coherent_dma_mask < dma_mask)
2975 dma_mask = dev->coherent_dma_mask;
2977 return dma_mask >= dma_get_required_mask(dev);
2983 static int __init dev_prepare_static_identity_mapping(struct device *dev, int hw)
2987 if (!iommu_should_identity_map(dev, 1))
2990 ret = domain_add_dev_info(si_domain, dev);
2992 pr_info("%s identity mapping for device %s\n",
2993 hw ? "Hardware" : "Software", dev_name(dev));
2994 else if (ret == -ENODEV)
2995 /* device not associated with an iommu */
3002 static int __init iommu_prepare_static_identity_mapping(int hw)
3004 struct pci_dev *pdev = NULL;
3005 struct dmar_drhd_unit *drhd;
3006 struct intel_iommu *iommu;
3011 for_each_pci_dev(pdev) {
3012 ret = dev_prepare_static_identity_mapping(&pdev->dev, hw);
3017 for_each_active_iommu(iommu, drhd)
3018 for_each_active_dev_scope(drhd->devices, drhd->devices_cnt, i, dev) {
3019 struct acpi_device_physical_node *pn;
3020 struct acpi_device *adev;
3022 if (dev->bus != &acpi_bus_type)
3025 adev= to_acpi_device(dev);
3026 mutex_lock(&adev->physical_node_lock);
3027 list_for_each_entry(pn, &adev->physical_node_list, node) {
3028 ret = dev_prepare_static_identity_mapping(pn->dev, hw);
3032 mutex_unlock(&adev->physical_node_lock);
3040 static void intel_iommu_init_qi(struct intel_iommu *iommu)
3043 * Start from the sane iommu hardware state.
3044 * If the queued invalidation is already initialized by us
3045 * (for example, while enabling interrupt-remapping) then
3046 * we got the things already rolling from a sane state.
3050 * Clear any previous faults.
3052 dmar_fault(-1, iommu);
3054 * Disable queued invalidation if supported and already enabled
3055 * before OS handover.
3057 dmar_disable_qi(iommu);
3060 if (dmar_enable_qi(iommu)) {
3062 * Queued Invalidate not enabled, use Register Based Invalidate
3064 iommu->flush.flush_context = __iommu_flush_context;
3065 iommu->flush.flush_iotlb = __iommu_flush_iotlb;
3066 pr_info("%s: Using Register based invalidation\n",
3069 iommu->flush.flush_context = qi_flush_context;
3070 iommu->flush.flush_iotlb = qi_flush_iotlb;
3071 pr_info("%s: Using Queued invalidation\n", iommu->name);
3075 static int copy_context_table(struct intel_iommu *iommu,
3076 struct root_entry *old_re,
3077 struct context_entry **tbl,
3080 int tbl_idx, pos = 0, idx, devfn, ret = 0, did;
3081 struct context_entry *new_ce = NULL, ce;
3082 struct context_entry *old_ce = NULL;
3083 struct root_entry re;
3084 phys_addr_t old_ce_phys;
3086 tbl_idx = ext ? bus * 2 : bus;
3087 memcpy(&re, old_re, sizeof(re));
3089 for (devfn = 0; devfn < 256; devfn++) {
3090 /* First calculate the correct index */
3091 idx = (ext ? devfn * 2 : devfn) % 256;
3094 /* First save what we may have and clean up */
3096 tbl[tbl_idx] = new_ce;
3097 __iommu_flush_cache(iommu, new_ce,
3107 old_ce_phys = root_entry_lctp(&re);
3109 old_ce_phys = root_entry_uctp(&re);
3112 if (ext && devfn == 0) {
3113 /* No LCTP, try UCTP */
3122 old_ce = memremap(old_ce_phys, PAGE_SIZE,
3127 new_ce = alloc_pgtable_page(iommu->node);
3134 /* Now copy the context entry */
3135 memcpy(&ce, old_ce + idx, sizeof(ce));
3137 if (!__context_present(&ce))
3140 did = context_domain_id(&ce);
3141 if (did >= 0 && did < cap_ndoms(iommu->cap))
3142 set_bit(did, iommu->domain_ids);
3145 * We need a marker for copied context entries. This
3146 * marker needs to work for the old format as well as
3147 * for extended context entries.
3149 * Bit 67 of the context entry is used. In the old
3150 * format this bit is available to software, in the
3151 * extended format it is the PGE bit, but PGE is ignored
3152 * by HW if PASIDs are disabled (and thus still
3155 * So disable PASIDs first and then mark the entry
3156 * copied. This means that we don't copy PASID
3157 * translations from the old kernel, but this is fine as
3158 * faults there are not fatal.
3160 context_clear_pasid_enable(&ce);
3161 context_set_copied(&ce);
3166 tbl[tbl_idx + pos] = new_ce;
3168 __iommu_flush_cache(iommu, new_ce, VTD_PAGE_SIZE);
3177 static int copy_translation_tables(struct intel_iommu *iommu)
3179 struct context_entry **ctxt_tbls;
3180 struct root_entry *old_rt;
3181 phys_addr_t old_rt_phys;
3182 int ctxt_table_entries;
3183 unsigned long flags;
3188 rtaddr_reg = dmar_readq(iommu->reg + DMAR_RTADDR_REG);
3189 ext = !!(rtaddr_reg & DMA_RTADDR_RTT);
3190 new_ext = !!ecap_ecs(iommu->ecap);
3193 * The RTT bit can only be changed when translation is disabled,
3194 * but disabling translation means to open a window for data
3195 * corruption. So bail out and don't copy anything if we would
3196 * have to change the bit.
3201 old_rt_phys = rtaddr_reg & VTD_PAGE_MASK;
3205 old_rt = memremap(old_rt_phys, PAGE_SIZE, MEMREMAP_WB);
3209 /* This is too big for the stack - allocate it from slab */
3210 ctxt_table_entries = ext ? 512 : 256;
3212 ctxt_tbls = kcalloc(ctxt_table_entries, sizeof(void *), GFP_KERNEL);
3216 for (bus = 0; bus < 256; bus++) {
3217 ret = copy_context_table(iommu, &old_rt[bus],
3218 ctxt_tbls, bus, ext);
3220 pr_err("%s: Failed to copy context table for bus %d\n",
3226 spin_lock_irqsave(&iommu->lock, flags);
3228 /* Context tables are copied, now write them to the root_entry table */
3229 for (bus = 0; bus < 256; bus++) {
3230 int idx = ext ? bus * 2 : bus;
3233 if (ctxt_tbls[idx]) {
3234 val = virt_to_phys(ctxt_tbls[idx]) | 1;
3235 iommu->root_entry[bus].lo = val;
3238 if (!ext || !ctxt_tbls[idx + 1])
3241 val = virt_to_phys(ctxt_tbls[idx + 1]) | 1;
3242 iommu->root_entry[bus].hi = val;
3245 spin_unlock_irqrestore(&iommu->lock, flags);
3249 __iommu_flush_cache(iommu, iommu->root_entry, PAGE_SIZE);
3259 static int __init init_dmars(void)
3261 struct dmar_drhd_unit *drhd;
3262 struct dmar_rmrr_unit *rmrr;
3263 bool copied_tables = false;
3265 struct intel_iommu *iommu;
3271 * initialize and program root entry to not present
3274 for_each_drhd_unit(drhd) {
3276 * lock not needed as this is only incremented in the single
3277 * threaded kernel __init code path all other access are read
3280 if (g_num_of_iommus < DMAR_UNITS_SUPPORTED) {
3284 pr_err_once("Exceeded %d IOMMUs\n", DMAR_UNITS_SUPPORTED);
3287 /* Preallocate enough resources for IOMMU hot-addition */
3288 if (g_num_of_iommus < DMAR_UNITS_SUPPORTED)
3289 g_num_of_iommus = DMAR_UNITS_SUPPORTED;
3291 g_iommus = kcalloc(g_num_of_iommus, sizeof(struct intel_iommu *),
3294 pr_err("Allocating global iommu array failed\n");
3299 for_each_active_iommu(iommu, drhd) {
3301 * Find the max pasid size of all IOMMU's in the system.
3302 * We need to ensure the system pasid table is no bigger
3303 * than the smallest supported.
3305 if (pasid_enabled(iommu)) {
3306 u32 temp = 2 << ecap_pss(iommu->ecap);
3308 intel_pasid_max_id = min_t(u32, temp,
3309 intel_pasid_max_id);
3312 g_iommus[iommu->seq_id] = iommu;
3314 intel_iommu_init_qi(iommu);
3316 ret = iommu_init_domains(iommu);
3320 init_translation_status(iommu);
3322 if (translation_pre_enabled(iommu) && !is_kdump_kernel()) {
3323 iommu_disable_translation(iommu);
3324 clear_translation_pre_enabled(iommu);
3325 pr_warn("Translation was enabled for %s but we are not in kdump mode\n",
3331 * we could share the same root & context tables
3332 * among all IOMMU's. Need to Split it later.
3334 ret = iommu_alloc_root_entry(iommu);
3338 if (translation_pre_enabled(iommu)) {
3339 pr_info("Translation already enabled - trying to copy translation structures\n");
3341 ret = copy_translation_tables(iommu);
3344 * We found the IOMMU with translation
3345 * enabled - but failed to copy over the
3346 * old root-entry table. Try to proceed
3347 * by disabling translation now and
3348 * allocating a clean root-entry table.
3349 * This might cause DMAR faults, but
3350 * probably the dump will still succeed.
3352 pr_err("Failed to copy translation tables from previous kernel for %s\n",
3354 iommu_disable_translation(iommu);
3355 clear_translation_pre_enabled(iommu);
3357 pr_info("Copied translation tables from previous kernel for %s\n",
3359 copied_tables = true;
3363 if (!ecap_pass_through(iommu->ecap))
3364 hw_pass_through = 0;
3365 #ifdef CONFIG_INTEL_IOMMU_SVM
3366 if (pasid_enabled(iommu))
3367 intel_svm_init(iommu);