]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/iommu/intel-iommu.c
Merge remote-tracking branch 'iommu/next'
[karo-tx-linux.git] / drivers / iommu / intel-iommu.c
1 /*
2  * Copyright © 2006-2014 Intel Corporation.
3  *
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.
7  *
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
11  * more details.
12  *
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>
19  */
20
21 #define pr_fmt(fmt)     "DMAR: " fmt
22
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/timer.h>
37 #include <linux/io.h>
38 #include <linux/iova.h>
39 #include <linux/iommu.h>
40 #include <linux/intel-iommu.h>
41 #include <linux/syscore_ops.h>
42 #include <linux/tboot.h>
43 #include <linux/dmi.h>
44 #include <linux/pci-ats.h>
45 #include <linux/memblock.h>
46 #include <linux/dma-contiguous.h>
47 #include <linux/crash_dump.h>
48 #include <asm/irq_remapping.h>
49 #include <asm/cacheflush.h>
50 #include <asm/iommu.h>
51
52 #include "irq_remapping.h"
53
54 #define ROOT_SIZE               VTD_PAGE_SIZE
55 #define CONTEXT_SIZE            VTD_PAGE_SIZE
56
57 #define IS_GFX_DEVICE(pdev) ((pdev->class >> 16) == PCI_BASE_CLASS_DISPLAY)
58 #define IS_USB_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_SERIAL_USB)
59 #define IS_ISA_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_BRIDGE_ISA)
60 #define IS_AZALIA(pdev) ((pdev)->vendor == 0x8086 && (pdev)->device == 0x3a3e)
61
62 #define IOAPIC_RANGE_START      (0xfee00000)
63 #define IOAPIC_RANGE_END        (0xfeefffff)
64 #define IOVA_START_ADDR         (0x1000)
65
66 #define DEFAULT_DOMAIN_ADDRESS_WIDTH 48
67
68 #define MAX_AGAW_WIDTH 64
69 #define MAX_AGAW_PFN_WIDTH      (MAX_AGAW_WIDTH - VTD_PAGE_SHIFT)
70
71 #define __DOMAIN_MAX_PFN(gaw)  ((((uint64_t)1) << (gaw-VTD_PAGE_SHIFT)) - 1)
72 #define __DOMAIN_MAX_ADDR(gaw) ((((uint64_t)1) << gaw) - 1)
73
74 /* We limit DOMAIN_MAX_PFN to fit in an unsigned long, and DOMAIN_MAX_ADDR
75    to match. That way, we can use 'unsigned long' for PFNs with impunity. */
76 #define DOMAIN_MAX_PFN(gaw)     ((unsigned long) min_t(uint64_t, \
77                                 __DOMAIN_MAX_PFN(gaw), (unsigned long)-1))
78 #define DOMAIN_MAX_ADDR(gaw)    (((uint64_t)__DOMAIN_MAX_PFN(gaw)) << VTD_PAGE_SHIFT)
79
80 /* IO virtual address start page frame number */
81 #define IOVA_START_PFN          (1)
82
83 #define IOVA_PFN(addr)          ((addr) >> PAGE_SHIFT)
84 #define DMA_32BIT_PFN           IOVA_PFN(DMA_BIT_MASK(32))
85 #define DMA_64BIT_PFN           IOVA_PFN(DMA_BIT_MASK(64))
86
87 /* page table handling */
88 #define LEVEL_STRIDE            (9)
89 #define LEVEL_MASK              (((u64)1 << LEVEL_STRIDE) - 1)
90
91 /*
92  * This bitmap is used to advertise the page sizes our hardware support
93  * to the IOMMU core, which will then use this information to split
94  * physically contiguous memory regions it is mapping into page sizes
95  * that we support.
96  *
97  * Traditionally the IOMMU core just handed us the mappings directly,
98  * after making sure the size is an order of a 4KiB page and that the
99  * mapping has natural alignment.
100  *
101  * To retain this behavior, we currently advertise that we support
102  * all page sizes that are an order of 4KiB.
103  *
104  * If at some point we'd like to utilize the IOMMU core's new behavior,
105  * we could change this to advertise the real page sizes we support.
106  */
107 #define INTEL_IOMMU_PGSIZES     (~0xFFFUL)
108
109 static inline int agaw_to_level(int agaw)
110 {
111         return agaw + 2;
112 }
113
114 static inline int agaw_to_width(int agaw)
115 {
116         return min_t(int, 30 + agaw * LEVEL_STRIDE, MAX_AGAW_WIDTH);
117 }
118
119 static inline int width_to_agaw(int width)
120 {
121         return DIV_ROUND_UP(width - 30, LEVEL_STRIDE);
122 }
123
124 static inline unsigned int level_to_offset_bits(int level)
125 {
126         return (level - 1) * LEVEL_STRIDE;
127 }
128
129 static inline int pfn_level_offset(unsigned long pfn, int level)
130 {
131         return (pfn >> level_to_offset_bits(level)) & LEVEL_MASK;
132 }
133
134 static inline unsigned long level_mask(int level)
135 {
136         return -1UL << level_to_offset_bits(level);
137 }
138
139 static inline unsigned long level_size(int level)
140 {
141         return 1UL << level_to_offset_bits(level);
142 }
143
144 static inline unsigned long align_to_level(unsigned long pfn, int level)
145 {
146         return (pfn + level_size(level) - 1) & level_mask(level);
147 }
148
149 static inline unsigned long lvl_to_nr_pages(unsigned int lvl)
150 {
151         return  1 << min_t(int, (lvl - 1) * LEVEL_STRIDE, MAX_AGAW_PFN_WIDTH);
152 }
153
154 /* VT-d pages must always be _smaller_ than MM pages. Otherwise things
155    are never going to work. */
156 static inline unsigned long dma_to_mm_pfn(unsigned long dma_pfn)
157 {
158         return dma_pfn >> (PAGE_SHIFT - VTD_PAGE_SHIFT);
159 }
160
161 static inline unsigned long mm_to_dma_pfn(unsigned long mm_pfn)
162 {
163         return mm_pfn << (PAGE_SHIFT - VTD_PAGE_SHIFT);
164 }
165 static inline unsigned long page_to_dma_pfn(struct page *pg)
166 {
167         return mm_to_dma_pfn(page_to_pfn(pg));
168 }
169 static inline unsigned long virt_to_dma_pfn(void *p)
170 {
171         return page_to_dma_pfn(virt_to_page(p));
172 }
173
174 /* global iommu list, set NULL for ignored DMAR units */
175 static struct intel_iommu **g_iommus;
176
177 static void __init check_tylersburg_isoch(void);
178 static int rwbf_quirk;
179
180 /*
181  * set to 1 to panic kernel if can't successfully enable VT-d
182  * (used when kernel is launched w/ TXT)
183  */
184 static int force_on = 0;
185
186 /*
187  * 0: Present
188  * 1-11: Reserved
189  * 12-63: Context Ptr (12 - (haw-1))
190  * 64-127: Reserved
191  */
192 struct root_entry {
193         u64     lo;
194         u64     hi;
195 };
196 #define ROOT_ENTRY_NR (VTD_PAGE_SIZE/sizeof(struct root_entry))
197
198 /*
199  * Take a root_entry and return the Lower Context Table Pointer (LCTP)
200  * if marked present.
201  */
202 static phys_addr_t root_entry_lctp(struct root_entry *re)
203 {
204         if (!(re->lo & 1))
205                 return 0;
206
207         return re->lo & VTD_PAGE_MASK;
208 }
209
210 /*
211  * Take a root_entry and return the Upper Context Table Pointer (UCTP)
212  * if marked present.
213  */
214 static phys_addr_t root_entry_uctp(struct root_entry *re)
215 {
216         if (!(re->hi & 1))
217                 return 0;
218
219         return re->hi & VTD_PAGE_MASK;
220 }
221 /*
222  * low 64 bits:
223  * 0: present
224  * 1: fault processing disable
225  * 2-3: translation type
226  * 12-63: address space root
227  * high 64 bits:
228  * 0-2: address width
229  * 3-6: aval
230  * 8-23: domain id
231  */
232 struct context_entry {
233         u64 lo;
234         u64 hi;
235 };
236
237 static inline void context_clear_pasid_enable(struct context_entry *context)
238 {
239         context->lo &= ~(1ULL << 11);
240 }
241
242 static inline bool context_pasid_enabled(struct context_entry *context)
243 {
244         return !!(context->lo & (1ULL << 11));
245 }
246
247 static inline void context_set_copied(struct context_entry *context)
248 {
249         context->hi |= (1ull << 3);
250 }
251
252 static inline bool context_copied(struct context_entry *context)
253 {
254         return !!(context->hi & (1ULL << 3));
255 }
256
257 static inline bool __context_present(struct context_entry *context)
258 {
259         return (context->lo & 1);
260 }
261
262 static inline bool context_present(struct context_entry *context)
263 {
264         return context_pasid_enabled(context) ?
265              __context_present(context) :
266              __context_present(context) && !context_copied(context);
267 }
268
269 static inline void context_set_present(struct context_entry *context)
270 {
271         context->lo |= 1;
272 }
273
274 static inline void context_set_fault_enable(struct context_entry *context)
275 {
276         context->lo &= (((u64)-1) << 2) | 1;
277 }
278
279 static inline void context_set_translation_type(struct context_entry *context,
280                                                 unsigned long value)
281 {
282         context->lo &= (((u64)-1) << 4) | 3;
283         context->lo |= (value & 3) << 2;
284 }
285
286 static inline void context_set_address_root(struct context_entry *context,
287                                             unsigned long value)
288 {
289         context->lo &= ~VTD_PAGE_MASK;
290         context->lo |= value & VTD_PAGE_MASK;
291 }
292
293 static inline void context_set_address_width(struct context_entry *context,
294                                              unsigned long value)
295 {
296         context->hi |= value & 7;
297 }
298
299 static inline void context_set_domain_id(struct context_entry *context,
300                                          unsigned long value)
301 {
302         context->hi |= (value & ((1 << 16) - 1)) << 8;
303 }
304
305 static inline int context_domain_id(struct context_entry *c)
306 {
307         return((c->hi >> 8) & 0xffff);
308 }
309
310 static inline void context_clear_entry(struct context_entry *context)
311 {
312         context->lo = 0;
313         context->hi = 0;
314 }
315
316 /*
317  * 0: readable
318  * 1: writable
319  * 2-6: reserved
320  * 7: super page
321  * 8-10: available
322  * 11: snoop behavior
323  * 12-63: Host physcial address
324  */
325 struct dma_pte {
326         u64 val;
327 };
328
329 static inline void dma_clear_pte(struct dma_pte *pte)
330 {
331         pte->val = 0;
332 }
333
334 static inline u64 dma_pte_addr(struct dma_pte *pte)
335 {
336 #ifdef CONFIG_64BIT
337         return pte->val & VTD_PAGE_MASK;
338 #else
339         /* Must have a full atomic 64-bit read */
340         return  __cmpxchg64(&pte->val, 0ULL, 0ULL) & VTD_PAGE_MASK;
341 #endif
342 }
343
344 static inline bool dma_pte_present(struct dma_pte *pte)
345 {
346         return (pte->val & 3) != 0;
347 }
348
349 static inline bool dma_pte_superpage(struct dma_pte *pte)
350 {
351         return (pte->val & DMA_PTE_LARGE_PAGE);
352 }
353
354 static inline int first_pte_in_page(struct dma_pte *pte)
355 {
356         return !((unsigned long)pte & ~VTD_PAGE_MASK);
357 }
358
359 /*
360  * This domain is a statically identity mapping domain.
361  *      1. This domain creats a static 1:1 mapping to all usable memory.
362  *      2. It maps to each iommu if successful.
363  *      3. Each iommu mapps to this domain if successful.
364  */
365 static struct dmar_domain *si_domain;
366 static int hw_pass_through = 1;
367
368 /*
369  * Domain represents a virtual machine, more than one devices
370  * across iommus may be owned in one domain, e.g. kvm guest.
371  */
372 #define DOMAIN_FLAG_VIRTUAL_MACHINE     (1 << 0)
373
374 /* si_domain contains mulitple devices */
375 #define DOMAIN_FLAG_STATIC_IDENTITY     (1 << 1)
376
377 #define for_each_domain_iommu(idx, domain)                      \
378         for (idx = 0; idx < g_num_of_iommus; idx++)             \
379                 if (domain->iommu_refcnt[idx])
380
381 struct dmar_domain {
382         int     nid;                    /* node id */
383
384         unsigned        iommu_refcnt[DMAR_UNITS_SUPPORTED];
385                                         /* Refcount of devices per iommu */
386
387
388         u16             iommu_did[DMAR_UNITS_SUPPORTED];
389                                         /* Domain ids per IOMMU. Use u16 since
390                                          * domain ids are 16 bit wide according
391                                          * to VT-d spec, section 9.3 */
392
393         struct list_head devices;       /* all devices' list */
394         struct iova_domain iovad;       /* iova's that belong to this domain */
395
396         struct dma_pte  *pgd;           /* virtual address */
397         int             gaw;            /* max guest address width */
398
399         /* adjusted guest address width, 0 is level 2 30-bit */
400         int             agaw;
401
402         int             flags;          /* flags to find out type of domain */
403
404         int             iommu_coherency;/* indicate coherency of iommu access */
405         int             iommu_snooping; /* indicate snooping control feature*/
406         int             iommu_count;    /* reference count of iommu */
407         int             iommu_superpage;/* Level of superpages supported:
408                                            0 == 4KiB (no superpages), 1 == 2MiB,
409                                            2 == 1GiB, 3 == 512GiB, 4 == 1TiB */
410         u64             max_addr;       /* maximum mapped address */
411
412         struct iommu_domain domain;     /* generic domain data structure for
413                                            iommu core */
414 };
415
416 /* PCI domain-device relationship */
417 struct device_domain_info {
418         struct list_head link;  /* link to domain siblings */
419         struct list_head global; /* link to global list */
420         u8 bus;                 /* PCI bus number */
421         u8 devfn;               /* PCI devfn number */
422         struct {
423                 u8 enabled:1;
424                 u8 qdep;
425         } ats;                  /* ATS state */
426         struct device *dev; /* it's NULL for PCIe-to-PCI bridge */
427         struct intel_iommu *iommu; /* IOMMU used by this device */
428         struct dmar_domain *domain; /* pointer to domain */
429 };
430
431 struct dmar_rmrr_unit {
432         struct list_head list;          /* list of rmrr units   */
433         struct acpi_dmar_header *hdr;   /* ACPI header          */
434         u64     base_address;           /* reserved base address*/
435         u64     end_address;            /* reserved end address */
436         struct dmar_dev_scope *devices; /* target devices */
437         int     devices_cnt;            /* target device count */
438 };
439
440 struct dmar_atsr_unit {
441         struct list_head list;          /* list of ATSR units */
442         struct acpi_dmar_header *hdr;   /* ACPI header */
443         struct dmar_dev_scope *devices; /* target devices */
444         int devices_cnt;                /* target device count */
445         u8 include_all:1;               /* include all ports */
446 };
447
448 static LIST_HEAD(dmar_atsr_units);
449 static LIST_HEAD(dmar_rmrr_units);
450
451 #define for_each_rmrr_units(rmrr) \
452         list_for_each_entry(rmrr, &dmar_rmrr_units, list)
453
454 static void flush_unmaps_timeout(unsigned long data);
455
456 static DEFINE_TIMER(unmap_timer,  flush_unmaps_timeout, 0, 0);
457
458 #define HIGH_WATER_MARK 250
459 struct deferred_flush_tables {
460         int next;
461         struct iova *iova[HIGH_WATER_MARK];
462         struct dmar_domain *domain[HIGH_WATER_MARK];
463         struct page *freelist[HIGH_WATER_MARK];
464 };
465
466 static struct deferred_flush_tables *deferred_flush;
467
468 /* bitmap for indexing intel_iommus */
469 static int g_num_of_iommus;
470
471 static DEFINE_SPINLOCK(async_umap_flush_lock);
472 static LIST_HEAD(unmaps_to_do);
473
474 static int timer_on;
475 static long list_size;
476
477 static void domain_exit(struct dmar_domain *domain);
478 static void domain_remove_dev_info(struct dmar_domain *domain);
479 static void dmar_remove_one_dev_info(struct dmar_domain *domain,
480                                      struct device *dev);
481 static void __dmar_remove_one_dev_info(struct device_domain_info *info);
482 static void domain_context_clear(struct intel_iommu *iommu,
483                                  struct device *dev);
484 static int domain_detach_iommu(struct dmar_domain *domain,
485                                struct intel_iommu *iommu);
486
487 #ifdef CONFIG_INTEL_IOMMU_DEFAULT_ON
488 int dmar_disabled = 0;
489 #else
490 int dmar_disabled = 1;
491 #endif /*CONFIG_INTEL_IOMMU_DEFAULT_ON*/
492
493 int intel_iommu_enabled = 0;
494 EXPORT_SYMBOL_GPL(intel_iommu_enabled);
495
496 static int dmar_map_gfx = 1;
497 static int dmar_forcedac;
498 static int intel_iommu_strict;
499 static int intel_iommu_superpage = 1;
500 static int intel_iommu_ecs = 1;
501
502 /* We only actually use ECS when PASID support (on the new bit 40)
503  * is also advertised. Some early implementations — the ones with
504  * PASID support on bit 28 — have issues even when we *only* use
505  * extended root/context tables. */
506 #define ecs_enabled(iommu) (intel_iommu_ecs && ecap_ecs(iommu->ecap) && \
507                             ecap_pasid(iommu->ecap))
508
509 int intel_iommu_gfx_mapped;
510 EXPORT_SYMBOL_GPL(intel_iommu_gfx_mapped);
511
512 #define DUMMY_DEVICE_DOMAIN_INFO ((struct device_domain_info *)(-1))
513 static DEFINE_SPINLOCK(device_domain_lock);
514 static LIST_HEAD(device_domain_list);
515
516 static const struct iommu_ops intel_iommu_ops;
517
518 static bool translation_pre_enabled(struct intel_iommu *iommu)
519 {
520         return (iommu->flags & VTD_FLAG_TRANS_PRE_ENABLED);
521 }
522
523 static void clear_translation_pre_enabled(struct intel_iommu *iommu)
524 {
525         iommu->flags &= ~VTD_FLAG_TRANS_PRE_ENABLED;
526 }
527
528 static void init_translation_status(struct intel_iommu *iommu)
529 {
530         u32 gsts;
531
532         gsts = readl(iommu->reg + DMAR_GSTS_REG);
533         if (gsts & DMA_GSTS_TES)
534                 iommu->flags |= VTD_FLAG_TRANS_PRE_ENABLED;
535 }
536
537 /* Convert generic 'struct iommu_domain to private struct dmar_domain */
538 static struct dmar_domain *to_dmar_domain(struct iommu_domain *dom)
539 {
540         return container_of(dom, struct dmar_domain, domain);
541 }
542
543 static int __init intel_iommu_setup(char *str)
544 {
545         if (!str)
546                 return -EINVAL;
547         while (*str) {
548                 if (!strncmp(str, "on", 2)) {
549                         dmar_disabled = 0;
550                         pr_info("IOMMU enabled\n");
551                 } else if (!strncmp(str, "off", 3)) {
552                         dmar_disabled = 1;
553                         pr_info("IOMMU disabled\n");
554                 } else if (!strncmp(str, "igfx_off", 8)) {
555                         dmar_map_gfx = 0;
556                         pr_info("Disable GFX device mapping\n");
557                 } else if (!strncmp(str, "forcedac", 8)) {
558                         pr_info("Forcing DAC for PCI devices\n");
559                         dmar_forcedac = 1;
560                 } else if (!strncmp(str, "strict", 6)) {
561                         pr_info("Disable batched IOTLB flush\n");
562                         intel_iommu_strict = 1;
563                 } else if (!strncmp(str, "sp_off", 6)) {
564                         pr_info("Disable supported super page\n");
565                         intel_iommu_superpage = 0;
566                 } else if (!strncmp(str, "ecs_off", 7)) {
567                         printk(KERN_INFO
568                                 "Intel-IOMMU: disable extended context table support\n");
569                         intel_iommu_ecs = 0;
570                 }
571
572                 str += strcspn(str, ",");
573                 while (*str == ',')
574                         str++;
575         }
576         return 0;
577 }
578 __setup("intel_iommu=", intel_iommu_setup);
579
580 static struct kmem_cache *iommu_domain_cache;
581 static struct kmem_cache *iommu_devinfo_cache;
582
583 static struct dmar_domain* get_iommu_domain(struct intel_iommu *iommu, u16 did)
584 {
585         struct dmar_domain **domains;
586         int idx = did >> 8;
587
588         domains = iommu->domains[idx];
589         if (!domains)
590                 return NULL;
591
592         return domains[did & 0xff];
593 }
594
595 static void set_iommu_domain(struct intel_iommu *iommu, u16 did,
596                              struct dmar_domain *domain)
597 {
598         struct dmar_domain **domains;
599         int idx = did >> 8;
600
601         if (!iommu->domains[idx]) {
602                 size_t size = 256 * sizeof(struct dmar_domain *);
603                 iommu->domains[idx] = kzalloc(size, GFP_ATOMIC);
604         }
605
606         domains = iommu->domains[idx];
607         if (WARN_ON(!domains))
608                 return;
609         else
610                 domains[did & 0xff] = domain;
611 }
612
613 static inline void *alloc_pgtable_page(int node)
614 {
615         struct page *page;
616         void *vaddr = NULL;
617
618         page = alloc_pages_node(node, GFP_ATOMIC | __GFP_ZERO, 0);
619         if (page)
620                 vaddr = page_address(page);
621         return vaddr;
622 }
623
624 static inline void free_pgtable_page(void *vaddr)
625 {
626         free_page((unsigned long)vaddr);
627 }
628
629 static inline void *alloc_domain_mem(void)
630 {
631         return kmem_cache_alloc(iommu_domain_cache, GFP_ATOMIC);
632 }
633
634 static void free_domain_mem(void *vaddr)
635 {
636         kmem_cache_free(iommu_domain_cache, vaddr);
637 }
638
639 static inline void * alloc_devinfo_mem(void)
640 {
641         return kmem_cache_alloc(iommu_devinfo_cache, GFP_ATOMIC);
642 }
643
644 static inline void free_devinfo_mem(void *vaddr)
645 {
646         kmem_cache_free(iommu_devinfo_cache, vaddr);
647 }
648
649 static inline int domain_type_is_vm(struct dmar_domain *domain)
650 {
651         return domain->flags & DOMAIN_FLAG_VIRTUAL_MACHINE;
652 }
653
654 static inline int domain_type_is_si(struct dmar_domain *domain)
655 {
656         return domain->flags & DOMAIN_FLAG_STATIC_IDENTITY;
657 }
658
659 static inline int domain_type_is_vm_or_si(struct dmar_domain *domain)
660 {
661         return domain->flags & (DOMAIN_FLAG_VIRTUAL_MACHINE |
662                                 DOMAIN_FLAG_STATIC_IDENTITY);
663 }
664
665 static inline int domain_pfn_supported(struct dmar_domain *domain,
666                                        unsigned long pfn)
667 {
668         int addr_width = agaw_to_width(domain->agaw) - VTD_PAGE_SHIFT;
669
670         return !(addr_width < BITS_PER_LONG && pfn >> addr_width);
671 }
672
673 static int __iommu_calculate_agaw(struct intel_iommu *iommu, int max_gaw)
674 {
675         unsigned long sagaw;
676         int agaw = -1;
677
678         sagaw = cap_sagaw(iommu->cap);
679         for (agaw = width_to_agaw(max_gaw);
680              agaw >= 0; agaw--) {
681                 if (test_bit(agaw, &sagaw))
682                         break;
683         }
684
685         return agaw;
686 }
687
688 /*
689  * Calculate max SAGAW for each iommu.
690  */
691 int iommu_calculate_max_sagaw(struct intel_iommu *iommu)
692 {
693         return __iommu_calculate_agaw(iommu, MAX_AGAW_WIDTH);
694 }
695
696 /*
697  * calculate agaw for each iommu.
698  * "SAGAW" may be different across iommus, use a default agaw, and
699  * get a supported less agaw for iommus that don't support the default agaw.
700  */
701 int iommu_calculate_agaw(struct intel_iommu *iommu)
702 {
703         return __iommu_calculate_agaw(iommu, DEFAULT_DOMAIN_ADDRESS_WIDTH);
704 }
705
706 /* This functionin only returns single iommu in a domain */
707 static struct intel_iommu *domain_get_iommu(struct dmar_domain *domain)
708 {
709         int iommu_id;
710
711         /* si_domain and vm domain should not get here. */
712         BUG_ON(domain_type_is_vm_or_si(domain));
713         for_each_domain_iommu(iommu_id, domain)
714                 break;
715
716         if (iommu_id < 0 || iommu_id >= g_num_of_iommus)
717                 return NULL;
718
719         return g_iommus[iommu_id];
720 }
721
722 static void domain_update_iommu_coherency(struct dmar_domain *domain)
723 {
724         struct dmar_drhd_unit *drhd;
725         struct intel_iommu *iommu;
726         bool found = false;
727         int i;
728
729         domain->iommu_coherency = 1;
730
731         for_each_domain_iommu(i, domain) {
732                 found = true;
733                 if (!ecap_coherent(g_iommus[i]->ecap)) {
734                         domain->iommu_coherency = 0;
735                         break;
736                 }
737         }
738         if (found)
739                 return;
740
741         /* No hardware attached; use lowest common denominator */
742         rcu_read_lock();
743         for_each_active_iommu(iommu, drhd) {
744                 if (!ecap_coherent(iommu->ecap)) {
745                         domain->iommu_coherency = 0;
746                         break;
747                 }
748         }
749         rcu_read_unlock();
750 }
751
752 static int domain_update_iommu_snooping(struct intel_iommu *skip)
753 {
754         struct dmar_drhd_unit *drhd;
755         struct intel_iommu *iommu;
756         int ret = 1;
757
758         rcu_read_lock();
759         for_each_active_iommu(iommu, drhd) {
760                 if (iommu != skip) {
761                         if (!ecap_sc_support(iommu->ecap)) {
762                                 ret = 0;
763                                 break;
764                         }
765                 }
766         }
767         rcu_read_unlock();
768
769         return ret;
770 }
771
772 static int domain_update_iommu_superpage(struct intel_iommu *skip)
773 {
774         struct dmar_drhd_unit *drhd;
775         struct intel_iommu *iommu;
776         int mask = 0xf;
777
778         if (!intel_iommu_superpage) {
779                 return 0;
780         }
781
782         /* set iommu_superpage to the smallest common denominator */
783         rcu_read_lock();
784         for_each_active_iommu(iommu, drhd) {
785                 if (iommu != skip) {
786                         mask &= cap_super_page_val(iommu->cap);
787                         if (!mask)
788                                 break;
789                 }
790         }
791         rcu_read_unlock();
792
793         return fls(mask);
794 }
795
796 /* Some capabilities may be different across iommus */
797 static void domain_update_iommu_cap(struct dmar_domain *domain)
798 {
799         domain_update_iommu_coherency(domain);
800         domain->iommu_snooping = domain_update_iommu_snooping(NULL);
801         domain->iommu_superpage = domain_update_iommu_superpage(NULL);
802 }
803
804 static inline struct context_entry *iommu_context_addr(struct intel_iommu *iommu,
805                                                        u8 bus, u8 devfn, int alloc)
806 {
807         struct root_entry *root = &iommu->root_entry[bus];
808         struct context_entry *context;
809         u64 *entry;
810
811         entry = &root->lo;
812         if (ecs_enabled(iommu)) {
813                 if (devfn >= 0x80) {
814                         devfn -= 0x80;
815                         entry = &root->hi;
816                 }
817                 devfn *= 2;
818         }
819         if (*entry & 1)
820                 context = phys_to_virt(*entry & VTD_PAGE_MASK);
821         else {
822                 unsigned long phy_addr;
823                 if (!alloc)
824                         return NULL;
825
826                 context = alloc_pgtable_page(iommu->node);
827                 if (!context)
828                         return NULL;
829
830                 __iommu_flush_cache(iommu, (void *)context, CONTEXT_SIZE);
831                 phy_addr = virt_to_phys((void *)context);
832                 *entry = phy_addr | 1;
833                 __iommu_flush_cache(iommu, entry, sizeof(*entry));
834         }
835         return &context[devfn];
836 }
837
838 static int iommu_dummy(struct device *dev)
839 {
840         return dev->archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO;
841 }
842
843 static struct intel_iommu *device_to_iommu(struct device *dev, u8 *bus, u8 *devfn)
844 {
845         struct dmar_drhd_unit *drhd = NULL;
846         struct intel_iommu *iommu;
847         struct device *tmp;
848         struct pci_dev *ptmp, *pdev = NULL;
849         u16 segment = 0;
850         int i;
851
852         if (iommu_dummy(dev))
853                 return NULL;
854
855         if (dev_is_pci(dev)) {
856                 pdev = to_pci_dev(dev);
857                 segment = pci_domain_nr(pdev->bus);
858         } else if (has_acpi_companion(dev))
859                 dev = &ACPI_COMPANION(dev)->dev;
860
861         rcu_read_lock();
862         for_each_active_iommu(iommu, drhd) {
863                 if (pdev && segment != drhd->segment)
864                         continue;
865
866                 for_each_active_dev_scope(drhd->devices,
867                                           drhd->devices_cnt, i, tmp) {
868                         if (tmp == dev) {
869                                 *bus = drhd->devices[i].bus;
870                                 *devfn = drhd->devices[i].devfn;
871                                 goto out;
872                         }
873
874                         if (!pdev || !dev_is_pci(tmp))
875                                 continue;
876
877                         ptmp = to_pci_dev(tmp);
878                         if (ptmp->subordinate &&
879                             ptmp->subordinate->number <= pdev->bus->number &&
880                             ptmp->subordinate->busn_res.end >= pdev->bus->number)
881                                 goto got_pdev;
882                 }
883
884                 if (pdev && drhd->include_all) {
885                 got_pdev:
886                         *bus = pdev->bus->number;
887                         *devfn = pdev->devfn;
888                         goto out;
889                 }
890         }
891         iommu = NULL;
892  out:
893         rcu_read_unlock();
894
895         return iommu;
896 }
897
898 static void domain_flush_cache(struct dmar_domain *domain,
899                                void *addr, int size)
900 {
901         if (!domain->iommu_coherency)
902                 clflush_cache_range(addr, size);
903 }
904
905 static int device_context_mapped(struct intel_iommu *iommu, u8 bus, u8 devfn)
906 {
907         struct context_entry *context;
908         int ret = 0;
909         unsigned long flags;
910
911         spin_lock_irqsave(&iommu->lock, flags);
912         context = iommu_context_addr(iommu, bus, devfn, 0);
913         if (context)
914                 ret = context_present(context);
915         spin_unlock_irqrestore(&iommu->lock, flags);
916         return ret;
917 }
918
919 static void clear_context_table(struct intel_iommu *iommu, u8 bus, u8 devfn)
920 {
921         struct context_entry *context;
922         unsigned long flags;
923
924         spin_lock_irqsave(&iommu->lock, flags);
925         context = iommu_context_addr(iommu, bus, devfn, 0);
926         if (context) {
927                 context_clear_entry(context);
928                 __iommu_flush_cache(iommu, context, sizeof(*context));
929         }
930         spin_unlock_irqrestore(&iommu->lock, flags);
931 }
932
933 static void free_context_table(struct intel_iommu *iommu)
934 {
935         int i;
936         unsigned long flags;
937         struct context_entry *context;
938
939         spin_lock_irqsave(&iommu->lock, flags);
940         if (!iommu->root_entry) {
941                 goto out;
942         }
943         for (i = 0; i < ROOT_ENTRY_NR; i++) {
944                 context = iommu_context_addr(iommu, i, 0, 0);
945                 if (context)
946                         free_pgtable_page(context);
947
948                 if (!ecs_enabled(iommu))
949                         continue;
950
951                 context = iommu_context_addr(iommu, i, 0x80, 0);
952                 if (context)
953                         free_pgtable_page(context);
954
955         }
956         free_pgtable_page(iommu->root_entry);
957         iommu->root_entry = NULL;
958 out:
959         spin_unlock_irqrestore(&iommu->lock, flags);
960 }
961
962 static struct dma_pte *pfn_to_dma_pte(struct dmar_domain *domain,
963                                       unsigned long pfn, int *target_level)
964 {
965         struct dma_pte *parent, *pte = NULL;
966         int level = agaw_to_level(domain->agaw);
967         int offset;
968
969         BUG_ON(!domain->pgd);
970
971         if (!domain_pfn_supported(domain, pfn))
972                 /* Address beyond IOMMU's addressing capabilities. */
973                 return NULL;
974
975         parent = domain->pgd;
976
977         while (1) {
978                 void *tmp_page;
979
980                 offset = pfn_level_offset(pfn, level);
981                 pte = &parent[offset];
982                 if (!*target_level && (dma_pte_superpage(pte) || !dma_pte_present(pte)))
983                         break;
984                 if (level == *target_level)
985                         break;
986
987                 if (!dma_pte_present(pte)) {
988                         uint64_t pteval;
989
990                         tmp_page = alloc_pgtable_page(domain->nid);
991
992                         if (!tmp_page)
993                                 return NULL;
994
995                         domain_flush_cache(domain, tmp_page, VTD_PAGE_SIZE);
996                         pteval = ((uint64_t)virt_to_dma_pfn(tmp_page) << VTD_PAGE_SHIFT) | DMA_PTE_READ | DMA_PTE_WRITE;
997                         if (cmpxchg64(&pte->val, 0ULL, pteval))
998                                 /* Someone else set it while we were thinking; use theirs. */
999                                 free_pgtable_page(tmp_page);
1000                         else
1001                                 domain_flush_cache(domain, pte, sizeof(*pte));
1002                 }
1003                 if (level == 1)
1004                         break;
1005
1006                 parent = phys_to_virt(dma_pte_addr(pte));
1007                 level--;
1008         }
1009
1010         if (!*target_level)
1011                 *target_level = level;
1012
1013         return pte;
1014 }
1015
1016
1017 /* return address's pte at specific level */
1018 static struct dma_pte *dma_pfn_level_pte(struct dmar_domain *domain,
1019                                          unsigned long pfn,
1020                                          int level, int *large_page)
1021 {
1022         struct dma_pte *parent, *pte = NULL;
1023         int total = agaw_to_level(domain->agaw);
1024         int offset;
1025
1026         parent = domain->pgd;
1027         while (level <= total) {
1028                 offset = pfn_level_offset(pfn, total);
1029                 pte = &parent[offset];
1030                 if (level == total)
1031                         return pte;
1032
1033                 if (!dma_pte_present(pte)) {
1034                         *large_page = total;
1035                         break;
1036                 }
1037
1038                 if (dma_pte_superpage(pte)) {
1039                         *large_page = total;
1040                         return pte;
1041                 }
1042
1043                 parent = phys_to_virt(dma_pte_addr(pte));
1044                 total--;
1045         }
1046         return NULL;
1047 }
1048
1049 /* clear last level pte, a tlb flush should be followed */
1050 static void dma_pte_clear_range(struct dmar_domain *domain,
1051                                 unsigned long start_pfn,
1052                                 unsigned long last_pfn)
1053 {
1054         unsigned int large_page = 1;
1055         struct dma_pte *first_pte, *pte;
1056
1057         BUG_ON(!domain_pfn_supported(domain, start_pfn));
1058         BUG_ON(!domain_pfn_supported(domain, last_pfn));
1059         BUG_ON(start_pfn > last_pfn);
1060
1061         /* we don't need lock here; nobody else touches the iova range */
1062         do {
1063                 large_page = 1;
1064                 first_pte = pte = dma_pfn_level_pte(domain, start_pfn, 1, &large_page);
1065                 if (!pte) {
1066                         start_pfn = align_to_level(start_pfn + 1, large_page + 1);
1067                         continue;
1068                 }
1069                 do {
1070                         dma_clear_pte(pte);
1071                         start_pfn += lvl_to_nr_pages(large_page);
1072                         pte++;
1073                 } while (start_pfn <= last_pfn && !first_pte_in_page(pte));
1074
1075                 domain_flush_cache(domain, first_pte,
1076                                    (void *)pte - (void *)first_pte);
1077
1078         } while (start_pfn && start_pfn <= last_pfn);
1079 }
1080
1081 static void dma_pte_free_level(struct dmar_domain *domain, int level,
1082                                struct dma_pte *pte, unsigned long pfn,
1083                                unsigned long start_pfn, unsigned long last_pfn)
1084 {
1085         pfn = max(start_pfn, pfn);
1086         pte = &pte[pfn_level_offset(pfn, level)];
1087
1088         do {
1089                 unsigned long level_pfn;
1090                 struct dma_pte *level_pte;
1091
1092                 if (!dma_pte_present(pte) || dma_pte_superpage(pte))
1093                         goto next;
1094
1095                 level_pfn = pfn & level_mask(level - 1);
1096                 level_pte = phys_to_virt(dma_pte_addr(pte));
1097
1098                 if (level > 2)
1099                         dma_pte_free_level(domain, level - 1, level_pte,
1100                                            level_pfn, start_pfn, last_pfn);
1101
1102                 /* If range covers entire pagetable, free it */
1103                 if (!(start_pfn > level_pfn ||
1104                       last_pfn < level_pfn + level_size(level) - 1)) {
1105                         dma_clear_pte(pte);
1106                         domain_flush_cache(domain, pte, sizeof(*pte));
1107                         free_pgtable_page(level_pte);
1108                 }
1109 next:
1110                 pfn += level_size(level);
1111         } while (!first_pte_in_page(++pte) && pfn <= last_pfn);
1112 }
1113
1114 /* free page table pages. last level pte should already be cleared */
1115 static void dma_pte_free_pagetable(struct dmar_domain *domain,
1116                                    unsigned long start_pfn,
1117                                    unsigned long last_pfn)
1118 {
1119         BUG_ON(!domain_pfn_supported(domain, start_pfn));
1120         BUG_ON(!domain_pfn_supported(domain, last_pfn));
1121         BUG_ON(start_pfn > last_pfn);
1122
1123         dma_pte_clear_range(domain, start_pfn, last_pfn);
1124
1125         /* We don't need lock here; nobody else touches the iova range */
1126         dma_pte_free_level(domain, agaw_to_level(domain->agaw),
1127                            domain->pgd, 0, start_pfn, last_pfn);
1128
1129         /* free pgd */
1130         if (start_pfn == 0 && last_pfn == DOMAIN_MAX_PFN(domain->gaw)) {
1131                 free_pgtable_page(domain->pgd);
1132                 domain->pgd = NULL;
1133         }
1134 }
1135
1136 /* When a page at a given level is being unlinked from its parent, we don't
1137    need to *modify* it at all. All we need to do is make a list of all the
1138    pages which can be freed just as soon as we've flushed the IOTLB and we
1139    know the hardware page-walk will no longer touch them.
1140    The 'pte' argument is the *parent* PTE, pointing to the page that is to
1141    be freed. */
1142 static struct page *dma_pte_list_pagetables(struct dmar_domain *domain,
1143                                             int level, struct dma_pte *pte,
1144                                             struct page *freelist)
1145 {
1146         struct page *pg;
1147
1148         pg = pfn_to_page(dma_pte_addr(pte) >> PAGE_SHIFT);
1149         pg->freelist = freelist;
1150         freelist = pg;
1151
1152         if (level == 1)
1153                 return freelist;
1154
1155         pte = page_address(pg);
1156         do {
1157                 if (dma_pte_present(pte) && !dma_pte_superpage(pte))
1158                         freelist = dma_pte_list_pagetables(domain, level - 1,
1159                                                            pte, freelist);
1160                 pte++;
1161         } while (!first_pte_in_page(pte));
1162
1163         return freelist;
1164 }
1165
1166 static struct page *dma_pte_clear_level(struct dmar_domain *domain, int level,
1167                                         struct dma_pte *pte, unsigned long pfn,
1168                                         unsigned long start_pfn,
1169                                         unsigned long last_pfn,
1170                                         struct page *freelist)
1171 {
1172         struct dma_pte *first_pte = NULL, *last_pte = NULL;
1173
1174         pfn = max(start_pfn, pfn);
1175         pte = &pte[pfn_level_offset(pfn, level)];
1176
1177         do {
1178                 unsigned long level_pfn;
1179
1180                 if (!dma_pte_present(pte))
1181                         goto next;
1182
1183                 level_pfn = pfn & level_mask(level);
1184
1185                 /* If range covers entire pagetable, free it */
1186                 if (start_pfn <= level_pfn &&
1187                     last_pfn >= level_pfn + level_size(level) - 1) {
1188                         /* These suborbinate page tables are going away entirely. Don't
1189                            bother to clear them; we're just going to *free* them. */
1190                         if (level > 1 && !dma_pte_superpage(pte))
1191                                 freelist = dma_pte_list_pagetables(domain, level - 1, pte, freelist);
1192
1193                         dma_clear_pte(pte);
1194                         if (!first_pte)
1195                                 first_pte = pte;
1196                         last_pte = pte;
1197                 } else if (level > 1) {
1198                         /* Recurse down into a level that isn't *entirely* obsolete */
1199                         freelist = dma_pte_clear_level(domain, level - 1,
1200                                                        phys_to_virt(dma_pte_addr(pte)),
1201                                                        level_pfn, start_pfn, last_pfn,
1202                                                        freelist);
1203                 }
1204 next:
1205                 pfn += level_size(level);
1206         } while (!first_pte_in_page(++pte) && pfn <= last_pfn);
1207
1208         if (first_pte)
1209                 domain_flush_cache(domain, first_pte,
1210                                    (void *)++last_pte - (void *)first_pte);
1211
1212         return freelist;
1213 }
1214
1215 /* We can't just free the pages because the IOMMU may still be walking
1216    the page tables, and may have cached the intermediate levels. The
1217    pages can only be freed after the IOTLB flush has been done. */
1218 static struct page *domain_unmap(struct dmar_domain *domain,
1219                                  unsigned long start_pfn,
1220                                  unsigned long last_pfn)
1221 {
1222         struct page *freelist = NULL;
1223
1224         BUG_ON(!domain_pfn_supported(domain, start_pfn));
1225         BUG_ON(!domain_pfn_supported(domain, last_pfn));
1226         BUG_ON(start_pfn > last_pfn);
1227
1228         /* we don't need lock here; nobody else touches the iova range */
1229         freelist = dma_pte_clear_level(domain, agaw_to_level(domain->agaw),
1230                                        domain->pgd, 0, start_pfn, last_pfn, NULL);
1231
1232         /* free pgd */
1233         if (start_pfn == 0 && last_pfn == DOMAIN_MAX_PFN(domain->gaw)) {
1234                 struct page *pgd_page = virt_to_page(domain->pgd);
1235                 pgd_page->freelist = freelist;
1236                 freelist = pgd_page;
1237
1238                 domain->pgd = NULL;
1239         }
1240
1241         return freelist;
1242 }
1243
1244 static void dma_free_pagelist(struct page *freelist)
1245 {
1246         struct page *pg;
1247
1248         while ((pg = freelist)) {
1249                 freelist = pg->freelist;
1250                 free_pgtable_page(page_address(pg));
1251         }
1252 }
1253
1254 /* iommu handling */
1255 static int iommu_alloc_root_entry(struct intel_iommu *iommu)
1256 {
1257         struct root_entry *root;
1258         unsigned long flags;
1259
1260         root = (struct root_entry *)alloc_pgtable_page(iommu->node);
1261         if (!root) {
1262                 pr_err("Allocating root entry for %s failed\n",
1263                         iommu->name);
1264                 return -ENOMEM;
1265         }
1266
1267         __iommu_flush_cache(iommu, root, ROOT_SIZE);
1268
1269         spin_lock_irqsave(&iommu->lock, flags);
1270         iommu->root_entry = root;
1271         spin_unlock_irqrestore(&iommu->lock, flags);
1272
1273         return 0;
1274 }
1275
1276 static void iommu_set_root_entry(struct intel_iommu *iommu)
1277 {
1278         u64 addr;
1279         u32 sts;
1280         unsigned long flag;
1281
1282         addr = virt_to_phys(iommu->root_entry);
1283         if (ecs_enabled(iommu))
1284                 addr |= DMA_RTADDR_RTT;
1285
1286         raw_spin_lock_irqsave(&iommu->register_lock, flag);
1287         dmar_writeq(iommu->reg + DMAR_RTADDR_REG, addr);
1288
1289         writel(iommu->gcmd | DMA_GCMD_SRTP, iommu->reg + DMAR_GCMD_REG);
1290
1291         /* Make sure hardware complete it */
1292         IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
1293                       readl, (sts & DMA_GSTS_RTPS), sts);
1294
1295         raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1296 }
1297
1298 static void iommu_flush_write_buffer(struct intel_iommu *iommu)
1299 {
1300         u32 val;
1301         unsigned long flag;
1302
1303         if (!rwbf_quirk && !cap_rwbf(iommu->cap))
1304                 return;
1305
1306         raw_spin_lock_irqsave(&iommu->register_lock, flag);
1307         writel(iommu->gcmd | DMA_GCMD_WBF, iommu->reg + DMAR_GCMD_REG);
1308
1309         /* Make sure hardware complete it */
1310         IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
1311                       readl, (!(val & DMA_GSTS_WBFS)), val);
1312
1313         raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1314 }
1315
1316 /* return value determine if we need a write buffer flush */
1317 static void __iommu_flush_context(struct intel_iommu *iommu,
1318                                   u16 did, u16 source_id, u8 function_mask,
1319                                   u64 type)
1320 {
1321         u64 val = 0;
1322         unsigned long flag;
1323
1324         switch (type) {
1325         case DMA_CCMD_GLOBAL_INVL:
1326                 val = DMA_CCMD_GLOBAL_INVL;
1327                 break;
1328         case DMA_CCMD_DOMAIN_INVL:
1329                 val = DMA_CCMD_DOMAIN_INVL|DMA_CCMD_DID(did);
1330                 break;
1331         case DMA_CCMD_DEVICE_INVL:
1332                 val = DMA_CCMD_DEVICE_INVL|DMA_CCMD_DID(did)
1333                         | DMA_CCMD_SID(source_id) | DMA_CCMD_FM(function_mask);
1334                 break;
1335         default:
1336                 BUG();
1337         }
1338         val |= DMA_CCMD_ICC;
1339
1340         raw_spin_lock_irqsave(&iommu->register_lock, flag);
1341         dmar_writeq(iommu->reg + DMAR_CCMD_REG, val);
1342
1343         /* Make sure hardware complete it */
1344         IOMMU_WAIT_OP(iommu, DMAR_CCMD_REG,
1345                 dmar_readq, (!(val & DMA_CCMD_ICC)), val);
1346
1347         raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1348 }
1349
1350 /* return value determine if we need a write buffer flush */
1351 static void __iommu_flush_iotlb(struct intel_iommu *iommu, u16 did,
1352                                 u64 addr, unsigned int size_order, u64 type)
1353 {
1354         int tlb_offset = ecap_iotlb_offset(iommu->ecap);
1355         u64 val = 0, val_iva = 0;
1356         unsigned long flag;
1357
1358         switch (type) {
1359         case DMA_TLB_GLOBAL_FLUSH:
1360                 /* global flush doesn't need set IVA_REG */
1361                 val = DMA_TLB_GLOBAL_FLUSH|DMA_TLB_IVT;
1362                 break;
1363         case DMA_TLB_DSI_FLUSH:
1364                 val = DMA_TLB_DSI_FLUSH|DMA_TLB_IVT|DMA_TLB_DID(did);
1365                 break;
1366         case DMA_TLB_PSI_FLUSH:
1367                 val = DMA_TLB_PSI_FLUSH|DMA_TLB_IVT|DMA_TLB_DID(did);
1368                 /* IH bit is passed in as part of address */
1369                 val_iva = size_order | addr;
1370                 break;
1371         default:
1372                 BUG();
1373         }
1374         /* Note: set drain read/write */
1375 #if 0
1376         /*
1377          * This is probably to be super secure.. Looks like we can
1378          * ignore it without any impact.
1379          */
1380         if (cap_read_drain(iommu->cap))
1381                 val |= DMA_TLB_READ_DRAIN;
1382 #endif
1383         if (cap_write_drain(iommu->cap))
1384                 val |= DMA_TLB_WRITE_DRAIN;
1385
1386         raw_spin_lock_irqsave(&iommu->register_lock, flag);
1387         /* Note: Only uses first TLB reg currently */
1388         if (val_iva)
1389                 dmar_writeq(iommu->reg + tlb_offset, val_iva);
1390         dmar_writeq(iommu->reg + tlb_offset + 8, val);
1391
1392         /* Make sure hardware complete it */
1393         IOMMU_WAIT_OP(iommu, tlb_offset + 8,
1394                 dmar_readq, (!(val & DMA_TLB_IVT)), val);
1395
1396         raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1397
1398         /* check IOTLB invalidation granularity */
1399         if (DMA_TLB_IAIG(val) == 0)
1400                 pr_err("Flush IOTLB failed\n");
1401         if (DMA_TLB_IAIG(val) != DMA_TLB_IIRG(type))
1402                 pr_debug("TLB flush request %Lx, actual %Lx\n",
1403                         (unsigned long long)DMA_TLB_IIRG(type),
1404                         (unsigned long long)DMA_TLB_IAIG(val));
1405 }
1406
1407 static struct device_domain_info *
1408 iommu_support_dev_iotlb (struct dmar_domain *domain, struct intel_iommu *iommu,
1409                          u8 bus, u8 devfn)
1410 {
1411         bool found = false;
1412         struct device_domain_info *info;
1413         struct pci_dev *pdev;
1414
1415         assert_spin_locked(&device_domain_lock);
1416
1417         if (!ecap_dev_iotlb_support(iommu->ecap))
1418                 return NULL;
1419
1420         if (!iommu->qi)
1421                 return NULL;
1422
1423         list_for_each_entry(info, &domain->devices, link)
1424                 if (info->iommu == iommu && info->bus == bus &&
1425                     info->devfn == devfn) {
1426                         found = true;
1427                         break;
1428                 }
1429
1430         if (!found || !info->dev || !dev_is_pci(info->dev))
1431                 return NULL;
1432
1433         pdev = to_pci_dev(info->dev);
1434
1435         if (!pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS))
1436                 return NULL;
1437
1438         if (!dmar_find_matched_atsr_unit(pdev))
1439                 return NULL;
1440
1441         return info;
1442 }
1443
1444 static void iommu_enable_dev_iotlb(struct device_domain_info *info)
1445 {
1446         struct pci_dev *pdev;
1447
1448         if (!info || !dev_is_pci(info->dev))
1449                 return;
1450
1451         pdev = to_pci_dev(info->dev);
1452         if (pci_enable_ats(pdev, VTD_PAGE_SHIFT))
1453                 return;
1454
1455         info->ats.enabled = 1;
1456         info->ats.qdep = pci_ats_queue_depth(pdev);
1457 }
1458
1459 static void iommu_disable_dev_iotlb(struct device_domain_info *info)
1460 {
1461         if (!info->ats.enabled)
1462                 return;
1463
1464         pci_disable_ats(to_pci_dev(info->dev));
1465         info->ats.enabled = 0;
1466 }
1467
1468 static void iommu_flush_dev_iotlb(struct dmar_domain *domain,
1469                                   u64 addr, unsigned mask)
1470 {
1471         u16 sid, qdep;
1472         unsigned long flags;
1473         struct device_domain_info *info;
1474
1475         spin_lock_irqsave(&device_domain_lock, flags);
1476         list_for_each_entry(info, &domain->devices, link) {
1477                 if (!info->ats.enabled)
1478                         continue;
1479
1480                 sid = info->bus << 8 | info->devfn;
1481                 qdep = info->ats.qdep;
1482                 qi_flush_dev_iotlb(info->iommu, sid, qdep, addr, mask);
1483         }
1484         spin_unlock_irqrestore(&device_domain_lock, flags);
1485 }
1486
1487 static void iommu_flush_iotlb_psi(struct intel_iommu *iommu,
1488                                   struct dmar_domain *domain,
1489                                   unsigned long pfn, unsigned int pages,
1490                                   int ih, int map)
1491 {
1492         unsigned int mask = ilog2(__roundup_pow_of_two(pages));
1493         uint64_t addr = (uint64_t)pfn << VTD_PAGE_SHIFT;
1494         u16 did = domain->iommu_did[iommu->seq_id];
1495
1496         BUG_ON(pages == 0);
1497
1498         if (ih)
1499                 ih = 1 << 6;
1500         /*
1501          * Fallback to domain selective flush if no PSI support or the size is
1502          * too big.
1503          * PSI requires page size to be 2 ^ x, and the base address is naturally
1504          * aligned to the size
1505          */
1506         if (!cap_pgsel_inv(iommu->cap) || mask > cap_max_amask_val(iommu->cap))
1507                 iommu->flush.flush_iotlb(iommu, did, 0, 0,
1508                                                 DMA_TLB_DSI_FLUSH);
1509         else
1510                 iommu->flush.flush_iotlb(iommu, did, addr | ih, mask,
1511                                                 DMA_TLB_PSI_FLUSH);
1512
1513         /*
1514          * In caching mode, changes of pages from non-present to present require
1515          * flush. However, device IOTLB doesn't need to be flushed in this case.
1516          */
1517         if (!cap_caching_mode(iommu->cap) || !map)
1518                 iommu_flush_dev_iotlb(get_iommu_domain(iommu, did),
1519                                       addr, mask);
1520 }
1521
1522 static void iommu_disable_protect_mem_regions(struct intel_iommu *iommu)
1523 {
1524         u32 pmen;
1525         unsigned long flags;
1526
1527         raw_spin_lock_irqsave(&iommu->register_lock, flags);
1528         pmen = readl(iommu->reg + DMAR_PMEN_REG);
1529         pmen &= ~DMA_PMEN_EPM;
1530         writel(pmen, iommu->reg + DMAR_PMEN_REG);
1531
1532         /* wait for the protected region status bit to clear */
1533         IOMMU_WAIT_OP(iommu, DMAR_PMEN_REG,
1534                 readl, !(pmen & DMA_PMEN_PRS), pmen);
1535
1536         raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
1537 }
1538
1539 static void iommu_enable_translation(struct intel_iommu *iommu)
1540 {
1541         u32 sts;
1542         unsigned long flags;
1543
1544         raw_spin_lock_irqsave(&iommu->register_lock, flags);
1545         iommu->gcmd |= DMA_GCMD_TE;
1546         writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
1547
1548         /* Make sure hardware complete it */
1549         IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
1550                       readl, (sts & DMA_GSTS_TES), sts);
1551
1552         raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
1553 }
1554
1555 static void iommu_disable_translation(struct intel_iommu *iommu)
1556 {
1557         u32 sts;
1558         unsigned long flag;
1559
1560         raw_spin_lock_irqsave(&iommu->register_lock, flag);
1561         iommu->gcmd &= ~DMA_GCMD_TE;
1562         writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
1563
1564         /* Make sure hardware complete it */
1565         IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
1566                       readl, (!(sts & DMA_GSTS_TES)), sts);
1567
1568         raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1569 }
1570
1571
1572 static int iommu_init_domains(struct intel_iommu *iommu)
1573 {
1574         u32 ndomains, nlongs;
1575         size_t size;
1576
1577         ndomains = cap_ndoms(iommu->cap);
1578         pr_debug("%s: Number of Domains supported <%d>\n",
1579                  iommu->name, ndomains);
1580         nlongs = BITS_TO_LONGS(ndomains);
1581
1582         spin_lock_init(&iommu->lock);
1583
1584         iommu->domain_ids = kcalloc(nlongs, sizeof(unsigned long), GFP_KERNEL);
1585         if (!iommu->domain_ids) {
1586                 pr_err("%s: Allocating domain id array failed\n",
1587                        iommu->name);
1588                 return -ENOMEM;
1589         }
1590
1591         size = ((ndomains >> 8) + 1) * sizeof(struct dmar_domain **);
1592         iommu->domains = kzalloc(size, GFP_KERNEL);
1593
1594         if (iommu->domains) {
1595                 size = 256 * sizeof(struct dmar_domain *);
1596                 iommu->domains[0] = kzalloc(size, GFP_KERNEL);
1597         }
1598
1599         if (!iommu->domains || !iommu->domains[0]) {
1600                 pr_err("%s: Allocating domain array failed\n",
1601                        iommu->name);
1602                 kfree(iommu->domain_ids);
1603                 kfree(iommu->domains);
1604                 iommu->domain_ids = NULL;
1605                 iommu->domains    = NULL;
1606                 return -ENOMEM;
1607         }
1608
1609
1610
1611         /*
1612          * If Caching mode is set, then invalid translations are tagged
1613          * with domain-id 0, hence we need to pre-allocate it. We also
1614          * use domain-id 0 as a marker for non-allocated domain-id, so
1615          * make sure it is not used for a real domain.
1616          */
1617         set_bit(0, iommu->domain_ids);
1618
1619         return 0;
1620 }
1621
1622 static void disable_dmar_iommu(struct intel_iommu *iommu)
1623 {
1624         struct device_domain_info *info, *tmp;
1625         unsigned long flags;
1626
1627         if (!iommu->domains || !iommu->domain_ids)
1628                 return;
1629
1630         spin_lock_irqsave(&device_domain_lock, flags);
1631         list_for_each_entry_safe(info, tmp, &device_domain_list, global) {
1632                 struct dmar_domain *domain;
1633
1634                 if (info->iommu != iommu)
1635                         continue;
1636
1637                 if (!info->dev || !info->domain)
1638                         continue;
1639
1640                 domain = info->domain;
1641
1642                 dmar_remove_one_dev_info(domain, info->dev);
1643
1644                 if (!domain_type_is_vm_or_si(domain))
1645                         domain_exit(domain);
1646         }
1647         spin_unlock_irqrestore(&device_domain_lock, flags);
1648
1649         if (iommu->gcmd & DMA_GCMD_TE)
1650                 iommu_disable_translation(iommu);
1651 }
1652
1653 static void free_dmar_iommu(struct intel_iommu *iommu)
1654 {
1655         if ((iommu->domains) && (iommu->domain_ids)) {
1656                 int elems = (cap_ndoms(iommu->cap) >> 8) + 1;
1657                 int i;
1658
1659                 for (i = 0; i < elems; i++)
1660                         kfree(iommu->domains[i]);
1661                 kfree(iommu->domains);
1662                 kfree(iommu->domain_ids);
1663                 iommu->domains = NULL;
1664                 iommu->domain_ids = NULL;
1665         }
1666
1667         g_iommus[iommu->seq_id] = NULL;
1668
1669         /* free context mapping */
1670         free_context_table(iommu);
1671 }
1672
1673 static struct dmar_domain *alloc_domain(int flags)
1674 {
1675         struct dmar_domain *domain;
1676
1677         domain = alloc_domain_mem();
1678         if (!domain)
1679                 return NULL;
1680
1681         memset(domain, 0, sizeof(*domain));
1682         domain->nid = -1;
1683         domain->flags = flags;
1684         INIT_LIST_HEAD(&domain->devices);
1685
1686         return domain;
1687 }
1688
1689 /* Must be called with iommu->lock */
1690 static int domain_attach_iommu(struct dmar_domain *domain,
1691                                struct intel_iommu *iommu)
1692 {
1693         unsigned long ndomains;
1694         int num;
1695
1696         assert_spin_locked(&device_domain_lock);
1697         assert_spin_locked(&iommu->lock);
1698
1699         domain->iommu_refcnt[iommu->seq_id] += 1;
1700         domain->iommu_count += 1;
1701         if (domain->iommu_refcnt[iommu->seq_id] == 1) {
1702                 ndomains = cap_ndoms(iommu->cap);
1703                 num      = find_first_zero_bit(iommu->domain_ids, ndomains);
1704
1705                 if (num >= ndomains) {
1706                         pr_err("%s: No free domain ids\n", iommu->name);
1707                         domain->iommu_refcnt[iommu->seq_id] -= 1;
1708                         domain->iommu_count -= 1;
1709                         return -ENOSPC;
1710                 }
1711
1712                 set_bit(num, iommu->domain_ids);
1713                 set_iommu_domain(iommu, num, domain);
1714
1715                 domain->iommu_did[iommu->seq_id] = num;
1716                 domain->nid                      = iommu->node;
1717
1718                 domain_update_iommu_cap(domain);
1719         }
1720
1721         return 0;
1722 }
1723
1724 static int domain_detach_iommu(struct dmar_domain *domain,
1725                                struct intel_iommu *iommu)
1726 {
1727         int num, count = INT_MAX;
1728
1729         assert_spin_locked(&device_domain_lock);
1730         assert_spin_locked(&iommu->lock);
1731
1732         domain->iommu_refcnt[iommu->seq_id] -= 1;
1733         count = --domain->iommu_count;
1734         if (domain->iommu_refcnt[iommu->seq_id] == 0) {
1735                 num = domain->iommu_did[iommu->seq_id];
1736                 clear_bit(num, iommu->domain_ids);
1737                 set_iommu_domain(iommu, num, NULL);
1738
1739                 domain_update_iommu_cap(domain);
1740                 domain->iommu_did[iommu->seq_id] = 0;
1741         }
1742
1743         return count;
1744 }
1745
1746 static struct iova_domain reserved_iova_list;
1747 static struct lock_class_key reserved_rbtree_key;
1748
1749 static int dmar_init_reserved_ranges(void)
1750 {
1751         struct pci_dev *pdev = NULL;
1752         struct iova *iova;
1753         int i;
1754
1755         init_iova_domain(&reserved_iova_list, VTD_PAGE_SIZE, IOVA_START_PFN,
1756                         DMA_32BIT_PFN);
1757
1758         lockdep_set_class(&reserved_iova_list.iova_rbtree_lock,
1759                 &reserved_rbtree_key);
1760
1761         /* IOAPIC ranges shouldn't be accessed by DMA */
1762         iova = reserve_iova(&reserved_iova_list, IOVA_PFN(IOAPIC_RANGE_START),
1763                 IOVA_PFN(IOAPIC_RANGE_END));
1764         if (!iova) {
1765                 pr_err("Reserve IOAPIC range failed\n");
1766                 return -ENODEV;
1767         }
1768
1769         /* Reserve all PCI MMIO to avoid peer-to-peer access */
1770         for_each_pci_dev(pdev) {
1771                 struct resource *r;
1772
1773                 for (i = 0; i < PCI_NUM_RESOURCES; i++) {
1774                         r = &pdev->resource[i];
1775                         if (!r->flags || !(r->flags & IORESOURCE_MEM))
1776                                 continue;
1777                         iova = reserve_iova(&reserved_iova_list,
1778                                             IOVA_PFN(r->start),
1779                                             IOVA_PFN(r->end));
1780                         if (!iova) {
1781                                 pr_err("Reserve iova failed\n");
1782                                 return -ENODEV;
1783                         }
1784                 }
1785         }
1786         return 0;
1787 }
1788
1789 static void domain_reserve_special_ranges(struct dmar_domain *domain)
1790 {
1791         copy_reserved_iova(&reserved_iova_list, &domain->iovad);
1792 }
1793
1794 static inline int guestwidth_to_adjustwidth(int gaw)
1795 {
1796         int agaw;
1797         int r = (gaw - 12) % 9;
1798
1799         if (r == 0)
1800                 agaw = gaw;
1801         else
1802                 agaw = gaw + 9 - r;
1803         if (agaw > 64)
1804                 agaw = 64;
1805         return agaw;
1806 }
1807
1808 static int domain_init(struct dmar_domain *domain, struct intel_iommu *iommu,
1809                        int guest_width)
1810 {
1811         int adjust_width, agaw;
1812         unsigned long sagaw;
1813
1814         init_iova_domain(&domain->iovad, VTD_PAGE_SIZE, IOVA_START_PFN,
1815                         DMA_32BIT_PFN);
1816         domain_reserve_special_ranges(domain);
1817
1818         /* calculate AGAW */
1819         if (guest_width > cap_mgaw(iommu->cap))
1820                 guest_width = cap_mgaw(iommu->cap);
1821         domain->gaw = guest_width;
1822         adjust_width = guestwidth_to_adjustwidth(guest_width);
1823         agaw = width_to_agaw(adjust_width);
1824         sagaw = cap_sagaw(iommu->cap);
1825         if (!test_bit(agaw, &sagaw)) {
1826                 /* hardware doesn't support it, choose a bigger one */
1827                 pr_debug("Hardware doesn't support agaw %d\n", agaw);
1828                 agaw = find_next_bit(&sagaw, 5, agaw);
1829                 if (agaw >= 5)
1830                         return -ENODEV;
1831         }
1832         domain->agaw = agaw;
1833
1834         if (ecap_coherent(iommu->ecap))
1835                 domain->iommu_coherency = 1;
1836         else
1837                 domain->iommu_coherency = 0;
1838
1839         if (ecap_sc_support(iommu->ecap))
1840                 domain->iommu_snooping = 1;
1841         else
1842                 domain->iommu_snooping = 0;
1843
1844         if (intel_iommu_superpage)
1845                 domain->iommu_superpage = fls(cap_super_page_val(iommu->cap));
1846         else
1847                 domain->iommu_superpage = 0;
1848
1849         domain->nid = iommu->node;
1850
1851         /* always allocate the top pgd */
1852         domain->pgd = (struct dma_pte *)alloc_pgtable_page(domain->nid);
1853         if (!domain->pgd)
1854                 return -ENOMEM;
1855         __iommu_flush_cache(iommu, domain->pgd, PAGE_SIZE);
1856         return 0;
1857 }
1858
1859 static void domain_exit(struct dmar_domain *domain)
1860 {
1861         struct page *freelist = NULL;
1862
1863         /* Domain 0 is reserved, so dont process it */
1864         if (!domain)
1865                 return;
1866
1867         /* Flush any lazy unmaps that may reference this domain */
1868         if (!intel_iommu_strict)
1869                 flush_unmaps_timeout(0);
1870
1871         /* Remove associated devices and clear attached or cached domains */
1872         rcu_read_lock();
1873         domain_remove_dev_info(domain);
1874         rcu_read_unlock();
1875
1876         /* destroy iovas */
1877         put_iova_domain(&domain->iovad);
1878
1879         freelist = domain_unmap(domain, 0, DOMAIN_MAX_PFN(domain->gaw));
1880
1881         dma_free_pagelist(freelist);
1882
1883         free_domain_mem(domain);
1884 }
1885
1886 static int domain_context_mapping_one(struct dmar_domain *domain,
1887                                       struct intel_iommu *iommu,
1888                                       u8 bus, u8 devfn)
1889 {
1890         u16 did = domain->iommu_did[iommu->seq_id];
1891         int translation = CONTEXT_TT_MULTI_LEVEL;
1892         struct device_domain_info *info = NULL;
1893         struct context_entry *context;
1894         unsigned long flags;
1895         struct dma_pte *pgd;
1896         int ret, agaw;
1897
1898         WARN_ON(did == 0);
1899
1900         if (hw_pass_through && domain_type_is_si(domain))
1901                 translation = CONTEXT_TT_PASS_THROUGH;
1902
1903         pr_debug("Set context mapping for %02x:%02x.%d\n",
1904                 bus, PCI_SLOT(devfn), PCI_FUNC(devfn));
1905
1906         BUG_ON(!domain->pgd);
1907
1908         spin_lock_irqsave(&device_domain_lock, flags);
1909         spin_lock(&iommu->lock);
1910
1911         ret = -ENOMEM;
1912         context = iommu_context_addr(iommu, bus, devfn, 1);
1913         if (!context)
1914                 goto out_unlock;
1915
1916         ret = 0;
1917         if (context_present(context))
1918                 goto out_unlock;
1919
1920         pgd = domain->pgd;
1921
1922         context_clear_entry(context);
1923         context_set_domain_id(context, did);
1924
1925         /*
1926          * Skip top levels of page tables for iommu which has less agaw
1927          * than default.  Unnecessary for PT mode.
1928          */
1929         if (translation != CONTEXT_TT_PASS_THROUGH) {
1930                 for (agaw = domain->agaw; agaw != iommu->agaw; agaw--) {
1931                         ret = -ENOMEM;
1932                         pgd = phys_to_virt(dma_pte_addr(pgd));
1933                         if (!dma_pte_present(pgd))
1934                                 goto out_unlock;
1935                 }
1936
1937                 info = iommu_support_dev_iotlb(domain, iommu, bus, devfn);
1938                 translation = info ? CONTEXT_TT_DEV_IOTLB :
1939                                      CONTEXT_TT_MULTI_LEVEL;
1940
1941                 context_set_address_root(context, virt_to_phys(pgd));
1942                 context_set_address_width(context, iommu->agaw);
1943         } else {
1944                 /*
1945                  * In pass through mode, AW must be programmed to
1946                  * indicate the largest AGAW value supported by
1947                  * hardware. And ASR is ignored by hardware.
1948                  */
1949                 context_set_address_width(context, iommu->msagaw);
1950         }
1951
1952         context_set_translation_type(context, translation);
1953         context_set_fault_enable(context);
1954         context_set_present(context);
1955         domain_flush_cache(domain, context, sizeof(*context));
1956
1957         /*
1958          * It's a non-present to present mapping. If hardware doesn't cache
1959          * non-present entry we only need to flush the write-buffer. If the
1960          * _does_ cache non-present entries, then it does so in the special
1961          * domain #0, which we have to flush:
1962          */
1963         if (cap_caching_mode(iommu->cap)) {
1964                 iommu->flush.flush_context(iommu, 0,
1965                                            (((u16)bus) << 8) | devfn,
1966                                            DMA_CCMD_MASK_NOBIT,
1967                                            DMA_CCMD_DEVICE_INVL);
1968                 iommu->flush.flush_iotlb(iommu, did, 0, 0, DMA_TLB_DSI_FLUSH);
1969         } else {
1970                 iommu_flush_write_buffer(iommu);
1971         }
1972         iommu_enable_dev_iotlb(info);
1973
1974         ret = 0;
1975
1976 out_unlock:
1977         spin_unlock(&iommu->lock);
1978         spin_unlock_irqrestore(&device_domain_lock, flags);
1979
1980         return 0;
1981 }
1982
1983 struct domain_context_mapping_data {
1984         struct dmar_domain *domain;
1985         struct intel_iommu *iommu;
1986 };
1987
1988 static int domain_context_mapping_cb(struct pci_dev *pdev,
1989                                      u16 alias, void *opaque)
1990 {
1991         struct domain_context_mapping_data *data = opaque;
1992
1993         return domain_context_mapping_one(data->domain, data->iommu,
1994                                           PCI_BUS_NUM(alias), alias & 0xff);
1995 }
1996
1997 static int
1998 domain_context_mapping(struct dmar_domain *domain, struct device *dev)
1999 {
2000         struct intel_iommu *iommu;
2001         u8 bus, devfn;
2002         struct domain_context_mapping_data data;
2003
2004         iommu = device_to_iommu(dev, &bus, &devfn);
2005         if (!iommu)
2006                 return -ENODEV;
2007
2008         if (!dev_is_pci(dev))
2009                 return domain_context_mapping_one(domain, iommu, bus, devfn);
2010
2011         data.domain = domain;
2012         data.iommu = iommu;
2013
2014         return pci_for_each_dma_alias(to_pci_dev(dev),
2015                                       &domain_context_mapping_cb, &data);
2016 }
2017
2018 static int domain_context_mapped_cb(struct pci_dev *pdev,
2019                                     u16 alias, void *opaque)
2020 {
2021         struct intel_iommu *iommu = opaque;
2022
2023         return !device_context_mapped(iommu, PCI_BUS_NUM(alias), alias & 0xff);
2024 }
2025
2026 static int domain_context_mapped(struct device *dev)
2027 {
2028         struct intel_iommu *iommu;
2029         u8 bus, devfn;
2030
2031         iommu = device_to_iommu(dev, &bus, &devfn);
2032         if (!iommu)
2033                 return -ENODEV;
2034
2035         if (!dev_is_pci(dev))
2036                 return device_context_mapped(iommu, bus, devfn);
2037
2038         return !pci_for_each_dma_alias(to_pci_dev(dev),
2039                                        domain_context_mapped_cb, iommu);
2040 }
2041
2042 /* Returns a number of VTD pages, but aligned to MM page size */
2043 static inline unsigned long aligned_nrpages(unsigned long host_addr,
2044                                             size_t size)
2045 {
2046         host_addr &= ~PAGE_MASK;
2047         return PAGE_ALIGN(host_addr + size) >> VTD_PAGE_SHIFT;
2048 }
2049
2050 /* Return largest possible superpage level for a given mapping */
2051 static inline int hardware_largepage_caps(struct dmar_domain *domain,
2052                                           unsigned long iov_pfn,
2053                                           unsigned long phy_pfn,
2054                                           unsigned long pages)
2055 {
2056         int support, level = 1;
2057         unsigned long pfnmerge;
2058
2059         support = domain->iommu_superpage;
2060
2061         /* To use a large page, the virtual *and* physical addresses
2062            must be aligned to 2MiB/1GiB/etc. Lower bits set in either
2063            of them will mean we have to use smaller pages. So just
2064            merge them and check both at once. */
2065         pfnmerge = iov_pfn | phy_pfn;
2066
2067         while (support && !(pfnmerge & ~VTD_STRIDE_MASK)) {
2068                 pages >>= VTD_STRIDE_SHIFT;
2069                 if (!pages)
2070                         break;
2071                 pfnmerge >>= VTD_STRIDE_SHIFT;
2072                 level++;
2073                 support--;
2074         }
2075         return level;
2076 }
2077
2078 static int __domain_mapping(struct dmar_domain *domain, unsigned long iov_pfn,
2079                             struct scatterlist *sg, unsigned long phys_pfn,
2080                             unsigned long nr_pages, int prot)
2081 {
2082         struct dma_pte *first_pte = NULL, *pte = NULL;
2083         phys_addr_t uninitialized_var(pteval);
2084         unsigned long sg_res = 0;
2085         unsigned int largepage_lvl = 0;
2086         unsigned long lvl_pages = 0;
2087
2088         BUG_ON(!domain_pfn_supported(domain, iov_pfn + nr_pages - 1));
2089
2090         if ((prot & (DMA_PTE_READ|DMA_PTE_WRITE)) == 0)
2091                 return -EINVAL;
2092
2093         prot &= DMA_PTE_READ | DMA_PTE_WRITE | DMA_PTE_SNP;
2094
2095         if (!sg) {
2096                 sg_res = nr_pages;
2097                 pteval = ((phys_addr_t)phys_pfn << VTD_PAGE_SHIFT) | prot;
2098         }
2099
2100         while (nr_pages > 0) {
2101                 uint64_t tmp;
2102
2103                 if (!sg_res) {
2104                         sg_res = aligned_nrpages(sg->offset, sg->length);
2105                         sg->dma_address = ((dma_addr_t)iov_pfn << VTD_PAGE_SHIFT) + sg->offset;
2106                         sg->dma_length = sg->length;
2107                         pteval = (sg_phys(sg) & PAGE_MASK) | prot;
2108                         phys_pfn = pteval >> VTD_PAGE_SHIFT;
2109                 }
2110
2111                 if (!pte) {
2112                         largepage_lvl = hardware_largepage_caps(domain, iov_pfn, phys_pfn, sg_res);
2113
2114                         first_pte = pte = pfn_to_dma_pte(domain, iov_pfn, &largepage_lvl);
2115                         if (!pte)
2116                                 return -ENOMEM;
2117                         /* It is large page*/
2118                         if (largepage_lvl > 1) {
2119                                 unsigned long nr_superpages, end_pfn;
2120
2121                                 pteval |= DMA_PTE_LARGE_PAGE;
2122                                 lvl_pages = lvl_to_nr_pages(largepage_lvl);
2123
2124                                 nr_superpages = sg_res / lvl_pages;
2125                                 end_pfn = iov_pfn + nr_superpages * lvl_pages - 1;
2126
2127                                 /*
2128                                  * Ensure that old small page tables are
2129                                  * removed to make room for superpage(s).
2130                                  */
2131                                 dma_pte_free_pagetable(domain, iov_pfn, end_pfn);
2132                         } else {
2133                                 pteval &= ~(uint64_t)DMA_PTE_LARGE_PAGE;
2134                         }
2135
2136                 }
2137                 /* We don't need lock here, nobody else
2138                  * touches the iova range
2139                  */
2140                 tmp = cmpxchg64_local(&pte->val, 0ULL, pteval);
2141                 if (tmp) {
2142                         static int dumps = 5;
2143                         pr_crit("ERROR: DMA PTE for vPFN 0x%lx already set (to %llx not %llx)\n",
2144                                 iov_pfn, tmp, (unsigned long long)pteval);
2145                         if (dumps) {
2146                                 dumps--;
2147                                 debug_dma_dump_mappings(NULL);
2148                         }
2149                         WARN_ON(1);
2150                 }
2151
2152                 lvl_pages = lvl_to_nr_pages(largepage_lvl);
2153
2154                 BUG_ON(nr_pages < lvl_pages);
2155                 BUG_ON(sg_res < lvl_pages);
2156
2157                 nr_pages -= lvl_pages;
2158                 iov_pfn += lvl_pages;
2159                 phys_pfn += lvl_pages;
2160                 pteval += lvl_pages * VTD_PAGE_SIZE;
2161                 sg_res -= lvl_pages;
2162
2163                 /* If the next PTE would be the first in a new page, then we
2164                    need to flush the cache on the entries we've just written.
2165                    And then we'll need to recalculate 'pte', so clear it and
2166                    let it get set again in the if (!pte) block above.
2167
2168                    If we're done (!nr_pages) we need to flush the cache too.
2169
2170                    Also if we've been setting superpages, we may need to
2171                    recalculate 'pte' and switch back to smaller pages for the
2172                    end of the mapping, if the trailing size is not enough to
2173                    use another superpage (i.e. sg_res < lvl_pages). */
2174                 pte++;
2175                 if (!nr_pages || first_pte_in_page(pte) ||
2176                     (largepage_lvl > 1 && sg_res < lvl_pages)) {
2177                         domain_flush_cache(domain, first_pte,
2178                                            (void *)pte - (void *)first_pte);
2179                         pte = NULL;
2180                 }
2181
2182                 if (!sg_res && nr_pages)
2183                         sg = sg_next(sg);
2184         }
2185         return 0;
2186 }
2187
2188 static inline int domain_sg_mapping(struct dmar_domain *domain, unsigned long iov_pfn,
2189                                     struct scatterlist *sg, unsigned long nr_pages,
2190                                     int prot)
2191 {
2192         return __domain_mapping(domain, iov_pfn, sg, 0, nr_pages, prot);
2193 }
2194
2195 static inline int domain_pfn_mapping(struct dmar_domain *domain, unsigned long iov_pfn,
2196                                      unsigned long phys_pfn, unsigned long nr_pages,
2197                                      int prot)
2198 {
2199         return __domain_mapping(domain, iov_pfn, NULL, phys_pfn, nr_pages, prot);
2200 }
2201
2202 static void domain_context_clear_one(struct intel_iommu *iommu, u8 bus, u8 devfn)
2203 {
2204         if (!iommu)
2205                 return;
2206
2207         clear_context_table(iommu, bus, devfn);
2208         iommu->flush.flush_context(iommu, 0, 0, 0,
2209                                            DMA_CCMD_GLOBAL_INVL);
2210         iommu->flush.flush_iotlb(iommu, 0, 0, 0, DMA_TLB_GLOBAL_FLUSH);
2211 }
2212
2213 static inline void unlink_domain_info(struct device_domain_info *info)
2214 {
2215         assert_spin_locked(&device_domain_lock);
2216         list_del(&info->link);
2217         list_del(&info->global);
2218         if (info->dev)
2219                 info->dev->archdata.iommu = NULL;
2220 }
2221
2222 static void domain_remove_dev_info(struct dmar_domain *domain)
2223 {
2224         struct device_domain_info *info, *tmp;
2225         unsigned long flags;
2226
2227         spin_lock_irqsave(&device_domain_lock, flags);
2228         list_for_each_entry_safe(info, tmp, &domain->devices, link)
2229                 __dmar_remove_one_dev_info(info);
2230         spin_unlock_irqrestore(&device_domain_lock, flags);
2231 }
2232
2233 /*
2234  * find_domain
2235  * Note: we use struct device->archdata.iommu stores the info
2236  */
2237 static struct dmar_domain *find_domain(struct device *dev)
2238 {
2239         struct device_domain_info *info;
2240
2241         /* No lock here, assumes no domain exit in normal case */
2242         info = dev->archdata.iommu;
2243         if (info)
2244                 return info->domain;
2245         return NULL;
2246 }
2247
2248 static inline struct device_domain_info *
2249 dmar_search_domain_by_dev_info(int segment, int bus, int devfn)
2250 {
2251         struct device_domain_info *info;
2252
2253         list_for_each_entry(info, &device_domain_list, global)
2254                 if (info->iommu->segment == segment && info->bus == bus &&
2255                     info->devfn == devfn)
2256                         return info;
2257
2258         return NULL;
2259 }
2260
2261 static struct dmar_domain *dmar_insert_one_dev_info(struct intel_iommu *iommu,
2262                                                     int bus, int devfn,
2263                                                     struct device *dev,
2264                                                     struct dmar_domain *domain)
2265 {
2266         struct dmar_domain *found = NULL;
2267         struct device_domain_info *info;
2268         unsigned long flags;
2269         int ret;
2270
2271         info = alloc_devinfo_mem();
2272         if (!info)
2273                 return NULL;
2274
2275         info->bus = bus;
2276         info->devfn = devfn;
2277         info->ats.enabled = 0;
2278         info->ats.qdep = 0;
2279         info->dev = dev;
2280         info->domain = domain;
2281         info->iommu = iommu;
2282
2283         spin_lock_irqsave(&device_domain_lock, flags);
2284         if (dev)
2285                 found = find_domain(dev);
2286
2287         if (!found) {
2288                 struct device_domain_info *info2;
2289                 info2 = dmar_search_domain_by_dev_info(iommu->segment, bus, devfn);
2290                 if (info2) {
2291                         found      = info2->domain;
2292                         info2->dev = dev;
2293                 }
2294         }
2295
2296         if (found) {
2297                 spin_unlock_irqrestore(&device_domain_lock, flags);
2298                 free_devinfo_mem(info);
2299                 /* Caller must free the original domain */
2300                 return found;
2301         }
2302
2303         spin_lock(&iommu->lock);
2304         ret = domain_attach_iommu(domain, iommu);
2305         spin_unlock(&iommu->lock);
2306
2307         if (ret) {
2308                 spin_unlock_irqrestore(&device_domain_lock, flags);
2309                 free_devinfo_mem(info);
2310                 return NULL;
2311         }
2312
2313         list_add(&info->link, &domain->devices);
2314         list_add(&info->global, &device_domain_list);
2315         if (dev)
2316                 dev->archdata.iommu = info;
2317         spin_unlock_irqrestore(&device_domain_lock, flags);
2318
2319         if (dev && domain_context_mapping(domain, dev)) {
2320                 pr_err("Domain context map for %s failed\n", dev_name(dev));
2321                 dmar_remove_one_dev_info(domain, dev);
2322                 return NULL;
2323         }
2324
2325         return domain;
2326 }
2327
2328 static int get_last_alias(struct pci_dev *pdev, u16 alias, void *opaque)
2329 {
2330         *(u16 *)opaque = alias;
2331         return 0;
2332 }
2333
2334 /* domain is initialized */
2335 static struct dmar_domain *get_domain_for_dev(struct device *dev, int gaw)
2336 {
2337         struct device_domain_info *info = NULL;
2338         struct dmar_domain *domain, *tmp;
2339         struct intel_iommu *iommu;
2340         u16 req_id, dma_alias;
2341         unsigned long flags;
2342         u8 bus, devfn;
2343
2344         domain = find_domain(dev);
2345         if (domain)
2346                 return domain;
2347
2348         iommu = device_to_iommu(dev, &bus, &devfn);
2349         if (!iommu)
2350                 return NULL;
2351
2352         req_id = ((u16)bus << 8) | devfn;
2353
2354         if (dev_is_pci(dev)) {
2355                 struct pci_dev *pdev = to_pci_dev(dev);
2356
2357                 pci_for_each_dma_alias(pdev, get_last_alias, &dma_alias);
2358
2359                 spin_lock_irqsave(&device_domain_lock, flags);
2360                 info = dmar_search_domain_by_dev_info(pci_domain_nr(pdev->bus),
2361                                                       PCI_BUS_NUM(dma_alias),
2362                                                       dma_alias & 0xff);
2363                 if (info) {
2364                         iommu = info->iommu;
2365                         domain = info->domain;
2366                 }
2367                 spin_unlock_irqrestore(&device_domain_lock, flags);
2368
2369                 /* DMA alias already has a domain, uses it */
2370                 if (info)
2371                         goto found_domain;
2372         }
2373
2374         /* Allocate and initialize new domain for the device */
2375         domain = alloc_domain(0);
2376         if (!domain)
2377                 return NULL;
2378         if (domain_init(domain, iommu, gaw)) {
2379                 domain_exit(domain);
2380                 return NULL;
2381         }
2382
2383         /* register PCI DMA alias device */
2384         if (req_id != dma_alias && dev_is_pci(dev)) {
2385                 tmp = dmar_insert_one_dev_info(iommu, PCI_BUS_NUM(dma_alias),
2386                                                dma_alias & 0xff, NULL, domain);
2387
2388                 if (!tmp || tmp != domain) {
2389                         domain_exit(domain);
2390                         domain = tmp;
2391                 }
2392
2393                 if (!domain)
2394                         return NULL;
2395         }
2396
2397 found_domain:
2398         tmp = dmar_insert_one_dev_info(iommu, bus, devfn, dev, domain);
2399
2400         if (!tmp || tmp != domain) {
2401                 domain_exit(domain);
2402                 domain = tmp;
2403         }
2404
2405         return domain;
2406 }
2407
2408 static int iommu_identity_mapping;
2409 #define IDENTMAP_ALL            1
2410 #define IDENTMAP_GFX            2
2411 #define IDENTMAP_AZALIA         4
2412
2413 static int iommu_domain_identity_map(struct dmar_domain *domain,
2414                                      unsigned long long start,
2415                                      unsigned long long end)
2416 {
2417         unsigned long first_vpfn = start >> VTD_PAGE_SHIFT;
2418         unsigned long last_vpfn = end >> VTD_PAGE_SHIFT;
2419
2420         if (!reserve_iova(&domain->iovad, dma_to_mm_pfn(first_vpfn),
2421                           dma_to_mm_pfn(last_vpfn))) {
2422                 pr_err("Reserving iova failed\n");
2423                 return -ENOMEM;
2424         }
2425
2426         pr_debug("Mapping reserved region %llx-%llx\n", start, end);
2427         /*
2428          * RMRR range might have overlap with physical memory range,
2429          * clear it first
2430          */
2431         dma_pte_clear_range(domain, first_vpfn, last_vpfn);
2432
2433         return domain_pfn_mapping(domain, first_vpfn, first_vpfn,
2434                                   last_vpfn - first_vpfn + 1,
2435                                   DMA_PTE_READ|DMA_PTE_WRITE);
2436 }
2437
2438 static int domain_prepare_identity_map(struct device *dev,
2439                                        struct dmar_domain *domain,
2440                                        unsigned long long start,
2441                                        unsigned long long end)
2442 {
2443         /* For _hardware_ passthrough, don't bother. But for software
2444            passthrough, we do it anyway -- it may indicate a memory
2445            range which is reserved in E820, so which didn't get set
2446            up to start with in si_domain */
2447         if (domain == si_domain && hw_pass_through) {
2448                 pr_warn("Ignoring identity map for HW passthrough device %s [0x%Lx - 0x%Lx]\n",
2449                         dev_name(dev), start, end);
2450                 return 0;
2451         }
2452
2453         pr_info("Setting identity map for device %s [0x%Lx - 0x%Lx]\n",
2454                 dev_name(dev), start, end);
2455
2456         if (end < start) {
2457                 WARN(1, "Your BIOS is broken; RMRR ends before it starts!\n"
2458                         "BIOS vendor: %s; Ver: %s; Product Version: %s\n",
2459                         dmi_get_system_info(DMI_BIOS_VENDOR),
2460                         dmi_get_system_info(DMI_BIOS_VERSION),
2461                      dmi_get_system_info(DMI_PRODUCT_VERSION));
2462                 return -EIO;
2463         }
2464
2465         if (end >> agaw_to_width(domain->agaw)) {
2466                 WARN(1, "Your BIOS is broken; RMRR exceeds permitted address width (%d bits)\n"
2467                      "BIOS vendor: %s; Ver: %s; Product Version: %s\n",
2468                      agaw_to_width(domain->agaw),
2469                      dmi_get_system_info(DMI_BIOS_VENDOR),
2470                      dmi_get_system_info(DMI_BIOS_VERSION),
2471                      dmi_get_system_info(DMI_PRODUCT_VERSION));
2472                 return -EIO;
2473         }
2474
2475         return iommu_domain_identity_map(domain, start, end);
2476 }
2477
2478 static int iommu_prepare_identity_map(struct device *dev,
2479                                       unsigned long long start,
2480                                       unsigned long long end)
2481 {
2482         struct dmar_domain *domain;
2483         int ret;
2484
2485         domain = get_domain_for_dev(dev, DEFAULT_DOMAIN_ADDRESS_WIDTH);
2486         if (!domain)
2487                 return -ENOMEM;
2488
2489         ret = domain_prepare_identity_map(dev, domain, start, end);
2490         if (ret)
2491                 domain_exit(domain);
2492
2493         return ret;
2494 }
2495
2496 static inline int iommu_prepare_rmrr_dev(struct dmar_rmrr_unit *rmrr,
2497                                          struct device *dev)
2498 {
2499         if (dev->archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO)
2500                 return 0;
2501         return iommu_prepare_identity_map(dev, rmrr->base_address,
2502                                           rmrr->end_address);
2503 }
2504
2505 #ifdef CONFIG_INTEL_IOMMU_FLOPPY_WA
2506 static inline void iommu_prepare_isa(void)
2507 {
2508         struct pci_dev *pdev;
2509         int ret;
2510
2511         pdev = pci_get_class(PCI_CLASS_BRIDGE_ISA << 8, NULL);
2512         if (!pdev)
2513                 return;
2514
2515         pr_info("Prepare 0-16MiB unity mapping for LPC\n");
2516         ret = iommu_prepare_identity_map(&pdev->dev, 0, 16*1024*1024 - 1);
2517
2518         if (ret)
2519                 pr_err("Failed to create 0-16MiB identity map - floppy might not work\n");
2520
2521         pci_dev_put(pdev);
2522 }
2523 #else
2524 static inline void iommu_prepare_isa(void)
2525 {
2526         return;
2527 }
2528 #endif /* !CONFIG_INTEL_IOMMU_FLPY_WA */
2529
2530 static int md_domain_init(struct dmar_domain *domain, int guest_width);
2531
2532 static int __init si_domain_init(int hw)
2533 {
2534         int nid, ret = 0;
2535
2536         si_domain = alloc_domain(DOMAIN_FLAG_STATIC_IDENTITY);
2537         if (!si_domain)
2538                 return -EFAULT;
2539
2540         if (md_domain_init(si_domain, DEFAULT_DOMAIN_ADDRESS_WIDTH)) {
2541                 domain_exit(si_domain);
2542                 return -EFAULT;
2543         }
2544
2545         pr_debug("Identity mapping domain allocated\n");
2546
2547         if (hw)
2548                 return 0;
2549
2550         for_each_online_node(nid) {
2551                 unsigned long start_pfn, end_pfn;
2552                 int i;
2553
2554                 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
2555                         ret = iommu_domain_identity_map(si_domain,
2556                                         PFN_PHYS(start_pfn), PFN_PHYS(end_pfn));
2557                         if (ret)
2558                                 return ret;
2559                 }
2560         }
2561
2562         return 0;
2563 }
2564
2565 static int identity_mapping(struct device *dev)
2566 {
2567         struct device_domain_info *info;
2568
2569         if (likely(!iommu_identity_mapping))
2570                 return 0;
2571
2572         info = dev->archdata.iommu;
2573         if (info && info != DUMMY_DEVICE_DOMAIN_INFO)
2574                 return (info->domain == si_domain);
2575
2576         return 0;
2577 }
2578
2579 static int domain_add_dev_info(struct dmar_domain *domain, struct device *dev)
2580 {
2581         struct dmar_domain *ndomain;
2582         struct intel_iommu *iommu;
2583         u8 bus, devfn;
2584
2585         iommu = device_to_iommu(dev, &bus, &devfn);
2586         if (!iommu)
2587                 return -ENODEV;
2588
2589         ndomain = dmar_insert_one_dev_info(iommu, bus, devfn, dev, domain);
2590         if (ndomain != domain)
2591                 return -EBUSY;
2592
2593         return 0;
2594 }
2595
2596 static bool device_has_rmrr(struct device *dev)
2597 {
2598         struct dmar_rmrr_unit *rmrr;
2599         struct device *tmp;
2600         int i;
2601
2602         rcu_read_lock();
2603         for_each_rmrr_units(rmrr) {
2604                 /*
2605                  * Return TRUE if this RMRR contains the device that
2606                  * is passed in.
2607                  */
2608                 for_each_active_dev_scope(rmrr->devices,
2609                                           rmrr->devices_cnt, i, tmp)
2610                         if (tmp == dev) {
2611                                 rcu_read_unlock();
2612                                 return true;
2613                         }
2614         }
2615         rcu_read_unlock();
2616         return false;
2617 }
2618
2619 /*
2620  * There are a couple cases where we need to restrict the functionality of
2621  * devices associated with RMRRs.  The first is when evaluating a device for
2622  * identity mapping because problems exist when devices are moved in and out
2623  * of domains and their respective RMRR information is lost.  This means that
2624  * a device with associated RMRRs will never be in a "passthrough" domain.
2625  * The second is use of the device through the IOMMU API.  This interface
2626  * expects to have full control of the IOVA space for the device.  We cannot
2627  * satisfy both the requirement that RMRR access is maintained and have an
2628  * unencumbered IOVA space.  We also have no ability to quiesce the device's
2629  * use of the RMRR space or even inform the IOMMU API user of the restriction.
2630  * We therefore prevent devices associated with an RMRR from participating in
2631  * the IOMMU API, which eliminates them from device assignment.
2632  *
2633  * In both cases we assume that PCI USB devices with RMRRs have them largely
2634  * for historical reasons and that the RMRR space is not actively used post
2635  * boot.  This exclusion may change if vendors begin to abuse it.
2636  *
2637  * The same exception is made for graphics devices, with the requirement that
2638  * any use of the RMRR regions will be torn down before assigning the device
2639  * to a guest.
2640  */
2641 static bool device_is_rmrr_locked(struct device *dev)
2642 {
2643         if (!device_has_rmrr(dev))
2644                 return false;
2645
2646         if (dev_is_pci(dev)) {
2647                 struct pci_dev *pdev = to_pci_dev(dev);
2648
2649                 if (IS_USB_DEVICE(pdev) || IS_GFX_DEVICE(pdev))
2650                         return false;
2651         }
2652
2653         return true;
2654 }
2655
2656 static int iommu_should_identity_map(struct device *dev, int startup)
2657 {
2658
2659         if (dev_is_pci(dev)) {
2660                 struct pci_dev *pdev = to_pci_dev(dev);
2661
2662                 if (device_is_rmrr_locked(dev))
2663                         return 0;
2664
2665                 if ((iommu_identity_mapping & IDENTMAP_AZALIA) && IS_AZALIA(pdev))
2666                         return 1;
2667
2668                 if ((iommu_identity_mapping & IDENTMAP_GFX) && IS_GFX_DEVICE(pdev))
2669                         return 1;
2670
2671                 if (!(iommu_identity_mapping & IDENTMAP_ALL))
2672                         return 0;
2673
2674                 /*
2675                  * We want to start off with all devices in the 1:1 domain, and
2676                  * take them out later if we find they can't access all of memory.
2677                  *
2678                  * However, we can't do this for PCI devices behind bridges,
2679                  * because all PCI devices behind the same bridge will end up
2680                  * with the same source-id on their transactions.
2681                  *
2682                  * Practically speaking, we can't change things around for these
2683                  * devices at run-time, because we can't be sure there'll be no
2684                  * DMA transactions in flight for any of their siblings.
2685                  *
2686                  * So PCI devices (unless they're on the root bus) as well as
2687                  * their parent PCI-PCI or PCIe-PCI bridges must be left _out_ of
2688                  * the 1:1 domain, just in _case_ one of their siblings turns out
2689                  * not to be able to map all of memory.
2690                  */
2691                 if (!pci_is_pcie(pdev)) {
2692                         if (!pci_is_root_bus(pdev->bus))
2693                                 return 0;
2694                         if (pdev->class >> 8 == PCI_CLASS_BRIDGE_PCI)
2695                                 return 0;
2696                 } else if (pci_pcie_type(pdev) == PCI_EXP_TYPE_PCI_BRIDGE)
2697                         return 0;
2698         } else {
2699                 if (device_has_rmrr(dev))
2700                         return 0;
2701         }
2702
2703         /*
2704          * At boot time, we don't yet know if devices will be 64-bit capable.
2705          * Assume that they will — if they turn out not to be, then we can
2706          * take them out of the 1:1 domain later.
2707          */
2708         if (!startup) {
2709                 /*
2710                  * If the device's dma_mask is less than the system's memory
2711                  * size then this is not a candidate for identity mapping.
2712                  */
2713                 u64 dma_mask = *dev->dma_mask;
2714
2715                 if (dev->coherent_dma_mask &&
2716                     dev->coherent_dma_mask < dma_mask)
2717                         dma_mask = dev->coherent_dma_mask;
2718
2719                 return dma_mask >= dma_get_required_mask(dev);
2720         }
2721
2722         return 1;
2723 }
2724
2725 static int __init dev_prepare_static_identity_mapping(struct device *dev, int hw)
2726 {
2727         int ret;
2728
2729         if (!iommu_should_identity_map(dev, 1))
2730                 return 0;
2731
2732         ret = domain_add_dev_info(si_domain, dev);
2733         if (!ret)
2734                 pr_info("%s identity mapping for device %s\n",
2735                         hw ? "Hardware" : "Software", dev_name(dev));
2736         else if (ret == -ENODEV)
2737                 /* device not associated with an iommu */
2738                 ret = 0;
2739
2740         return ret;
2741 }
2742
2743
2744 static int __init iommu_prepare_static_identity_mapping(int hw)
2745 {
2746         struct pci_dev *pdev = NULL;
2747         struct dmar_drhd_unit *drhd;
2748         struct intel_iommu *iommu;
2749         struct device *dev;
2750         int i;
2751         int ret = 0;
2752
2753         for_each_pci_dev(pdev) {
2754                 ret = dev_prepare_static_identity_mapping(&pdev->dev, hw);
2755                 if (ret)
2756                         return ret;
2757         }
2758
2759         for_each_active_iommu(iommu, drhd)
2760                 for_each_active_dev_scope(drhd->devices, drhd->devices_cnt, i, dev) {
2761                         struct acpi_device_physical_node *pn;
2762                         struct acpi_device *adev;
2763
2764                         if (dev->bus != &acpi_bus_type)
2765                                 continue;
2766
2767                         adev= to_acpi_device(dev);
2768                         mutex_lock(&adev->physical_node_lock);
2769                         list_for_each_entry(pn, &adev->physical_node_list, node) {
2770                                 ret = dev_prepare_static_identity_mapping(pn->dev, hw);
2771                                 if (ret)
2772                                         break;
2773                         }
2774                         mutex_unlock(&adev->physical_node_lock);
2775                         if (ret)
2776                                 return ret;
2777                 }
2778
2779         return 0;
2780 }
2781
2782 static void intel_iommu_init_qi(struct intel_iommu *iommu)
2783 {
2784         /*
2785          * Start from the sane iommu hardware state.
2786          * If the queued invalidation is already initialized by us
2787          * (for example, while enabling interrupt-remapping) then
2788          * we got the things already rolling from a sane state.
2789          */
2790         if (!iommu->qi) {
2791                 /*
2792                  * Clear any previous faults.
2793                  */
2794                 dmar_fault(-1, iommu);
2795                 /*
2796                  * Disable queued invalidation if supported and already enabled
2797                  * before OS handover.
2798                  */
2799                 dmar_disable_qi(iommu);
2800         }
2801
2802         if (dmar_enable_qi(iommu)) {
2803                 /*
2804                  * Queued Invalidate not enabled, use Register Based Invalidate
2805                  */
2806                 iommu->flush.flush_context = __iommu_flush_context;
2807                 iommu->flush.flush_iotlb = __iommu_flush_iotlb;
2808                 pr_info("%s: Using Register based invalidation\n",
2809                         iommu->name);
2810         } else {
2811                 iommu->flush.flush_context = qi_flush_context;
2812                 iommu->flush.flush_iotlb = qi_flush_iotlb;
2813                 pr_info("%s: Using Queued invalidation\n", iommu->name);
2814         }
2815 }
2816
2817 static int copy_context_table(struct intel_iommu *iommu,
2818                               struct root_entry *old_re,
2819                               struct context_entry **tbl,
2820                               int bus, bool ext)
2821 {
2822         int tbl_idx, pos = 0, idx, devfn, ret = 0, did;
2823         struct context_entry *new_ce = NULL, ce;
2824         struct context_entry *old_ce = NULL;
2825         struct root_entry re;
2826         phys_addr_t old_ce_phys;
2827
2828         tbl_idx = ext ? bus * 2 : bus;
2829         memcpy(&re, old_re, sizeof(re));
2830
2831         for (devfn = 0; devfn < 256; devfn++) {
2832                 /* First calculate the correct index */
2833                 idx = (ext ? devfn * 2 : devfn) % 256;
2834
2835                 if (idx == 0) {
2836                         /* First save what we may have and clean up */
2837                         if (new_ce) {
2838                                 tbl[tbl_idx] = new_ce;
2839                                 __iommu_flush_cache(iommu, new_ce,
2840                                                     VTD_PAGE_SIZE);
2841                                 pos = 1;
2842                         }
2843
2844                         if (old_ce)
2845                                 iounmap(old_ce);
2846
2847                         ret = 0;
2848                         if (devfn < 0x80)
2849                                 old_ce_phys = root_entry_lctp(&re);
2850                         else
2851                                 old_ce_phys = root_entry_uctp(&re);
2852
2853                         if (!old_ce_phys) {
2854                                 if (ext && devfn == 0) {
2855                                         /* No LCTP, try UCTP */
2856                                         devfn = 0x7f;
2857                                         continue;
2858                                 } else {
2859                                         goto out;
2860                                 }
2861                         }
2862
2863                         ret = -ENOMEM;
2864                         old_ce = memremap(old_ce_phys, PAGE_SIZE,
2865                                         MEMREMAP_WB);
2866                         if (!old_ce)
2867                                 goto out;
2868
2869                         new_ce = alloc_pgtable_page(iommu->node);
2870                         if (!new_ce)
2871                                 goto out_unmap;
2872
2873                         ret = 0;
2874                 }
2875
2876                 /* Now copy the context entry */
2877                 memcpy(&ce, old_ce + idx, sizeof(ce));
2878
2879                 if (!__context_present(&ce))
2880                         continue;
2881
2882                 did = context_domain_id(&ce);
2883                 if (did >= 0 && did < cap_ndoms(iommu->cap))
2884                         set_bit(did, iommu->domain_ids);
2885
2886                 /*
2887                  * We need a marker for copied context entries. This
2888                  * marker needs to work for the old format as well as
2889                  * for extended context entries.
2890                  *
2891                  * Bit 67 of the context entry is used. In the old
2892                  * format this bit is available to software, in the
2893                  * extended format it is the PGE bit, but PGE is ignored
2894                  * by HW if PASIDs are disabled (and thus still
2895                  * available).
2896                  *
2897                  * So disable PASIDs first and then mark the entry
2898                  * copied. This means that we don't copy PASID
2899                  * translations from the old kernel, but this is fine as
2900                  * faults there are not fatal.
2901                  */
2902                 context_clear_pasid_enable(&ce);
2903                 context_set_copied(&ce);
2904
2905                 new_ce[idx] = ce;
2906         }
2907
2908         tbl[tbl_idx + pos] = new_ce;
2909
2910         __iommu_flush_cache(iommu, new_ce, VTD_PAGE_SIZE);
2911
2912 out_unmap:
2913         memunmap(old_ce);
2914
2915 out:
2916         return ret;
2917 }
2918
2919 static int copy_translation_tables(struct intel_iommu *iommu)
2920 {
2921         struct context_entry **ctxt_tbls;
2922         struct root_entry *old_rt;
2923         phys_addr_t old_rt_phys;
2924         int ctxt_table_entries;
2925         unsigned long flags;
2926         u64 rtaddr_reg;
2927         int bus, ret;
2928         bool new_ext, ext;
2929
2930         rtaddr_reg = dmar_readq(iommu->reg + DMAR_RTADDR_REG);
2931         ext        = !!(rtaddr_reg & DMA_RTADDR_RTT);
2932         new_ext    = !!ecap_ecs(iommu->ecap);
2933
2934         /*
2935          * The RTT bit can only be changed when translation is disabled,
2936          * but disabling translation means to open a window for data
2937          * corruption. So bail out and don't copy anything if we would
2938          * have to change the bit.
2939          */
2940         if (new_ext != ext)
2941                 return -EINVAL;
2942
2943         old_rt_phys = rtaddr_reg & VTD_PAGE_MASK;
2944         if (!old_rt_phys)
2945                 return -EINVAL;
2946
2947         old_rt = memremap(old_rt_phys, PAGE_SIZE, MEMREMAP_WB);
2948         if (!old_rt)
2949                 return -ENOMEM;
2950
2951         /* This is too big for the stack - allocate it from slab */
2952         ctxt_table_entries = ext ? 512 : 256;
2953         ret = -ENOMEM;
2954         ctxt_tbls = kzalloc(ctxt_table_entries * sizeof(void *), GFP_KERNEL);
2955         if (!ctxt_tbls)
2956                 goto out_unmap;
2957
2958         for (bus = 0; bus < 256; bus++) {
2959                 ret = copy_context_table(iommu, &old_rt[bus],
2960                                          ctxt_tbls, bus, ext);
2961                 if (ret) {
2962                         pr_err("%s: Failed to copy context table for bus %d\n",
2963                                 iommu->name, bus);
2964                         continue;
2965                 }
2966         }
2967
2968         spin_lock_irqsave(&iommu->lock, flags);
2969
2970         /* Context tables are copied, now write them to the root_entry table */
2971         for (bus = 0; bus < 256; bus++) {
2972                 int idx = ext ? bus * 2 : bus;
2973                 u64 val;
2974
2975                 if (ctxt_tbls[idx]) {
2976                         val = virt_to_phys(ctxt_tbls[idx]) | 1;
2977                         iommu->root_entry[bus].lo = val;
2978                 }
2979
2980                 if (!ext || !ctxt_tbls[idx + 1])
2981                         continue;
2982
2983                 val = virt_to_phys(ctxt_tbls[idx + 1]) | 1;
2984                 iommu->root_entry[bus].hi = val;
2985         }
2986
2987         spin_unlock_irqrestore(&iommu->lock, flags);
2988
2989         kfree(ctxt_tbls);
2990
2991         __iommu_flush_cache(iommu, iommu->root_entry, PAGE_SIZE);
2992
2993         ret = 0;
2994
2995 out_unmap:
2996         memunmap(old_rt);
2997
2998         return ret;
2999 }
3000
3001 static int __init init_dmars(void)
3002 {
3003         struct dmar_drhd_unit *drhd;
3004         struct dmar_rmrr_unit *rmrr;
3005         bool copied_tables = false;
3006         struct device *dev;
3007         struct intel_iommu *iommu;
3008         int i, ret;
3009
3010         /*
3011          * for each drhd
3012          *    allocate root
3013          *    initialize and program root entry to not present
3014          * endfor
3015          */
3016         for_each_drhd_unit(drhd) {
3017                 /*
3018                  * lock not needed as this is only incremented in the single
3019                  * threaded kernel __init code path all other access are read
3020                  * only
3021                  */
3022                 if (g_num_of_iommus < DMAR_UNITS_SUPPORTED) {
3023                         g_num_of_iommus++;
3024                         continue;
3025                 }
3026                 pr_err_once("Exceeded %d IOMMUs\n", DMAR_UNITS_SUPPORTED);
3027         }
3028
3029         /* Preallocate enough resources for IOMMU hot-addition */
3030         if (g_num_of_iommus < DMAR_UNITS_SUPPORTED)
3031                 g_num_of_iommus = DMAR_UNITS_SUPPORTED;
3032
3033         g_iommus = kcalloc(g_num_of_iommus, sizeof(struct intel_iommu *),
3034                         GFP_KERNEL);
3035         if (!g_iommus) {
3036                 pr_err("Allocating global iommu array failed\n");
3037                 ret = -ENOMEM;
3038                 goto error;
3039         }
3040
3041         deferred_flush = kzalloc(g_num_of_iommus *
3042                 sizeof(struct deferred_flush_tables), GFP_KERNEL);
3043         if (!deferred_flush) {
3044                 ret = -ENOMEM;
3045                 goto free_g_iommus;
3046         }
3047
3048         for_each_active_iommu(iommu, drhd) {
3049                 g_iommus[iommu->seq_id] = iommu;
3050
3051                 intel_iommu_init_qi(iommu);
3052
3053                 ret = iommu_init_domains(iommu);
3054                 if (ret)
3055                         goto free_iommu;
3056
3057                 init_translation_status(iommu);
3058
3059                 if (translation_pre_enabled(iommu) && !is_kdump_kernel()) {
3060                         iommu_disable_translation(iommu);
3061                         clear_translation_pre_enabled(iommu);
3062                         pr_warn("Translation was enabled for %s but we are not in kdump mode\n",
3063                                 iommu->name);
3064                 }
3065
3066                 /*
3067                  * TBD:
3068                  * we could share the same root & context tables
3069                  * among all IOMMU's. Need to Split it later.
3070                  */
3071                 ret = iommu_alloc_root_entry(iommu);
3072                 if (ret)
3073                         goto free_iommu;
3074
3075                 if (translation_pre_enabled(iommu)) {
3076                         pr_info("Translation already enabled - trying to copy translation structures\n");
3077
3078                         ret = copy_translation_tables(iommu);
3079                         if (ret) {
3080                                 /*
3081                                  * We found the IOMMU with translation
3082                                  * enabled - but failed to copy over the
3083                                  * old root-entry table. Try to proceed
3084                                  * by disabling translation now and
3085                                  * allocating a clean root-entry table.
3086                                  * This might cause DMAR faults, but
3087                                  * probably the dump will still succeed.
3088                                  */
3089                                 pr_err("Failed to copy translation tables from previous kernel for %s\n",
3090                                        iommu->name);
3091                                 iommu_disable_translation(iommu);
3092                                 clear_translation_pre_enabled(iommu);
3093                         } else {
3094                                 pr_info("Copied translation tables from previous kernel for %s\n",
3095                                         iommu->name);
3096                                 copied_tables = true;
3097                         }
3098                 }
3099
3100                 iommu_flush_write_buffer(iommu);
3101                 iommu_set_root_entry(iommu);
3102                 iommu->flush.flush_context(iommu, 0, 0, 0, DMA_CCMD_GLOBAL_INVL);
3103                 iommu->flush.flush_iotlb(iommu, 0, 0, 0, DMA_TLB_GLOBAL_FLUSH);
3104
3105                 if (!ecap_pass_through(iommu->ecap))
3106                         hw_pass_through = 0;
3107         }
3108
3109         if (iommu_pass_through)
3110                 iommu_identity_mapping |= IDENTMAP_ALL;
3111
3112 #ifdef CONFIG_INTEL_IOMMU_BROKEN_GFX_WA
3113         iommu_identity_mapping |= IDENTMAP_GFX;
3114 #endif
3115
3116         if (iommu_identity_mapping) {
3117                 ret = si_domain_init(hw_pass_through);
3118                 if (ret)
3119                         goto free_iommu;
3120         }
3121
3122         check_tylersburg_isoch();
3123
3124         /*
3125          * If we copied translations from a previous kernel in the kdump
3126          * case, we can not assign the devices to domains now, as that
3127          * would eliminate the old mappings. So skip this part and defer
3128          * the assignment to device driver initialization time.
3129          */
3130         if (copied_tables)
3131                 goto domains_done;
3132
3133         /*
3134          * If pass through is not set or not enabled, setup context entries for
3135          * identity mappings for rmrr, gfx, and isa and may fall back to static
3136          * identity mapping if iommu_identity_mapping is set.
3137          */
3138         if (iommu_identity_mapping) {
3139                 ret = iommu_prepare_static_identity_mapping(hw_pass_through);
3140                 if (ret) {
3141                         pr_crit("Failed to setup IOMMU pass-through\n");
3142                         goto free_iommu;
3143                 }
3144         }
3145         /*
3146          * For each rmrr
3147          *   for each dev attached to rmrr
3148          *   do
3149          *     locate drhd for dev, alloc domain for dev
3150          *     allocate free domain
3151          *     allocate page table entries for rmrr
3152          *     if context not allocated for bus
3153          *           allocate and init context
3154          *           set present in root table for this bus
3155          *     init context with domain, translation etc
3156          *    endfor
3157          * endfor
3158          */
3159         pr_info("Setting RMRR:\n");
3160         for_each_rmrr_units(rmrr) {
3161                 /* some BIOS lists non-exist devices in DMAR table. */
3162                 for_each_active_dev_scope(rmrr->devices, rmrr->devices_cnt,
3163                                           i, dev) {
3164                         ret = iommu_prepare_rmrr_dev(rmrr, dev);
3165                         if (ret)
3166                                 pr_err("Mapping reserved region failed\n");
3167                 }
3168         }
3169
3170         iommu_prepare_isa();
3171
3172 domains_done:
3173
3174         /*
3175          * for each drhd
3176          *   enable fault log
3177          *   global invalidate context cache
3178          *   global invalidate iotlb
3179          *   enable translation
3180          */
3181         for_each_iommu(iommu, drhd) {
3182                 if (drhd->ignored) {
3183                         /*
3184                          * we always have to disable PMRs or DMA may fail on
3185                          * this device
3186                          */
3187                         if (force_on)
3188                                 iommu_disable_protect_mem_regions(iommu);
3189                         continue;
3190                 }
3191
3192                 iommu_flush_write_buffer(iommu);
3193
3194                 ret = dmar_set_interrupt(iommu);
3195                 if (ret)
3196                         goto free_iommu;
3197
3198                 if (!translation_pre_enabled(iommu))
3199                         iommu_enable_translation(iommu);
3200
3201                 iommu_disable_protect_mem_regions(iommu);
3202         }
3203
3204         return 0;
3205
3206 free_iommu:
3207         for_each_active_iommu(iommu, drhd) {
3208                 disable_dmar_iommu(iommu);
3209                 free_dmar_iommu(iommu);
3210         }
3211         kfree(deferred_flush);
3212 free_g_iommus:
3213         kfree(g_iommus);
3214 error:
3215         return ret;
3216 }
3217
3218 /* This takes a number of _MM_ pages, not VTD pages */
3219 static struct iova *intel_alloc_iova(struct device *dev,
3220                                      struct dmar_domain *domain,
3221                                      unsigned long nrpages, uint64_t dma_mask)
3222 {
3223         struct iova *iova = NULL;
3224
3225         /* Restrict dma_mask to the width that the iommu can handle */
3226         dma_mask = min_t(uint64_t, DOMAIN_MAX_ADDR(domain->gaw), dma_mask);
3227         /* Ensure we reserve the whole size-aligned region */
3228         nrpages = __roundup_pow_of_two(nrpages);
3229
3230         if (!dmar_forcedac && dma_mask > DMA_BIT_MASK(32)) {
3231                 /*
3232                  * First try to allocate an io virtual address in
3233                  * DMA_BIT_MASK(32) and if that fails then try allocating
3234                  * from higher range
3235                  */
3236                 iova = alloc_iova(&domain->iovad, nrpages,
3237                                   IOVA_PFN(DMA_BIT_MASK(32)), 1);
3238                 if (iova)
3239                         return iova;
3240         }
3241         iova = alloc_iova(&domain->iovad, nrpages, IOVA_PFN(dma_mask), 1);
3242         if (unlikely(!iova)) {
3243                 pr_err("Allocating %ld-page iova for %s failed",
3244                        nrpages, dev_name(dev));
3245                 return NULL;
3246         }
3247
3248         return iova;
3249 }
3250
3251 static struct dmar_domain *__get_valid_domain_for_dev(struct device *dev)
3252 {
3253         struct dmar_rmrr_unit *rmrr;
3254         struct dmar_domain *domain;
3255         struct device *i_dev;
3256         int i, ret;
3257
3258         domain = get_domain_for_dev(dev, DEFAULT_DOMAIN_ADDRESS_WIDTH);
3259         if (!domain) {
3260                 pr_err("Allocating domain for %s failed\n",
3261                        dev_name(dev));
3262                 return NULL;
3263         }
3264
3265         /* We have a new domain - setup possible RMRRs for the device */
3266         rcu_read_lock();
3267         for_each_rmrr_units(rmrr) {
3268                 for_each_active_dev_scope(rmrr->devices, rmrr->devices_cnt,
3269                                           i, i_dev) {
3270                         if (i_dev != dev)
3271                                 continue;
3272
3273                         ret = domain_prepare_identity_map(dev, domain,
3274                                                           rmrr->base_address,
3275                                                           rmrr->end_address);
3276                         if (ret)
3277                                 dev_err(dev, "Mapping reserved region failed\n");
3278                 }
3279         }
3280         rcu_read_unlock();
3281
3282         return domain;
3283 }
3284
3285 static inline struct dmar_domain *get_valid_domain_for_dev(struct device *dev)
3286 {
3287         struct device_domain_info *info;
3288
3289         /* No lock here, assumes no domain exit in normal case */
3290         info = dev->archdata.iommu;
3291         if (likely(info))
3292                 return info->domain;
3293
3294         return __get_valid_domain_for_dev(dev);
3295 }
3296
3297 /* Check if the dev needs to go through non-identity map and unmap process.*/
3298 static int iommu_no_mapping(struct device *dev)
3299 {
3300         int found;
3301
3302         if (iommu_dummy(dev))
3303                 return 1;
3304
3305         if (!iommu_identity_mapping)
3306                 return 0;
3307
3308         found = identity_mapping(dev);
3309         if (found) {
3310                 if (iommu_should_identity_map(dev, 0))
3311                         return 1;
3312                 else {
3313                         /*
3314                          * 32 bit DMA is removed from si_domain and fall back
3315                          * to non-identity mapping.
3316                          */
3317                         dmar_remove_one_dev_info(si_domain, dev);
3318                         pr_info("32bit %s uses non-identity mapping\n",
3319                                 dev_name(dev));
3320                         return 0;
3321                 }
3322         } else {
3323                 /*
3324                  * In case of a detached 64 bit DMA device from vm, the device
3325                  * is put into si_domain for identity mapping.
3326                  */
3327                 if (iommu_should_identity_map(dev, 0)) {
3328                         int ret;
3329                         ret = domain_add_dev_info(si_domain, dev);
3330                         if (!ret) {
3331                                 pr_info("64bit %s uses identity mapping\n",
3332                                         dev_name(dev));
3333                                 return 1;
3334                         }
3335                 }
3336         }
3337
3338         return 0;
3339 }
3340
3341 static dma_addr_t __intel_map_single(struct device *dev, phys_addr_t paddr,
3342                                      size_t size, int dir, u64 dma_mask)
3343 {
3344         struct dmar_domain *domain;
3345         phys_addr_t start_paddr;
3346         struct iova *iova;
3347         int prot = 0;
3348         int ret;
3349         struct intel_iommu *iommu;
3350         unsigned long paddr_pfn = paddr >> PAGE_SHIFT;
3351
3352         BUG_ON(dir == DMA_NONE);
3353
3354         if (iommu_no_mapping(dev))
3355                 return paddr;
3356
3357         domain = get_valid_domain_for_dev(dev);
3358         if (!domain)
3359                 return 0;
3360
3361         iommu = domain_get_iommu(domain);
3362         size = aligned_nrpages(paddr, size);
3363
3364         iova = intel_alloc_iova(dev, domain, dma_to_mm_pfn(size), dma_mask);
3365         if (!iova)
3366                 goto error;
3367
3368         /*
3369          * Check if DMAR supports zero-length reads on write only
3370          * mappings..
3371          */
3372         if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL || \
3373                         !cap_zlr(iommu->cap))
3374                 prot |= DMA_PTE_READ;
3375         if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
3376                 prot |= DMA_PTE_WRITE;
3377         /*
3378          * paddr - (paddr + size) might be partial page, we should map the whole
3379          * page.  Note: if two part of one page are separately mapped, we
3380          * might have two guest_addr mapping to the same host paddr, but this
3381          * is not a big problem
3382          */
3383         ret = domain_pfn_mapping(domain, mm_to_dma_pfn(iova->pfn_lo),
3384                                  mm_to_dma_pfn(paddr_pfn), size, prot);
3385         if (ret)
3386                 goto error;
3387
3388         /* it's a non-present to present mapping. Only flush if caching mode */
3389         if (cap_caching_mode(iommu->cap))
3390                 iommu_flush_iotlb_psi(iommu, domain,
3391                                       mm_to_dma_pfn(iova->pfn_lo),
3392                                       size, 0, 1);
3393         else
3394                 iommu_flush_write_buffer(iommu);
3395
3396         start_paddr = (phys_addr_t)iova->pfn_lo << PAGE_SHIFT;
3397         start_paddr += paddr & ~PAGE_MASK;
3398         return start_paddr;
3399
3400 error:
3401         if (iova)
3402                 __free_iova(&domain->iovad, iova);
3403         pr_err("Device %s request: %zx@%llx dir %d --- failed\n",
3404                 dev_name(dev), size, (unsigned long long)paddr, dir);
3405         return 0;
3406 }
3407
3408 static dma_addr_t intel_map_page(struct device *dev, struct page *page,
3409                                  unsigned long offset, size_t size,
3410                                  enum dma_data_direction dir,
3411                                  struct dma_attrs *attrs)
3412 {
3413         return __intel_map_single(dev, page_to_phys(page) + offset, size,
3414                                   dir, *dev->dma_mask);
3415 }
3416
3417 static void flush_unmaps(void)
3418 {
3419         int i, j;
3420
3421         timer_on = 0;
3422
3423         /* just flush them all */
3424         for (i = 0; i < g_num_of_iommus; i++) {
3425                 struct intel_iommu *iommu = g_iommus[i];
3426                 if (!iommu)
3427                         continue;
3428
3429                 if (!deferred_flush[i].next)
3430                         continue;
3431
3432                 /* In caching mode, global flushes turn emulation expensive */
3433                 if (!cap_caching_mode(iommu->cap))
3434                         iommu->flush.flush_iotlb(iommu, 0, 0, 0,
3435                                          DMA_TLB_GLOBAL_FLUSH);
3436                 for (j = 0; j < deferred_flush[i].next; j++) {
3437                         unsigned long mask;
3438                         struct iova *iova = deferred_flush[i].iova[j];
3439                         struct dmar_domain *domain = deferred_flush[i].domain[j];
3440
3441                         /* On real hardware multiple invalidations are expensive */
3442                         if (cap_caching_mode(iommu->cap))
3443                                 iommu_flush_iotlb_psi(iommu, domain,
3444                                         iova->pfn_lo, iova_size(iova),
3445                                         !deferred_flush[i].freelist[j], 0);
3446                         else {
3447                                 mask = ilog2(mm_to_dma_pfn(iova_size(iova)));
3448                                 iommu_flush_dev_iotlb(deferred_flush[i].domain[j],
3449                                                 (uint64_t)iova->pfn_lo << PAGE_SHIFT, mask);
3450                         }
3451                         __free_iova(&deferred_flush[i].domain[j]->iovad, iova);
3452                         if (deferred_flush[i].freelist[j])
3453                                 dma_free_pagelist(deferred_flush[i].freelist[j]);
3454                 }
3455                 deferred_flush[i].next = 0;
3456         }
3457
3458         list_size = 0;
3459 }
3460
3461 static void flush_unmaps_timeout(unsigned long data)
3462 {
3463         unsigned long flags;
3464
3465         spin_lock_irqsave(&async_umap_flush_lock, flags);
3466         flush_unmaps();
3467         spin_unlock_irqrestore(&async_umap_flush_lock, flags);
3468 }
3469
3470 static void add_unmap(struct dmar_domain *dom, struct iova *iova, struct page *freelist)
3471 {
3472         unsigned long flags;
3473         int next, iommu_id;
3474         struct intel_iommu *iommu;
3475
3476         spin_lock_irqsave(&async_umap_flush_lock, flags);
3477         if (list_size == HIGH_WATER_MARK)
3478                 flush_unmaps();
3479
3480         iommu = domain_get_iommu(dom);
3481         iommu_id = iommu->seq_id;
3482
3483         next = deferred_flush[iommu_id].next;
3484         deferred_flush[iommu_id].domain[next] = dom;
3485         deferred_flush[iommu_id].iova[next] = iova;
3486         deferred_flush[iommu_id].freelist[next] = freelist;
3487         deferred_flush[iommu_id].next++;
3488
3489         if (!timer_on) {
3490                 mod_timer(&unmap_timer, jiffies + msecs_to_jiffies(10));
3491                 timer_on = 1;
3492         }
3493         list_size++;
3494         spin_unlock_irqrestore(&async_umap_flush_lock, flags);
3495 }
3496
3497 static void intel_unmap(struct device *dev, dma_addr_t dev_addr)
3498 {
3499         struct dmar_domain *domain;
3500         unsigned long start_pfn, last_pfn;
3501         struct iova *iova;
3502         struct intel_iommu *iommu;
3503         struct page *freelist;
3504
3505         if (iommu_no_mapping(dev))
3506                 return;
3507
3508         domain = find_domain(dev);
3509         BUG_ON(!domain);
3510
3511         iommu = domain_get_iommu(domain);
3512
3513         iova = find_iova(&domain->iovad, IOVA_PFN(dev_addr));
3514         if (WARN_ONCE(!iova, "Driver unmaps unmatched page at PFN %llx\n",
3515                       (unsigned long long)dev_addr))
3516                 return;
3517
3518         start_pfn = mm_to_dma_pfn(iova->pfn_lo);
3519         last_pfn = mm_to_dma_pfn(iova->pfn_hi + 1) - 1;
3520
3521         pr_debug("Device %s unmapping: pfn %lx-%lx\n",
3522                  dev_name(dev), start_pfn, last_pfn);
3523
3524         freelist = domain_unmap(domain, start_pfn, last_pfn);
3525
3526         if (intel_iommu_strict) {
3527                 iommu_flush_iotlb_psi(iommu, domain, start_pfn,
3528                                       last_pfn - start_pfn + 1, !freelist, 0);
3529                 /* free iova */
3530                 __free_iova(&domain->iovad, iova);
3531                 dma_free_pagelist(freelist);
3532         } else {
3533                 add_unmap(domain, iova, freelist);
3534                 /*
3535                  * queue up the release of the unmap to save the 1/6th of the
3536                  * cpu used up by the iotlb flush operation...
3537                  */
3538         }
3539 }
3540
3541 static void intel_unmap_page(struct device *dev, dma_addr_t dev_addr,
3542                              size_t size, enum dma_data_direction dir,
3543                              struct dma_attrs *attrs)
3544 {
3545         intel_unmap(dev, dev_addr);
3546 }
3547
3548 static void *intel_alloc_coherent(struct device *dev, size_t size,
3549                                   dma_addr_t *dma_handle, gfp_t flags,
3550                                   struct dma_attrs *attrs)
3551 {
3552         struct page *page = NULL;
3553         int order;
3554
3555         size = PAGE_ALIGN(size);
3556         order = get_order(size);
3557
3558         if (!iommu_no_mapping(dev))
3559                 flags &= ~(GFP_DMA | GFP_DMA32);
3560         else if (dev->coherent_dma_mask < dma_get_required_mask(dev)) {
3561                 if (dev->coherent_dma_mask < DMA_BIT_MASK(32))
3562                         flags |= GFP_DMA;
3563                 else
3564                         flags |= GFP_DMA32;
3565         }
3566
3567         if (flags & __GFP_WAIT) {
3568                 unsigned int count = size >> PAGE_SHIFT;
3569
3570                 page = dma_alloc_from_contiguous(dev, count, order);
3571                 if (page && iommu_no_mapping(dev) &&
3572                     page_to_phys(page) + size > dev->coherent_dma_mask) {
3573                         dma_release_from_contiguous(dev, page, count);
3574                         page = NULL;
3575                 }
3576         }
3577
3578         if (!page)
3579                 page = alloc_pages(flags, order);
3580         if (!page)
3581                 return NULL;
3582         memset(page_address(page), 0, size);
3583
3584         *dma_handle = __intel_map_single(dev, page_to_phys(page), size,
3585                                          DMA_BIDIRECTIONAL,
3586                                          dev->coherent_dma_mask);
3587         if (*dma_handle)
3588                 return page_address(page);
3589         if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
3590                 __free_pages(page, order);
3591
3592         return NULL;
3593 }
3594
3595 static void intel_free_coherent(struct device *dev, size_t size, void *vaddr,
3596                                 dma_addr_t dma_handle, struct dma_attrs *attrs)
3597 {
3598         int order;
3599         struct page *page = virt_to_page(vaddr);
3600
3601         size = PAGE_ALIGN(size);
3602         order = get_order(size);
3603
3604         intel_unmap(dev, dma_handle);
3605         if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
3606                 __free_pages(page, order);
3607 }
3608
3609 static void intel_unmap_sg(struct device *dev, struct scatterlist *sglist,
3610                            int nelems, enum dma_data_direction dir,
3611                            struct dma_attrs *attrs)
3612 {
3613         intel_unmap(dev, sglist[0].dma_address);
3614 }
3615
3616 static int intel_nontranslate_map_sg(struct device *hddev,
3617         struct scatterlist *sglist, int nelems, int dir)
3618 {
3619         int i;
3620         struct scatterlist *sg;
3621
3622         for_each_sg(sglist, sg, nelems, i) {
3623                 BUG_ON(!sg_page(sg));
3624                 sg->dma_address = sg_phys(sg);
3625                 sg->dma_length = sg->length;
3626         }
3627         return nelems;
3628 }
3629
3630 static int intel_map_sg(struct device *dev, struct scatterlist *sglist, int nelems,
3631                         enum dma_data_direction dir, struct dma_attrs *attrs)
3632 {
3633         int i;
3634         struct dmar_domain *domain;
3635         size_t size = 0;
3636         int prot = 0;
3637         struct iova *iova = NULL;
3638         int ret;
3639         struct scatterlist *sg;
3640         unsigned long start_vpfn;
3641         struct intel_iommu *iommu;
3642
3643         BUG_ON(dir == DMA_NONE);
3644         if (iommu_no_mapping(dev))
3645                 return intel_nontranslate_map_sg(dev, sglist, nelems, dir);
3646
3647         domain = get_valid_domain_for_dev(dev);
3648         if (!domain)
3649                 return 0;
3650
3651         iommu = domain_get_iommu(domain);
3652
3653         for_each_sg(sglist, sg, nelems, i)
3654                 size += aligned_nrpages(sg->offset, sg->length);
3655
3656         iova = intel_alloc_iova(dev, domain, dma_to_mm_pfn(size),
3657                                 *dev->dma_mask);
3658         if (!iova) {
3659                 sglist->dma_length = 0;
3660                 return 0;
3661         }
3662
3663         /*
3664          * Check if DMAR supports zero-length reads on write only
3665          * mappings..
3666          */
3667         if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL || \
3668                         !cap_zlr(iommu->cap))
3669                 prot |= DMA_PTE_READ;
3670         if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
3671                 prot |= DMA_PTE_WRITE;
3672
3673         start_vpfn = mm_to_dma_pfn(iova->pfn_lo);
3674
3675         ret = domain_sg_mapping(domain, start_vpfn, sglist, size, prot);
3676         if (unlikely(ret)) {
3677                 dma_pte_free_pagetable(domain, start_vpfn,
3678                                        start_vpfn + size - 1);
3679                 __free_iova(&domain->iovad, iova);
3680                 return 0;
3681         }
3682
3683         /* it's a non-present to present mapping. Only flush if caching mode */
3684         if (cap_caching_mode(iommu->cap))
3685                 iommu_flush_iotlb_psi(iommu, domain, start_vpfn, size, 0, 1);
3686         else
3687                 iommu_flush_write_buffer(iommu);
3688
3689         return nelems;
3690 }
3691
3692 static int intel_mapping_error(struct device *dev, dma_addr_t dma_addr)
3693 {
3694         return !dma_addr;
3695 }
3696
3697 struct dma_map_ops intel_dma_ops = {
3698         .alloc = intel_alloc_coherent,
3699         .free = intel_free_coherent,
3700         .map_sg = intel_map_sg,
3701         .unmap_sg = intel_unmap_sg,
3702         .map_page = intel_map_page,
3703         .unmap_page = intel_unmap_page,
3704         .mapping_error = intel_mapping_error,
3705 };
3706
3707 static inline int iommu_domain_cache_init(void)
3708 {
3709         int ret = 0;
3710
3711         iommu_domain_cache = kmem_cache_create("iommu_domain",
3712                                          sizeof(struct dmar_domain),
3713                                          0,
3714                                          SLAB_HWCACHE_ALIGN,
3715
3716                                          NULL);
3717         if (!iommu_domain_cache) {
3718                 pr_err("Couldn't create iommu_domain cache\n");
3719                 ret = -ENOMEM;
3720         }
3721
3722         return ret;
3723 }
3724
3725 static inline int iommu_devinfo_cache_init(void)
3726 {
3727         int ret = 0;
3728
3729         iommu_devinfo_cache = kmem_cache_create("iommu_devinfo",
3730                                          sizeof(struct device_domain_info),
3731                                          0,
3732                                          SLAB_HWCACHE_ALIGN,
3733                                          NULL);
3734         if (!iommu_devinfo_cache) {
3735                 pr_err("Couldn't create devinfo cache\n");
3736                 ret = -ENOMEM;
3737         }
3738
3739         return ret;
3740 }
3741
3742 static int __init iommu_init_mempool(void)
3743 {
3744         int ret;
3745         ret = iova_cache_get();
3746         if (ret)
3747                 return ret;
3748
3749         ret = iommu_domain_cache_init();
3750         if (ret)
3751                 goto domain_error;
3752
3753         ret = iommu_devinfo_cache_init();
3754         if (!ret)
3755                 return ret;
3756
3757         kmem_cache_destroy(iommu_domain_cache);
3758 domain_error:
3759         iova_cache_put();
3760
3761         return -ENOMEM;
3762 }
3763
3764 static void __init iommu_exit_mempool(void)
3765 {
3766         kmem_cache_destroy(iommu_devinfo_cache);
3767         kmem_cache_destroy(iommu_domain_cache);
3768         iova_cache_put();
3769 }
3770
3771 static void quirk_ioat_snb_local_iommu(struct pci_dev *pdev)
3772 {
3773         struct dmar_drhd_unit *drhd;
3774         u32 vtbar;
3775         int rc;
3776
3777         /* We know that this device on this chipset has its own IOMMU.
3778          * If we find it under a different IOMMU, then the BIOS is lying
3779          * to us. Hope that the IOMMU for this device is actually
3780          * disabled, and it needs no translation...
3781          */
3782         rc = pci_bus_read_config_dword(pdev->bus, PCI_DEVFN(0, 0), 0xb0, &vtbar);
3783         if (rc) {
3784                 /* "can't" happen */
3785                 dev_info(&pdev->dev, "failed to run vt-d quirk\n");
3786                 return;
3787         }
3788         vtbar &= 0xffff0000;
3789
3790         /* we know that the this iommu should be at offset 0xa000 from vtbar */
3791         drhd = dmar_find_matched_drhd_unit(pdev);
3792         if (WARN_TAINT_ONCE(!drhd || drhd->reg_base_addr - vtbar != 0xa000,
3793                             TAINT_FIRMWARE_WORKAROUND,
3794                             "BIOS assigned incorrect VT-d unit for Intel(R) QuickData Technology device\n"))
3795                 pdev->dev.archdata.iommu = DUMMY_DEVICE_DOMAIN_INFO;
3796 }
3797 DECLARE_PCI_FIXUP_ENABLE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_IOAT_SNB, quirk_ioat_snb_local_iommu);
3798
3799 static void __init init_no_remapping_devices(void)
3800 {
3801         struct dmar_drhd_unit *drhd;
3802         struct device *dev;
3803         int i;
3804
3805         for_each_drhd_unit(drhd) {
3806                 if (!drhd->include_all) {
3807                         for_each_active_dev_scope(drhd->devices,
3808                                                   drhd->devices_cnt, i, dev)
3809                                 break;
3810                         /* ignore DMAR unit if no devices exist */
3811                         if (i == drhd->devices_cnt)
3812                                 drhd->ignored = 1;
3813                 }
3814         }
3815
3816         for_each_active_drhd_unit(drhd) {
3817                 if (drhd->include_all)
3818                         continue;
3819
3820                 for_each_active_dev_scope(drhd->devices,
3821                                           drhd->devices_cnt, i, dev)
3822                         if (!dev_is_pci(dev) || !IS_GFX_DEVICE(to_pci_dev(dev)))
3823                                 break;
3824                 if (i < drhd->devices_cnt)
3825                         continue;
3826
3827                 /* This IOMMU has *only* gfx devices. Either bypass it or
3828                    set the gfx_mapped flag, as appropriate */
3829                 if (dmar_map_gfx) {
3830                         intel_iommu_gfx_mapped = 1;
3831                 } else {
3832                         drhd->ignored = 1;
3833                         for_each_active_dev_scope(drhd->devices,
3834                                                   drhd->devices_cnt, i, dev)
3835                                 dev->archdata.iommu = DUMMY_DEVICE_DOMAIN_INFO;
3836                 }
3837         }
3838 }
3839
3840 #ifdef CONFIG_SUSPEND
3841 static int init_iommu_hw(void)
3842 {
3843         struct dmar_drhd_unit *drhd;
3844         struct intel_iommu *iommu = NULL;
3845
3846         for_each_active_iommu(iommu, drhd)
3847                 if (iommu->qi)
3848                         dmar_reenable_qi(iommu);
3849
3850         for_each_iommu(iommu, drhd) {
3851                 if (drhd->ignored) {
3852                         /*
3853                          * we always have to disable PMRs or DMA may fail on
3854                          * this device
3855                          */
3856                         if (force_on)
3857                                 iommu_disable_protect_mem_regions(iommu);
3858                         continue;
3859                 }
3860         
3861                 iommu_flush_write_buffer(iommu);
3862
3863                 iommu_set_root_entry(iommu);
3864
3865                 iommu->flush.flush_context(iommu, 0, 0, 0,
3866                                            DMA_CCMD_GLOBAL_INVL);
3867                 iommu->flush.flush_iotlb(iommu, 0, 0, 0, DMA_TLB_GLOBAL_FLUSH);
3868                 iommu_enable_translation(iommu);
3869                 iommu_disable_protect_mem_regions(iommu);
3870         }
3871
3872         return 0;
3873 }
3874
3875 static void iommu_flush_all(void)
3876 {
3877         struct dmar_drhd_unit *drhd;
3878         struct intel_iommu *iommu;
3879
3880         for_each_active_iommu(iommu, drhd) {
3881                 iommu->flush.flush_context(iommu, 0, 0, 0,
3882                                            DMA_CCMD_GLOBAL_INVL);
3883                 iommu->flush.flush_iotlb(iommu, 0, 0, 0,
3884                                          DMA_TLB_GLOBAL_FLUSH);
3885         }
3886 }
3887
3888 static int iommu_suspend(void)
3889 {
3890         struct dmar_drhd_unit *drhd;
3891         struct intel_iommu *iommu = NULL;
3892         unsigned long flag;
3893
3894         for_each_active_iommu(iommu, drhd) {
3895                 iommu->iommu_state = kzalloc(sizeof(u32) * MAX_SR_DMAR_REGS,
3896                                                  GFP_ATOMIC);
3897                 if (!iommu->iommu_state)
3898                         goto nomem;
3899         }
3900
3901         iommu_flush_all();
3902
3903         for_each_active_iommu(iommu, drhd) {
3904                 iommu_disable_translation(iommu);
3905
3906                 raw_spin_lock_irqsave(&iommu->register_lock, flag);
3907
3908                 iommu->iommu_state[SR_DMAR_FECTL_REG] =
3909                         readl(iommu->reg + DMAR_FECTL_REG);
3910                 iommu->iommu_state[SR_DMAR_FEDATA_REG] =
3911                         readl(iommu->reg + DMAR_FEDATA_REG);
3912                 iommu->iommu_state[SR_DMAR_FEADDR_REG] =
3913                         readl(iommu->reg + DMAR_FEADDR_REG);
3914                 iommu->iommu_state[SR_DMAR_FEUADDR_REG] =
3915                         readl(iommu->reg + DMAR_FEUADDR_REG);
3916
3917                 raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
3918         }
3919         return 0;
3920
3921 nomem:
3922         for_each_active_iommu(iommu, drhd)
3923                 kfree(iommu->iommu_state);
3924
3925         return -ENOMEM;
3926 }
3927
3928 static void iommu_resume(void)
3929 {
3930         struct dmar_drhd_unit *drhd;
3931         struct intel_iommu *iommu = NULL;
3932         unsigned long flag;
3933
3934         if (init_iommu_hw()) {
3935                 if (force_on)
3936                         panic("tboot: IOMMU setup failed, DMAR can not resume!\n");
3937                 else
3938                         WARN(1, "IOMMU setup failed, DMAR can not resume!\n");
3939                 return;
3940         }
3941
3942         for_each_active_iommu(iommu, drhd) {
3943
3944                 raw_spin_lock_irqsave(&iommu->register_lock, flag);
3945
3946                 writel(iommu->iommu_state[SR_DMAR_FECTL_REG],
3947                         iommu->reg + DMAR_FECTL_REG);
3948                 writel(iommu->iommu_state[SR_DMAR_FEDATA_REG],
3949                         iommu->reg + DMAR_FEDATA_REG);
3950                 writel(iommu->iommu_state[SR_DMAR_FEADDR_REG],
3951                         iommu->reg + DMAR_FEADDR_REG);
3952                 writel(iommu->iommu_state[SR_DMAR_FEUADDR_REG],
3953                         iommu->reg + DMAR_FEUADDR_REG);
3954
3955                 raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
3956         }
3957
3958         for_each_active_iommu(iommu, drhd)
3959                 kfree(iommu->iommu_state);
3960 }
3961
3962 static struct syscore_ops iommu_syscore_ops = {
3963         .resume         = iommu_resume,
3964         .suspend        = iommu_suspend,
3965 };
3966
3967 static void __init init_iommu_pm_ops(void)
3968 {
3969         register_syscore_ops(&iommu_syscore_ops);
3970 }
3971
3972 #else
3973 static inline void init_iommu_pm_ops(void) {}
3974 #endif  /* CONFIG_PM */
3975
3976
3977 int __init dmar_parse_one_rmrr(struct acpi_dmar_header *header, void *arg)
3978 {
3979         struct acpi_dmar_reserved_memory *rmrr;
3980         struct dmar_rmrr_unit *rmrru;
3981
3982         rmrru = kzalloc(sizeof(*rmrru), GFP_KERNEL);
3983         if (!rmrru)
3984                 return -ENOMEM;
3985
3986         rmrru->hdr = header;
3987         rmrr = (struct acpi_dmar_reserved_memory *)header;
3988         rmrru->base_address = rmrr->base_address;
3989         rmrru->end_address = rmrr->end_address;
3990         rmrru->devices = dmar_alloc_dev_scope((void *)(rmrr + 1),
3991                                 ((void *)rmrr) + rmrr->header.length,
3992                                 &rmrru->devices_cnt);
3993         if (rmrru->devices_cnt && rmrru->devices == NULL) {
3994                 kfree(rmrru);
3995                 return -ENOMEM;
3996         }
3997
3998         list_add(&rmrru->list, &dmar_rmrr_units);
3999
4000         return 0;
4001 }
4002
4003 static struct dmar_atsr_unit *dmar_find_atsr(struct acpi_dmar_atsr *atsr)
4004 {
4005         struct dmar_atsr_unit *atsru;
4006         struct acpi_dmar_atsr *tmp;
4007
4008         list_for_each_entry_rcu(atsru, &dmar_atsr_units, list) {
4009                 tmp = (struct acpi_dmar_atsr *)atsru->hdr;
4010                 if (atsr->segment != tmp->segment)
4011                         continue;
4012                 if (atsr->header.length != tmp->header.length)
4013                         continue;
4014                 if (memcmp(atsr, tmp, atsr->header.length) == 0)
4015                         return atsru;
4016         }
4017
4018         return NULL;
4019 }
4020
4021 int dmar_parse_one_atsr(struct acpi_dmar_header *hdr, void *arg)
4022 {
4023         struct acpi_dmar_atsr *atsr;
4024         struct dmar_atsr_unit *atsru;
4025
4026         if (system_state != SYSTEM_BOOTING && !intel_iommu_enabled)
4027                 return 0;
4028
4029         atsr = container_of(hdr, struct acpi_dmar_atsr, header);
4030         atsru = dmar_find_atsr(atsr);
4031         if (atsru)
4032                 return 0;
4033
4034         atsru = kzalloc(sizeof(*atsru) + hdr->length, GFP_KERNEL);
4035         if (!atsru)
4036                 return -ENOMEM;
4037
4038         /*
4039          * If memory is allocated from slab by ACPI _DSM method, we need to
4040          * copy the memory content because the memory buffer will be freed
4041          * on return.
4042          */
4043         atsru->hdr = (void *)(atsru + 1);
4044         memcpy(atsru->hdr, hdr, hdr->length);
4045         atsru->include_all = atsr->flags & 0x1;
4046         if (!atsru->include_all) {
4047                 atsru->devices = dmar_alloc_dev_scope((void *)(atsr + 1),
4048                                 (void *)atsr + atsr->header.length,
4049                                 &atsru->devices_cnt);
4050                 if (atsru->devices_cnt && atsru->devices == NULL) {
4051                         kfree(atsru);
4052                         return -ENOMEM;
4053                 }
4054         }
4055
4056         list_add_rcu(&atsru->list, &dmar_atsr_units);
4057
4058         return 0;
4059 }
4060
4061 static void intel_iommu_free_atsr(struct dmar_atsr_unit *atsru)
4062 {
4063         dmar_free_dev_scope(&atsru->devices, &atsru->devices_cnt);
4064         kfree(atsru);
4065 }
4066
4067 int dmar_release_one_atsr(struct acpi_dmar_header *hdr, void *arg)
4068 {
4069         struct acpi_dmar_atsr *atsr;
4070         struct dmar_atsr_unit *atsru;
4071
4072         atsr = container_of(hdr, struct acpi_dmar_atsr, header);
4073         atsru = dmar_find_atsr(atsr);
4074         if (atsru) {
4075                 list_del_rcu(&atsru->list);
4076                 synchronize_rcu();
4077                 intel_iommu_free_atsr(atsru);
4078         }
4079
4080         return 0;
4081 }
4082
4083 int dmar_check_one_atsr(struct acpi_dmar_header *hdr, void *arg)
4084 {
4085         int i;
4086         struct device *dev;
4087         struct acpi_dmar_atsr *atsr;
4088         struct dmar_atsr_unit *atsru;
4089
4090         atsr = container_of(hdr, struct acpi_dmar_atsr, header);
4091         atsru = dmar_find_atsr(atsr);
4092         if (!atsru)
4093                 return 0;
4094
4095         if (!atsru->include_all && atsru->devices && atsru->devices_cnt)
4096                 for_each_active_dev_scope(atsru->devices, atsru->devices_cnt,
4097                                           i, dev)
4098                         return -EBUSY;
4099
4100         return 0;
4101 }
4102
4103 static int intel_iommu_add(struct dmar_drhd_unit *dmaru)
4104 {
4105         int sp, ret = 0;
4106         struct intel_iommu *iommu = dmaru->iommu;
4107
4108         if (g_iommus[iommu->seq_id])
4109                 return 0;
4110
4111         if (hw_pass_through && !ecap_pass_through(iommu->ecap)) {
4112                 pr_warn("%s: Doesn't support hardware pass through.\n",
4113                         iommu->name);
4114                 return -ENXIO;
4115         }
4116         if (!ecap_sc_support(iommu->ecap) &&
4117             domain_update_iommu_snooping(iommu)) {
4118                 pr_warn("%s: Doesn't support snooping.\n",
4119                         iommu->name);
4120                 return -ENXIO;
4121         }
4122         sp = domain_update_iommu_superpage(iommu) - 1;
4123         if (sp >= 0 && !(cap_super_page_val(iommu->cap) & (1 << sp))) {
4124                 pr_warn("%s: Doesn't support large page.\n",
4125                         iommu->name);
4126                 return -ENXIO;
4127         }
4128
4129         /*
4130          * Disable translation if already enabled prior to OS handover.
4131          */
4132         if (iommu->gcmd & DMA_GCMD_TE)
4133                 iommu_disable_translation(iommu);
4134
4135         g_iommus[iommu->seq_id] = iommu;
4136         ret = iommu_init_domains(iommu);
4137         if (ret == 0)
4138                 ret = iommu_alloc_root_entry(iommu);
4139         if (ret)
4140                 goto out;
4141
4142         if (dmaru->ignored) {
4143                 /*
4144                  * we always have to disable PMRs or DMA may fail on this device
4145                  */
4146                 if (force_on)
4147                         iommu_disable_protect_mem_regions(iommu);
4148                 return 0;
4149         }
4150
4151         intel_iommu_init_qi(iommu);
4152         iommu_flush_write_buffer(iommu);
4153         ret = dmar_set_interrupt(iommu);
4154         if (ret)
4155                 goto disable_iommu;
4156
4157         iommu_set_root_entry(iommu);
4158         iommu->flush.flush_context(iommu, 0, 0, 0, DMA_CCMD_GLOBAL_INVL);
4159         iommu->flush.flush_iotlb(iommu, 0, 0, 0, DMA_TLB_GLOBAL_FLUSH);
4160         iommu_enable_translation(iommu);
4161
4162         iommu_disable_protect_mem_regions(iommu);
4163         return 0;
4164
4165 disable_iommu:
4166         disable_dmar_iommu(iommu);
4167 out:
4168         free_dmar_iommu(iommu);
4169         return ret;
4170 }
4171
4172 int dmar_iommu_hotplug(struct dmar_drhd_unit *dmaru, bool insert)
4173 {
4174         int ret = 0;
4175         struct intel_iommu *iommu = dmaru->iommu;
4176
4177         if (!intel_iommu_enabled)
4178                 return 0;
4179         if (iommu == NULL)
4180                 return -EINVAL;
4181
4182         if (insert) {
4183                 ret = intel_iommu_add(dmaru);
4184         } else {
4185                 disable_dmar_iommu(iommu);
4186                 free_dmar_iommu(iommu);
4187         }
4188
4189         return ret;
4190 }
4191
4192 static void intel_iommu_free_dmars(void)
4193 {
4194         struct dmar_rmrr_unit *rmrru, *rmrr_n;
4195         struct dmar_atsr_unit *atsru, *atsr_n;
4196
4197         list_for_each_entry_safe(rmrru, rmrr_n, &dmar_rmrr_units, list) {
4198                 list_del(&rmrru->list);
4199                 dmar_free_dev_scope(&rmrru->devices, &rmrru->devices_cnt);
4200                 kfree(rmrru);
4201         }
4202
4203         list_for_each_entry_safe(atsru, atsr_n, &dmar_atsr_units, list) {
4204                 list_del(&atsru->list);
4205                 intel_iommu_free_atsr(atsru);
4206         }
4207 }
4208
4209 int dmar_find_matched_atsr_unit(struct pci_dev *dev)
4210 {
4211         int i, ret = 1;
4212         struct pci_bus *bus;
4213         struct pci_dev *bridge = NULL;
4214         struct device *tmp;
4215         struct acpi_dmar_atsr *atsr;
4216         struct dmar_atsr_unit *atsru;
4217
4218         dev = pci_physfn(dev);
4219         for (bus = dev->bus; bus; bus = bus->parent) {
4220                 bridge = bus->self;
4221                 if (!bridge || !pci_is_pcie(bridge) ||
4222                     pci_pcie_type(bridge) == PCI_EXP_TYPE_PCI_BRIDGE)
4223                         return 0;
4224                 if (pci_pcie_type(bridge) == PCI_EXP_TYPE_ROOT_PORT)
4225                         break;
4226         }
4227         if (!bridge)
4228                 return 0;
4229
4230         rcu_read_lock();
4231         list_for_each_entry_rcu(atsru, &dmar_atsr_units, list) {
4232                 atsr = container_of(atsru->hdr, struct acpi_dmar_atsr, header);
4233                 if (atsr->segment != pci_domain_nr(dev->bus))
4234                         continue;
4235
4236                 for_each_dev_scope(atsru->devices, atsru->devices_cnt, i, tmp)
4237                         if (tmp == &bridge->dev)
4238                                 goto out;
4239
4240                 if (atsru->include_all)
4241                         goto out;
4242         }
4243         ret = 0;
4244 out:
4245         rcu_read_unlock();
4246
4247         return ret;
4248 }
4249
4250 int dmar_iommu_notify_scope_dev(struct dmar_pci_notify_info *info)
4251 {
4252         int ret = 0;
4253         struct dmar_rmrr_unit *rmrru;
4254         struct dmar_atsr_unit *atsru;
4255         struct acpi_dmar_atsr *atsr;
4256         struct acpi_dmar_reserved_memory *rmrr;
4257
4258         if (!intel_iommu_enabled && system_state != SYSTEM_BOOTING)
4259                 return 0;
4260
4261         list_for_each_entry(rmrru, &dmar_rmrr_units, list) {
4262                 rmrr = container_of(rmrru->hdr,
4263                                     struct acpi_dmar_reserved_memory, header);
4264                 if (info->event == BUS_NOTIFY_ADD_DEVICE) {
4265                         ret = dmar_insert_dev_scope(info, (void *)(rmrr + 1),
4266                                 ((void *)rmrr) + rmrr->header.length,
4267                                 rmrr->segment, rmrru->devices,
4268                                 rmrru->devices_cnt);
4269                         if(ret < 0)
4270                                 return ret;
4271                 } else if (info->event == BUS_NOTIFY_DEL_DEVICE) {
4272                         dmar_remove_dev_scope(info, rmrr->segment,
4273                                 rmrru->devices, rmrru->devices_cnt);
4274                 }
4275         }
4276
4277         list_for_each_entry(atsru, &dmar_atsr_units, list) {
4278                 if (atsru->include_all)
4279                         continue;
4280
4281                 atsr = container_of(atsru->hdr, struct acpi_dmar_atsr, header);
4282                 if (info->event == BUS_NOTIFY_ADD_DEVICE) {
4283                         ret = dmar_insert_dev_scope(info, (void *)(atsr + 1),
4284                                         (void *)atsr + atsr->header.length,
4285                                         atsr->segment, atsru->devices,
4286                                         atsru->devices_cnt);
4287                         if (ret > 0)
4288                                 break;
4289                         else if(ret < 0)
4290                                 return ret;
4291                 } else if (info->event == BUS_NOTIFY_DEL_DEVICE) {
4292                         if (dmar_remove_dev_scope(info, atsr->segment,
4293                                         atsru->devices, atsru->devices_cnt))
4294                                 break;
4295                 }
4296         }
4297
4298         return 0;
4299 }
4300
4301 /*
4302  * Here we only respond to action of unbound device from driver.
4303  *
4304  * Added device is not attached to its DMAR domain here yet. That will happen
4305  * when mapping the device to iova.
4306  */
4307 static int device_notifier(struct notifier_block *nb,
4308                                   unsigned long action, void *data)
4309 {
4310         struct device *dev = data;
4311         struct dmar_domain *domain;
4312
4313         if (iommu_dummy(dev))
4314                 return 0;
4315
4316         if (action != BUS_NOTIFY_REMOVED_DEVICE)
4317                 return 0;
4318
4319         domain = find_domain(dev);
4320         if (!domain)
4321                 return 0;
4322
4323         dmar_remove_one_dev_info(domain, dev);
4324         if (!domain_type_is_vm_or_si(domain) && list_empty(&domain->devices))
4325                 domain_exit(domain);
4326
4327         return 0;
4328 }
4329
4330 static struct notifier_block device_nb = {
4331         .notifier_call = device_notifier,
4332 };
4333
4334 static int intel_iommu_memory_notifier(struct notifier_block *nb,
4335                                        unsigned long val, void *v)
4336 {
4337         struct memory_notify *mhp = v;
4338         unsigned long long start, end;
4339         unsigned long start_vpfn, last_vpfn;
4340
4341         switch (val) {
4342         case MEM_GOING_ONLINE:
4343                 start = mhp->start_pfn << PAGE_SHIFT;
4344                 end = ((mhp->start_pfn + mhp->nr_pages) << PAGE_SHIFT) - 1;
4345                 if (iommu_domain_identity_map(si_domain, start, end)) {
4346                         pr_warn("Failed to build identity map for [%llx-%llx]\n",
4347                                 start, end);
4348                         return NOTIFY_BAD;
4349                 }
4350                 break;
4351
4352         case MEM_OFFLINE:
4353         case MEM_CANCEL_ONLINE:
4354                 start_vpfn = mm_to_dma_pfn(mhp->start_pfn);
4355                 last_vpfn = mm_to_dma_pfn(mhp->start_pfn + mhp->nr_pages - 1);
4356                 while (start_vpfn <= last_vpfn) {
4357                         struct iova *iova;
4358                         struct dmar_drhd_unit *drhd;
4359                         struct intel_iommu *iommu;
4360                         struct page *freelist;
4361
4362                         iova = find_iova(&si_domain->iovad, start_vpfn);
4363                         if (iova == NULL) {
4364                                 pr_debug("Failed get IOVA for PFN %lx\n",
4365                                          start_vpfn);
4366                                 break;
4367                         }
4368
4369                         iova = split_and_remove_iova(&si_domain->iovad, iova,
4370                                                      start_vpfn, last_vpfn);
4371                         if (iova == NULL) {
4372                                 pr_warn("Failed to split IOVA PFN [%lx-%lx]\n",
4373                                         start_vpfn, last_vpfn);
4374                                 return NOTIFY_BAD;
4375                         }
4376
4377                         freelist = domain_unmap(si_domain, iova->pfn_lo,
4378                                                iova->pfn_hi);
4379
4380                         rcu_read_lock();
4381                         for_each_active_iommu(iommu, drhd)
4382                                 iommu_flush_iotlb_psi(iommu, si_domain,
4383                                         iova->pfn_lo, iova_size(iova),
4384                                         !freelist, 0);
4385                         rcu_read_unlock();
4386                         dma_free_pagelist(freelist);
4387
4388                         start_vpfn = iova->pfn_hi + 1;
4389                         free_iova_mem(iova);
4390                 }
4391                 break;
4392         }
4393
4394         return NOTIFY_OK;
4395 }
4396
4397 static struct notifier_block intel_iommu_memory_nb = {
4398         .notifier_call = intel_iommu_memory_notifier,
4399         .priority = 0
4400 };
4401
4402
4403 static ssize_t intel_iommu_show_version(struct device *dev,
4404                                         struct device_attribute *attr,
4405                                         char *buf)
4406 {
4407         struct intel_iommu *iommu = dev_get_drvdata(dev);
4408         u32 ver = readl(iommu->reg + DMAR_VER_REG);
4409         return sprintf(buf, "%d:%d\n",
4410                        DMAR_VER_MAJOR(ver), DMAR_VER_MINOR(ver));
4411 }
4412 static DEVICE_ATTR(version, S_IRUGO, intel_iommu_show_version, NULL);
4413
4414 static ssize_t intel_iommu_show_address(struct device *dev,
4415                                         struct device_attribute *attr,
4416                                         char *buf)
4417 {
4418         struct intel_iommu *iommu = dev_get_drvdata(dev);
4419         return sprintf(buf, "%llx\n", iommu->reg_phys);
4420 }
4421 static DEVICE_ATTR(address, S_IRUGO, intel_iommu_show_address, NULL);
4422
4423 static ssize_t intel_iommu_show_cap(struct device *dev,
4424                                     struct device_attribute *attr,
4425                                     char *buf)
4426 {
4427         struct intel_iommu *iommu = dev_get_drvdata(dev);
4428         return sprintf(buf, "%llx\n", iommu->cap);
4429 }
4430 static DEVICE_ATTR(cap, S_IRUGO, intel_iommu_show_cap, NULL);
4431
4432 static ssize_t intel_iommu_show_ecap(struct device *dev,
4433                                     struct device_attribute *attr,
4434                                     char *buf)
4435 {
4436         struct intel_iommu *iommu = dev_get_drvdata(dev);
4437         return sprintf(buf, "%llx\n", iommu->ecap);
4438 }
4439 static DEVICE_ATTR(ecap, S_IRUGO, intel_iommu_show_ecap, NULL);
4440
4441 static ssize_t intel_iommu_show_ndoms(struct device *dev,
4442                                       struct device_attribute *attr,
4443                                       char *buf)
4444 {
4445         struct intel_iommu *iommu = dev_get_drvdata(dev);
4446         return sprintf(buf, "%ld\n", cap_ndoms(iommu->cap));
4447 }
4448 static DEVICE_ATTR(domains_supported, S_IRUGO, intel_iommu_show_ndoms, NULL);
4449
4450 static ssize_t intel_iommu_show_ndoms_used(struct device *dev,
4451                                            struct device_attribute *attr,
4452                                            char *buf)
4453 {
4454         struct intel_iommu *iommu = dev_get_drvdata(dev);
4455         return sprintf(buf, "%d\n", bitmap_weight(iommu->domain_ids,
4456                                                   cap_ndoms(iommu->cap)));
4457 }
4458 static DEVICE_ATTR(domains_used, S_IRUGO, intel_iommu_show_ndoms_used, NULL);
4459
4460 static struct attribute *intel_iommu_attrs[] = {
4461         &dev_attr_version.attr,
4462         &dev_attr_address.attr,
4463         &dev_attr_cap.attr,
4464         &dev_attr_ecap.attr,
4465         &dev_attr_domains_supported.attr,
4466         &dev_attr_domains_used.attr,
4467         NULL,
4468 };
4469
4470 static struct attribute_group intel_iommu_group = {
4471         .name = "intel-iommu",
4472         .attrs = intel_iommu_attrs,
4473 };
4474
4475 const struct attribute_group *intel_iommu_groups[] = {
4476         &intel_iommu_group,
4477         NULL,
4478 };
4479
4480 int __init intel_iommu_init(void)
4481 {
4482         int ret = -ENODEV;
4483         struct dmar_drhd_unit *drhd;
4484         struct intel_iommu *iommu;
4485
4486         /* VT-d is required for a TXT/tboot launch, so enforce that */
4487         force_on = tboot_force_iommu();
4488
4489         if (iommu_init_mempool()) {
4490                 if (force_on)
4491                         panic("tboot: Failed to initialize iommu memory\n");
4492                 return -ENOMEM;
4493         }
4494
4495         down_write(&dmar_global_lock);
4496         if (dmar_table_init()) {
4497                 if (force_on)
4498                         panic("tboot: Failed to initialize DMAR table\n");
4499                 goto out_free_dmar;
4500         }
4501
4502         if (dmar_dev_scope_init() < 0) {
4503                 if (force_on)
4504                         panic("tboot: Failed to initialize DMAR device scope\n");
4505                 goto out_free_dmar;
4506         }
4507
4508         if (no_iommu || dmar_disabled)
4509                 goto out_free_dmar;
4510
4511         if (list_empty(&dmar_rmrr_units))
4512                 pr_info("No RMRR found\n");
4513
4514         if (list_empty(&dmar_atsr_units))
4515                 pr_info("No ATSR found\n");
4516
4517         if (dmar_init_reserved_ranges()) {
4518                 if (force_on)
4519                         panic("tboot: Failed to reserve iommu ranges\n");
4520                 goto out_free_reserved_range;
4521         }
4522
4523         init_no_remapping_devices();
4524
4525         ret = init_dmars();
4526         if (ret) {
4527                 if (force_on)
4528                         panic("tboot: Failed to initialize DMARs\n");
4529                 pr_err("Initialization failed\n");
4530                 goto out_free_reserved_range;
4531         }
4532         up_write(&dmar_global_lock);
4533         pr_info("Intel(R) Virtualization Technology for Directed I/O\n");
4534
4535         init_timer(&unmap_timer);
4536 #ifdef CONFIG_SWIOTLB
4537         swiotlb = 0;
4538 #endif
4539         dma_ops = &intel_dma_ops;
4540
4541         init_iommu_pm_ops();
4542
4543         for_each_active_iommu(iommu, drhd)
4544                 iommu->iommu_dev = iommu_device_create(NULL, iommu,
4545                                                        intel_iommu_groups,
4546                                                        "%s", iommu->name);
4547
4548         bus_set_iommu(&pci_bus_type, &intel_iommu_ops);
4549         bus_register_notifier(&pci_bus_type, &device_nb);
4550         if (si_domain && !hw_pass_through)
4551                 register_memory_notifier(&intel_iommu_memory_nb);
4552
4553         intel_iommu_enabled = 1;
4554
4555         return 0;
4556
4557 out_free_reserved_range:
4558         put_iova_domain(&reserved_iova_list);
4559 out_free_dmar:
4560         intel_iommu_free_dmars();
4561         up_write(&dmar_global_lock);
4562         iommu_exit_mempool();
4563         return ret;
4564 }
4565
4566 static int domain_context_clear_one_cb(struct pci_dev *pdev, u16 alias, void *opaque)
4567 {
4568         struct intel_iommu *iommu = opaque;
4569
4570         domain_context_clear_one(iommu, PCI_BUS_NUM(alias), alias & 0xff);
4571         return 0;
4572 }
4573
4574 /*
4575  * NB - intel-iommu lacks any sort of reference counting for the users of
4576  * dependent devices.  If multiple endpoints have intersecting dependent
4577  * devices, unbinding the driver from any one of them will possibly leave
4578  * the others unable to operate.
4579  */
4580 static void domain_context_clear(struct intel_iommu *iommu, struct device *dev)
4581 {
4582         if (!iommu || !dev || !dev_is_pci(dev))
4583                 return;
4584
4585         pci_for_each_dma_alias(to_pci_dev(dev), &domain_context_clear_one_cb, iommu);
4586 }
4587
4588 static void __dmar_remove_one_dev_info(struct device_domain_info *info)
4589 {
4590         struct intel_iommu *iommu;
4591         unsigned long flags;
4592
4593         assert_spin_locked(&device_domain_lock);
4594
4595         if (WARN_ON(!info))
4596                 return;
4597
4598         iommu = info->iommu;
4599
4600         if (info->dev) {
4601                 iommu_disable_dev_iotlb(info);
4602                 domain_context_clear(iommu, info->dev);
4603         }
4604
4605         unlink_domain_info(info);
4606
4607         spin_lock_irqsave(&iommu->lock, flags);
4608         domain_detach_iommu(info->domain, iommu);
4609         spin_unlock_irqrestore(&iommu->lock, flags);
4610
4611         free_devinfo_mem(info);
4612 }
4613
4614 static void dmar_remove_one_dev_info(struct dmar_domain *domain,
4615                                      struct device *dev)
4616 {
4617         struct device_domain_info *info;
4618         unsigned long flags;
4619
4620         spin_lock_irqsave(&device_domain_lock, flags);
4621         info = dev->archdata.iommu;
4622         __dmar_remove_one_dev_info(info);
4623         spin_unlock_irqrestore(&device_domain_lock, flags);
4624 }
4625
4626 static int md_domain_init(struct dmar_domain *domain, int guest_width)
4627 {
4628         int adjust_width;
4629
4630         init_iova_domain(&domain->iovad, VTD_PAGE_SIZE, IOVA_START_PFN,
4631                         DMA_32BIT_PFN);
4632         domain_reserve_special_ranges(domain);
4633
4634         /* calculate AGAW */
4635         domain->gaw = guest_width;
4636         adjust_width = guestwidth_to_adjustwidth(guest_width);
4637         domain->agaw = width_to_agaw(adjust_width);
4638
4639         domain->iommu_coherency = 0;
4640         domain->iommu_snooping = 0;
4641         domain->iommu_superpage = 0;
4642         domain->max_addr = 0;
4643
4644         /* always allocate the top pgd */
4645         domain->pgd = (struct dma_pte *)alloc_pgtable_page(domain->nid);
4646         if (!domain->pgd)
4647                 return -ENOMEM;
4648         domain_flush_cache(domain, domain->pgd, PAGE_SIZE);
4649         return 0;
4650 }
4651
4652 static struct iommu_domain *intel_iommu_domain_alloc(unsigned type)
4653 {
4654         struct dmar_domain *dmar_domain;
4655         struct iommu_domain *domain;
4656
4657         if (type != IOMMU_DOMAIN_UNMANAGED)
4658                 return NULL;
4659
4660         dmar_domain = alloc_domain(DOMAIN_FLAG_VIRTUAL_MACHINE);
4661         if (!dmar_domain) {
4662                 pr_err("Can't allocate dmar_domain\n");
4663                 return NULL;
4664         }
4665         if (md_domain_init(dmar_domain, DEFAULT_DOMAIN_ADDRESS_WIDTH)) {
4666                 pr_err("Domain initialization failed\n");
4667                 domain_exit(dmar_domain);
4668                 return NULL;
4669         }
4670         domain_update_iommu_cap(dmar_domain);
4671
4672         domain = &dmar_domain->domain;
4673         domain->geometry.aperture_start = 0;
4674         domain->geometry.aperture_end   = __DOMAIN_MAX_ADDR(dmar_domain->gaw);
4675         domain->geometry.force_aperture = true;
4676
4677         return domain;
4678 }
4679
4680 static void intel_iommu_domain_free(struct iommu_domain *domain)
4681 {
4682         domain_exit(to_dmar_domain(domain));
4683 }
4684
4685 static int intel_iommu_attach_device(struct iommu_domain *domain,
4686                                      struct device *dev)
4687 {
4688         struct dmar_domain *dmar_domain = to_dmar_domain(domain);
4689         struct intel_iommu *iommu;
4690         int addr_width;
4691         u8 bus, devfn;
4692
4693         if (device_is_rmrr_locked(dev)) {
4694                 dev_warn(dev, "Device is ineligible for IOMMU domain attach due to platform RMRR requirement.  Contact your platform vendor.\n");
4695                 return -EPERM;
4696         }
4697
4698         /* normally dev is not mapped */
4699         if (unlikely(domain_context_mapped(dev))) {
4700                 struct dmar_domain *old_domain;
4701
4702                 old_domain = find_domain(dev);
4703                 if (old_domain) {
4704                         rcu_read_lock();
4705                         dmar_remove_one_dev_info(old_domain, dev);
4706                         rcu_read_unlock();
4707
4708                         if (!domain_type_is_vm_or_si(old_domain) &&
4709                              list_empty(&old_domain->devices))
4710                                 domain_exit(old_domain);
4711                 }
4712         }
4713
4714         iommu = device_to_iommu(dev, &bus, &devfn);
4715         if (!iommu)
4716                 return -ENODEV;
4717
4718         /* check if this iommu agaw is sufficient for max mapped address */
4719         addr_width = agaw_to_width(iommu->agaw);
4720         if (addr_width > cap_mgaw(iommu->cap))
4721                 addr_width = cap_mgaw(iommu->cap);
4722
4723         if (dmar_domain->max_addr > (1LL << addr_width)) {
4724                 pr_err("%s: iommu width (%d) is not "
4725                        "sufficient for the mapped address (%llx)\n",
4726                        __func__, addr_width, dmar_domain->max_addr);
4727                 return -EFAULT;
4728         }
4729         dmar_domain->gaw = addr_width;
4730
4731         /*
4732          * Knock out extra levels of page tables if necessary
4733          */
4734         while (iommu->agaw < dmar_domain->agaw) {
4735                 struct dma_pte *pte;
4736
4737                 pte = dmar_domain->pgd;
4738                 if (dma_pte_present(pte)) {
4739                         dmar_domain->pgd = (struct dma_pte *)
4740                                 phys_to_virt(dma_pte_addr(pte));
4741                         free_pgtable_page(pte);
4742                 }
4743                 dmar_domain->agaw--;
4744         }
4745
4746         return domain_add_dev_info(dmar_domain, dev);
4747 }
4748
4749 static void intel_iommu_detach_device(struct iommu_domain *domain,
4750                                       struct device *dev)
4751 {
4752         dmar_remove_one_dev_info(to_dmar_domain(domain), dev);
4753 }
4754
4755 static int intel_iommu_map(struct iommu_domain *domain,
4756                            unsigned long iova, phys_addr_t hpa,
4757                            size_t size, int iommu_prot)
4758 {
4759         struct dmar_domain *dmar_domain = to_dmar_domain(domain);
4760         u64 max_addr;
4761         int prot = 0;
4762         int ret;
4763
4764         if (iommu_prot & IOMMU_READ)
4765                 prot |= DMA_PTE_READ;
4766         if (iommu_prot & IOMMU_WRITE)
4767                 prot |= DMA_PTE_WRITE;
4768         if ((iommu_prot & IOMMU_CACHE) && dmar_domain->iommu_snooping)
4769                 prot |= DMA_PTE_SNP;
4770
4771         max_addr = iova + size;
4772         if (dmar_domain->max_addr < max_addr) {
4773                 u64 end;
4774
4775                 /* check if minimum agaw is sufficient for mapped address */
4776                 end = __DOMAIN_MAX_ADDR(dmar_domain->gaw) + 1;
4777                 if (end < max_addr) {
4778                         pr_err("%s: iommu width (%d) is not "
4779                                "sufficient for the mapped address (%llx)\n",
4780                                __func__, dmar_domain->gaw, max_addr);
4781                         return -EFAULT;
4782                 }
4783                 dmar_domain->max_addr = max_addr;
4784         }
4785         /* Round up size to next multiple of PAGE_SIZE, if it and
4786            the low bits of hpa would take us onto the next page */
4787         size = aligned_nrpages(hpa, size);
4788         ret = domain_pfn_mapping(dmar_domain, iova >> VTD_PAGE_SHIFT,
4789                                  hpa >> VTD_PAGE_SHIFT, size, prot);
4790         return ret;
4791 }
4792
4793 static size_t intel_iommu_unmap(struct iommu_domain *domain,
4794                                 unsigned long iova, size_t size)
4795 {
4796         struct dmar_domain *dmar_domain = to_dmar_domain(domain);
4797         struct page *freelist = NULL;
4798         struct intel_iommu *iommu;
4799         unsigned long start_pfn, last_pfn;
4800         unsigned int npages;
4801         int iommu_id, level = 0;
4802
4803         /* Cope with horrid API which requires us to unmap more than the
4804            size argument if it happens to be a large-page mapping. */
4805         BUG_ON(!pfn_to_dma_pte(dmar_domain, iova >> VTD_PAGE_SHIFT, &level));
4806
4807         if (size < VTD_PAGE_SIZE << level_to_offset_bits(level))
4808                 size = VTD_PAGE_SIZE << level_to_offset_bits(level);
4809
4810         start_pfn = iova >> VTD_PAGE_SHIFT;
4811         last_pfn = (iova + size - 1) >> VTD_PAGE_SHIFT;
4812
4813         freelist = domain_unmap(dmar_domain, start_pfn, last_pfn);
4814
4815         npages = last_pfn - start_pfn + 1;
4816
4817         for_each_domain_iommu(iommu_id, dmar_domain) {
4818                 iommu = g_iommus[iommu_id];
4819
4820                 iommu_flush_iotlb_psi(g_iommus[iommu_id], dmar_domain,
4821                                       start_pfn, npages, !freelist, 0);
4822         }
4823
4824         dma_free_pagelist(freelist);
4825
4826         if (dmar_domain->max_addr == iova + size)
4827                 dmar_domain->max_addr = iova;
4828
4829         return size;
4830 }
4831
4832 static phys_addr_t intel_iommu_iova_to_phys(struct iommu_domain *domain,
4833                                             dma_addr_t iova)
4834 {
4835         struct dmar_domain *dmar_domain = to_dmar_domain(domain);
4836         struct dma_pte *pte;
4837         int level = 0;
4838         u64 phys = 0;
4839
4840         pte = pfn_to_dma_pte(dmar_domain, iova >> VTD_PAGE_SHIFT, &level);
4841         if (pte)
4842                 phys = dma_pte_addr(pte);
4843
4844         return phys;
4845 }
4846
4847 static bool intel_iommu_capable(enum iommu_cap cap)
4848 {
4849         if (cap == IOMMU_CAP_CACHE_COHERENCY)
4850                 return domain_update_iommu_snooping(NULL) == 1;
4851         if (cap == IOMMU_CAP_INTR_REMAP)
4852                 return irq_remapping_enabled == 1;
4853
4854         return false;
4855 }
4856
4857 static int intel_iommu_add_device(struct device *dev)
4858 {
4859         struct intel_iommu *iommu;
4860         struct iommu_group *group;
4861         u8 bus, devfn;
4862
4863         iommu = device_to_iommu(dev, &bus, &devfn);
4864         if (!iommu)
4865                 return -ENODEV;
4866
4867         iommu_device_link(iommu->iommu_dev, dev);
4868
4869         group = iommu_group_get_for_dev(dev);
4870
4871         if (IS_ERR(group))
4872                 return PTR_ERR(group);
4873
4874         iommu_group_put(group);
4875         return 0;
4876 }
4877
4878 static void intel_iommu_remove_device(struct device *dev)
4879 {
4880         struct intel_iommu *iommu;
4881         u8 bus, devfn;
4882
4883         iommu = device_to_iommu(dev, &bus, &devfn);
4884         if (!iommu)
4885                 return;
4886
4887         iommu_group_remove_device(dev);
4888
4889         iommu_device_unlink(iommu->iommu_dev, dev);
4890 }
4891
4892 static const struct iommu_ops intel_iommu_ops = {
4893         .capable        = intel_iommu_capable,
4894         .domain_alloc   = intel_iommu_domain_alloc,
4895         .domain_free    = intel_iommu_domain_free,
4896         .attach_dev     = intel_iommu_attach_device,
4897         .detach_dev     = intel_iommu_detach_device,
4898         .map            = intel_iommu_map,
4899         .unmap          = intel_iommu_unmap,
4900         .map_sg         = default_iommu_map_sg,
4901         .iova_to_phys   = intel_iommu_iova_to_phys,
4902         .add_device     = intel_iommu_add_device,
4903         .remove_device  = intel_iommu_remove_device,
4904         .device_group   = pci_device_group,
4905         .pgsize_bitmap  = INTEL_IOMMU_PGSIZES,
4906 };
4907
4908 static void quirk_iommu_g4x_gfx(struct pci_dev *dev)
4909 {
4910         /* G4x/GM45 integrated gfx dmar support is totally busted. */
4911         pr_info("Disabling IOMMU for graphics on this chipset\n");
4912         dmar_map_gfx = 0;
4913 }
4914
4915 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2a40, quirk_iommu_g4x_gfx);
4916 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e00, quirk_iommu_g4x_gfx);
4917 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e10, quirk_iommu_g4x_gfx);
4918 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e20, quirk_iommu_g4x_gfx);
4919 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e30, quirk_iommu_g4x_gfx);
4920 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e40, quirk_iommu_g4x_gfx);
4921 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e90, quirk_iommu_g4x_gfx);
4922
4923 static void quirk_iommu_rwbf(struct pci_dev *dev)
4924 {
4925         /*
4926          * Mobile 4 Series Chipset neglects to set RWBF capability,
4927          * but needs it. Same seems to hold for the desktop versions.
4928          */
4929         pr_info("Forcing write-buffer flush capability\n");
4930         rwbf_quirk = 1;
4931 }
4932
4933 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2a40, quirk_iommu_rwbf);
4934 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e00, quirk_iommu_rwbf);
4935 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e10, quirk_iommu_rwbf);
4936 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e20, quirk_iommu_rwbf);
4937 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e30, quirk_iommu_rwbf);
4938 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e40, quirk_iommu_rwbf);
4939 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e90, quirk_iommu_rwbf);
4940
4941 #define GGC 0x52
4942 #define GGC_MEMORY_SIZE_MASK    (0xf << 8)
4943 #define GGC_MEMORY_SIZE_NONE    (0x0 << 8)
4944 #define GGC_MEMORY_SIZE_1M      (0x1 << 8)
4945 #define GGC_MEMORY_SIZE_2M      (0x3 << 8)
4946 #define GGC_MEMORY_VT_ENABLED   (0x8 << 8)
4947 #define GGC_MEMORY_SIZE_2M_VT   (0x9 << 8)
4948 #define GGC_MEMORY_SIZE_3M_VT   (0xa << 8)
4949 #define GGC_MEMORY_SIZE_4M_VT   (0xb << 8)
4950
4951 static void quirk_calpella_no_shadow_gtt(struct pci_dev *dev)
4952 {
4953         unsigned short ggc;
4954
4955         if (pci_read_config_word(dev, GGC, &ggc))
4956                 return;
4957
4958         if (!(ggc & GGC_MEMORY_VT_ENABLED)) {
4959                 pr_info("BIOS has allocated no shadow GTT; disabling IOMMU for graphics\n");
4960                 dmar_map_gfx = 0;
4961         } else if (dmar_map_gfx) {
4962                 /* we have to ensure the gfx device is idle before we flush */
4963                 pr_info("Disabling batched IOTLB flush on Ironlake\n");
4964                 intel_iommu_strict = 1;
4965        }
4966 }
4967 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x0040, quirk_calpella_no_shadow_gtt);
4968 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x0044, quirk_calpella_no_shadow_gtt);
4969 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x0062, quirk_calpella_no_shadow_gtt);
4970 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x006a, quirk_calpella_no_shadow_gtt);
4971
4972 /* On Tylersburg chipsets, some BIOSes have been known to enable the
4973    ISOCH DMAR unit for the Azalia sound device, but not give it any
4974    TLB entries, which causes it to deadlock. Check for that.  We do
4975    this in a function called from init_dmars(), instead of in a PCI
4976    quirk, because we don't want to print the obnoxious "BIOS broken"
4977    message if VT-d is actually disabled.
4978 */
4979 static void __init check_tylersburg_isoch(void)
4980 {
4981         struct pci_dev *pdev;
4982         uint32_t vtisochctrl;
4983
4984         /* If there's no Azalia in the system anyway, forget it. */
4985         pdev = pci_get_device(PCI_VENDOR_ID_INTEL, 0x3a3e, NULL);
4986         if (!pdev)
4987                 return;
4988         pci_dev_put(pdev);
4989
4990         /* System Management Registers. Might be hidden, in which case
4991            we can't do the sanity check. But that's OK, because the
4992            known-broken BIOSes _don't_ actually hide it, so far. */
4993         pdev = pci_get_device(PCI_VENDOR_ID_INTEL, 0x342e, NULL);
4994         if (!pdev)
4995                 return;
4996
4997         if (pci_read_config_dword(pdev, 0x188, &vtisochctrl)) {
4998                 pci_dev_put(pdev);
4999                 return;
5000         }
5001
5002         pci_dev_put(pdev);
5003
5004         /* If Azalia DMA is routed to the non-isoch DMAR unit, fine. */
5005         if (vtisochctrl & 1)
5006                 return;
5007
5008         /* Drop all bits other than the number of TLB entries */
5009         vtisochctrl &= 0x1c;
5010
5011         /* If we have the recommended number of TLB entries (16), fine. */
5012         if (vtisochctrl == 0x10)
5013                 return;
5014
5015         /* Zero TLB entries? You get to ride the short bus to school. */
5016         if (!vtisochctrl) {
5017                 WARN(1, "Your BIOS is broken; DMA routed to ISOCH DMAR unit but no TLB space.\n"
5018                      "BIOS vendor: %s; Ver: %s; Product Version: %s\n",
5019                      dmi_get_system_info(DMI_BIOS_VENDOR),
5020                      dmi_get_system_info(DMI_BIOS_VERSION),
5021                      dmi_get_system_info(DMI_PRODUCT_VERSION));
5022                 iommu_identity_mapping |= IDENTMAP_AZALIA;
5023                 return;
5024         }
5025
5026         pr_warn("Recommended TLB entries for ISOCH unit is 16; your BIOS set %d\n",
5027                vtisochctrl);
5028 }