x86, intel_txt: clean up the impact on generic code, unbreak non-x86
[linux-2.6.git] / drivers / pci / intel-iommu.c
1 /*
2  * Copyright (c) 2006, 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  * You should have received a copy of the GNU General Public License along with
14  * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
15  * Place - Suite 330, Boston, MA 02111-1307 USA.
16  *
17  * Copyright (C) 2006-2008 Intel Corporation
18  * Author: Ashok Raj <ashok.raj@intel.com>
19  * Author: Shaohua Li <shaohua.li@intel.com>
20  * Author: Anil S Keshavamurthy <anil.s.keshavamurthy@intel.com>
21  * Author: Fenghua Yu <fenghua.yu@intel.com>
22  */
23
24 #include <linux/init.h>
25 #include <linux/bitmap.h>
26 #include <linux/debugfs.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/timer.h>
36 #include <linux/iova.h>
37 #include <linux/iommu.h>
38 #include <linux/intel-iommu.h>
39 #include <linux/sysdev.h>
40 #include <linux/tboot.h>
41 #include <asm/cacheflush.h>
42 #include <asm/iommu.h>
43 #include "pci.h"
44
45 #define ROOT_SIZE               VTD_PAGE_SIZE
46 #define CONTEXT_SIZE            VTD_PAGE_SIZE
47
48 #define IS_GFX_DEVICE(pdev) ((pdev->class >> 16) == PCI_BASE_CLASS_DISPLAY)
49 #define IS_ISA_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_BRIDGE_ISA)
50
51 #define IOAPIC_RANGE_START      (0xfee00000)
52 #define IOAPIC_RANGE_END        (0xfeefffff)
53 #define IOVA_START_ADDR         (0x1000)
54
55 #define DEFAULT_DOMAIN_ADDRESS_WIDTH 48
56
57 #define MAX_AGAW_WIDTH 64
58
59 #define DOMAIN_MAX_ADDR(gaw) ((((u64)1) << gaw) - 1)
60 #define DOMAIN_MAX_PFN(gaw)  ((((u64)1) << (gaw-VTD_PAGE_SHIFT)) - 1)
61
62 #define IOVA_PFN(addr)          ((addr) >> PAGE_SHIFT)
63 #define DMA_32BIT_PFN           IOVA_PFN(DMA_BIT_MASK(32))
64 #define DMA_64BIT_PFN           IOVA_PFN(DMA_BIT_MASK(64))
65
66
67 /* VT-d pages must always be _smaller_ than MM pages. Otherwise things
68    are never going to work. */
69 static inline unsigned long dma_to_mm_pfn(unsigned long dma_pfn)
70 {
71         return dma_pfn >> (PAGE_SHIFT - VTD_PAGE_SHIFT);
72 }
73
74 static inline unsigned long mm_to_dma_pfn(unsigned long mm_pfn)
75 {
76         return mm_pfn << (PAGE_SHIFT - VTD_PAGE_SHIFT);
77 }
78 static inline unsigned long page_to_dma_pfn(struct page *pg)
79 {
80         return mm_to_dma_pfn(page_to_pfn(pg));
81 }
82 static inline unsigned long virt_to_dma_pfn(void *p)
83 {
84         return page_to_dma_pfn(virt_to_page(p));
85 }
86
87 /* global iommu list, set NULL for ignored DMAR units */
88 static struct intel_iommu **g_iommus;
89
90 static int rwbf_quirk;
91
92 /*
93  * 0: Present
94  * 1-11: Reserved
95  * 12-63: Context Ptr (12 - (haw-1))
96  * 64-127: Reserved
97  */
98 struct root_entry {
99         u64     val;
100         u64     rsvd1;
101 };
102 #define ROOT_ENTRY_NR (VTD_PAGE_SIZE/sizeof(struct root_entry))
103 static inline bool root_present(struct root_entry *root)
104 {
105         return (root->val & 1);
106 }
107 static inline void set_root_present(struct root_entry *root)
108 {
109         root->val |= 1;
110 }
111 static inline void set_root_value(struct root_entry *root, unsigned long value)
112 {
113         root->val |= value & VTD_PAGE_MASK;
114 }
115
116 static inline struct context_entry *
117 get_context_addr_from_root(struct root_entry *root)
118 {
119         return (struct context_entry *)
120                 (root_present(root)?phys_to_virt(
121                 root->val & VTD_PAGE_MASK) :
122                 NULL);
123 }
124
125 /*
126  * low 64 bits:
127  * 0: present
128  * 1: fault processing disable
129  * 2-3: translation type
130  * 12-63: address space root
131  * high 64 bits:
132  * 0-2: address width
133  * 3-6: aval
134  * 8-23: domain id
135  */
136 struct context_entry {
137         u64 lo;
138         u64 hi;
139 };
140
141 static inline bool context_present(struct context_entry *context)
142 {
143         return (context->lo & 1);
144 }
145 static inline void context_set_present(struct context_entry *context)
146 {
147         context->lo |= 1;
148 }
149
150 static inline void context_set_fault_enable(struct context_entry *context)
151 {
152         context->lo &= (((u64)-1) << 2) | 1;
153 }
154
155 static inline void context_set_translation_type(struct context_entry *context,
156                                                 unsigned long value)
157 {
158         context->lo &= (((u64)-1) << 4) | 3;
159         context->lo |= (value & 3) << 2;
160 }
161
162 static inline void context_set_address_root(struct context_entry *context,
163                                             unsigned long value)
164 {
165         context->lo |= value & VTD_PAGE_MASK;
166 }
167
168 static inline void context_set_address_width(struct context_entry *context,
169                                              unsigned long value)
170 {
171         context->hi |= value & 7;
172 }
173
174 static inline void context_set_domain_id(struct context_entry *context,
175                                          unsigned long value)
176 {
177         context->hi |= (value & ((1 << 16) - 1)) << 8;
178 }
179
180 static inline void context_clear_entry(struct context_entry *context)
181 {
182         context->lo = 0;
183         context->hi = 0;
184 }
185
186 /*
187  * 0: readable
188  * 1: writable
189  * 2-6: reserved
190  * 7: super page
191  * 8-10: available
192  * 11: snoop behavior
193  * 12-63: Host physcial address
194  */
195 struct dma_pte {
196         u64 val;
197 };
198
199 static inline void dma_clear_pte(struct dma_pte *pte)
200 {
201         pte->val = 0;
202 }
203
204 static inline void dma_set_pte_readable(struct dma_pte *pte)
205 {
206         pte->val |= DMA_PTE_READ;
207 }
208
209 static inline void dma_set_pte_writable(struct dma_pte *pte)
210 {
211         pte->val |= DMA_PTE_WRITE;
212 }
213
214 static inline void dma_set_pte_snp(struct dma_pte *pte)
215 {
216         pte->val |= DMA_PTE_SNP;
217 }
218
219 static inline void dma_set_pte_prot(struct dma_pte *pte, unsigned long prot)
220 {
221         pte->val = (pte->val & ~3) | (prot & 3);
222 }
223
224 static inline u64 dma_pte_addr(struct dma_pte *pte)
225 {
226 #ifdef CONFIG_64BIT
227         return pte->val & VTD_PAGE_MASK;
228 #else
229         /* Must have a full atomic 64-bit read */
230         return  __cmpxchg64(pte, 0ULL, 0ULL) & VTD_PAGE_MASK;
231 #endif
232 }
233
234 static inline void dma_set_pte_pfn(struct dma_pte *pte, unsigned long pfn)
235 {
236         pte->val |= (uint64_t)pfn << VTD_PAGE_SHIFT;
237 }
238
239 static inline bool dma_pte_present(struct dma_pte *pte)
240 {
241         return (pte->val & 3) != 0;
242 }
243
244 static inline int first_pte_in_page(struct dma_pte *pte)
245 {
246         return !((unsigned long)pte & ~VTD_PAGE_MASK);
247 }
248
249 /*
250  * This domain is a statically identity mapping domain.
251  *      1. This domain creats a static 1:1 mapping to all usable memory.
252  *      2. It maps to each iommu if successful.
253  *      3. Each iommu mapps to this domain if successful.
254  */
255 struct dmar_domain *si_domain;
256
257 /* devices under the same p2p bridge are owned in one domain */
258 #define DOMAIN_FLAG_P2P_MULTIPLE_DEVICES (1 << 0)
259
260 /* domain represents a virtual machine, more than one devices
261  * across iommus may be owned in one domain, e.g. kvm guest.
262  */
263 #define DOMAIN_FLAG_VIRTUAL_MACHINE     (1 << 1)
264
265 /* si_domain contains mulitple devices */
266 #define DOMAIN_FLAG_STATIC_IDENTITY     (1 << 2)
267
268 struct dmar_domain {
269         int     id;                     /* domain id */
270         unsigned long iommu_bmp;        /* bitmap of iommus this domain uses*/
271
272         struct list_head devices;       /* all devices' list */
273         struct iova_domain iovad;       /* iova's that belong to this domain */
274
275         struct dma_pte  *pgd;           /* virtual address */
276         int             gaw;            /* max guest address width */
277
278         /* adjusted guest address width, 0 is level 2 30-bit */
279         int             agaw;
280
281         int             flags;          /* flags to find out type of domain */
282
283         int             iommu_coherency;/* indicate coherency of iommu access */
284         int             iommu_snooping; /* indicate snooping control feature*/
285         int             iommu_count;    /* reference count of iommu */
286         spinlock_t      iommu_lock;     /* protect iommu set in domain */
287         u64             max_addr;       /* maximum mapped address */
288 };
289
290 /* PCI domain-device relationship */
291 struct device_domain_info {
292         struct list_head link;  /* link to domain siblings */
293         struct list_head global; /* link to global list */
294         int segment;            /* PCI domain */
295         u8 bus;                 /* PCI bus number */
296         u8 devfn;               /* PCI devfn number */
297         struct pci_dev *dev; /* it's NULL for PCIE-to-PCI bridge */
298         struct intel_iommu *iommu; /* IOMMU used by this device */
299         struct dmar_domain *domain; /* pointer to domain */
300 };
301
302 static void flush_unmaps_timeout(unsigned long data);
303
304 DEFINE_TIMER(unmap_timer,  flush_unmaps_timeout, 0, 0);
305
306 #define HIGH_WATER_MARK 250
307 struct deferred_flush_tables {
308         int next;
309         struct iova *iova[HIGH_WATER_MARK];
310         struct dmar_domain *domain[HIGH_WATER_MARK];
311 };
312
313 static struct deferred_flush_tables *deferred_flush;
314
315 /* bitmap for indexing intel_iommus */
316 static int g_num_of_iommus;
317
318 static DEFINE_SPINLOCK(async_umap_flush_lock);
319 static LIST_HEAD(unmaps_to_do);
320
321 static int timer_on;
322 static long list_size;
323
324 static void domain_remove_dev_info(struct dmar_domain *domain);
325
326 #ifdef CONFIG_DMAR_DEFAULT_ON
327 int dmar_disabled = 0;
328 #else
329 int dmar_disabled = 1;
330 #endif /*CONFIG_DMAR_DEFAULT_ON*/
331
332 static int __initdata dmar_map_gfx = 1;
333 static int dmar_forcedac;
334 static int intel_iommu_strict;
335
336 #define DUMMY_DEVICE_DOMAIN_INFO ((struct device_domain_info *)(-1))
337 static DEFINE_SPINLOCK(device_domain_lock);
338 static LIST_HEAD(device_domain_list);
339
340 static struct iommu_ops intel_iommu_ops;
341
342 static int __init intel_iommu_setup(char *str)
343 {
344         if (!str)
345                 return -EINVAL;
346         while (*str) {
347                 if (!strncmp(str, "on", 2)) {
348                         dmar_disabled = 0;
349                         printk(KERN_INFO "Intel-IOMMU: enabled\n");
350                 } else if (!strncmp(str, "off", 3)) {
351                         dmar_disabled = 1;
352                         printk(KERN_INFO "Intel-IOMMU: disabled\n");
353                 } else if (!strncmp(str, "igfx_off", 8)) {
354                         dmar_map_gfx = 0;
355                         printk(KERN_INFO
356                                 "Intel-IOMMU: disable GFX device mapping\n");
357                 } else if (!strncmp(str, "forcedac", 8)) {
358                         printk(KERN_INFO
359                                 "Intel-IOMMU: Forcing DAC for PCI devices\n");
360                         dmar_forcedac = 1;
361                 } else if (!strncmp(str, "strict", 6)) {
362                         printk(KERN_INFO
363                                 "Intel-IOMMU: disable batched IOTLB flush\n");
364                         intel_iommu_strict = 1;
365                 }
366
367                 str += strcspn(str, ",");
368                 while (*str == ',')
369                         str++;
370         }
371         return 0;
372 }
373 __setup("intel_iommu=", intel_iommu_setup);
374
375 static struct kmem_cache *iommu_domain_cache;
376 static struct kmem_cache *iommu_devinfo_cache;
377 static struct kmem_cache *iommu_iova_cache;
378
379 static inline void *iommu_kmem_cache_alloc(struct kmem_cache *cachep)
380 {
381         unsigned int flags;
382         void *vaddr;
383
384         /* trying to avoid low memory issues */
385         flags = current->flags & PF_MEMALLOC;
386         current->flags |= PF_MEMALLOC;
387         vaddr = kmem_cache_alloc(cachep, GFP_ATOMIC);
388         current->flags &= (~PF_MEMALLOC | flags);
389         return vaddr;
390 }
391
392
393 static inline void *alloc_pgtable_page(void)
394 {
395         unsigned int flags;
396         void *vaddr;
397
398         /* trying to avoid low memory issues */
399         flags = current->flags & PF_MEMALLOC;
400         current->flags |= PF_MEMALLOC;
401         vaddr = (void *)get_zeroed_page(GFP_ATOMIC);
402         current->flags &= (~PF_MEMALLOC | flags);
403         return vaddr;
404 }
405
406 static inline void free_pgtable_page(void *vaddr)
407 {
408         free_page((unsigned long)vaddr);
409 }
410
411 static inline void *alloc_domain_mem(void)
412 {
413         return iommu_kmem_cache_alloc(iommu_domain_cache);
414 }
415
416 static void free_domain_mem(void *vaddr)
417 {
418         kmem_cache_free(iommu_domain_cache, vaddr);
419 }
420
421 static inline void * alloc_devinfo_mem(void)
422 {
423         return iommu_kmem_cache_alloc(iommu_devinfo_cache);
424 }
425
426 static inline void free_devinfo_mem(void *vaddr)
427 {
428         kmem_cache_free(iommu_devinfo_cache, vaddr);
429 }
430
431 struct iova *alloc_iova_mem(void)
432 {
433         return iommu_kmem_cache_alloc(iommu_iova_cache);
434 }
435
436 void free_iova_mem(struct iova *iova)
437 {
438         kmem_cache_free(iommu_iova_cache, iova);
439 }
440
441
442 static inline int width_to_agaw(int width);
443
444 static int __iommu_calculate_agaw(struct intel_iommu *iommu, int max_gaw)
445 {
446         unsigned long sagaw;
447         int agaw = -1;
448
449         sagaw = cap_sagaw(iommu->cap);
450         for (agaw = width_to_agaw(max_gaw);
451              agaw >= 0; agaw--) {
452                 if (test_bit(agaw, &sagaw))
453                         break;
454         }
455
456         return agaw;
457 }
458
459 /*
460  * Calculate max SAGAW for each iommu.
461  */
462 int iommu_calculate_max_sagaw(struct intel_iommu *iommu)
463 {
464         return __iommu_calculate_agaw(iommu, MAX_AGAW_WIDTH);
465 }
466
467 /*
468  * calculate agaw for each iommu.
469  * "SAGAW" may be different across iommus, use a default agaw, and
470  * get a supported less agaw for iommus that don't support the default agaw.
471  */
472 int iommu_calculate_agaw(struct intel_iommu *iommu)
473 {
474         return __iommu_calculate_agaw(iommu, DEFAULT_DOMAIN_ADDRESS_WIDTH);
475 }
476
477 /* This functionin only returns single iommu in a domain */
478 static struct intel_iommu *domain_get_iommu(struct dmar_domain *domain)
479 {
480         int iommu_id;
481
482         /* si_domain and vm domain should not get here. */
483         BUG_ON(domain->flags & DOMAIN_FLAG_VIRTUAL_MACHINE);
484         BUG_ON(domain->flags & DOMAIN_FLAG_STATIC_IDENTITY);
485
486         iommu_id = find_first_bit(&domain->iommu_bmp, g_num_of_iommus);
487         if (iommu_id < 0 || iommu_id >= g_num_of_iommus)
488                 return NULL;
489
490         return g_iommus[iommu_id];
491 }
492
493 static void domain_update_iommu_coherency(struct dmar_domain *domain)
494 {
495         int i;
496
497         domain->iommu_coherency = 1;
498
499         i = find_first_bit(&domain->iommu_bmp, g_num_of_iommus);
500         for (; i < g_num_of_iommus; ) {
501                 if (!ecap_coherent(g_iommus[i]->ecap)) {
502                         domain->iommu_coherency = 0;
503                         break;
504                 }
505                 i = find_next_bit(&domain->iommu_bmp, g_num_of_iommus, i+1);
506         }
507 }
508
509 static void domain_update_iommu_snooping(struct dmar_domain *domain)
510 {
511         int i;
512
513         domain->iommu_snooping = 1;
514
515         i = find_first_bit(&domain->iommu_bmp, g_num_of_iommus);
516         for (; i < g_num_of_iommus; ) {
517                 if (!ecap_sc_support(g_iommus[i]->ecap)) {
518                         domain->iommu_snooping = 0;
519                         break;
520                 }
521                 i = find_next_bit(&domain->iommu_bmp, g_num_of_iommus, i+1);
522         }
523 }
524
525 /* Some capabilities may be different across iommus */
526 static void domain_update_iommu_cap(struct dmar_domain *domain)
527 {
528         domain_update_iommu_coherency(domain);
529         domain_update_iommu_snooping(domain);
530 }
531
532 static struct intel_iommu *device_to_iommu(int segment, u8 bus, u8 devfn)
533 {
534         struct dmar_drhd_unit *drhd = NULL;
535         int i;
536
537         for_each_drhd_unit(drhd) {
538                 if (drhd->ignored)
539                         continue;
540                 if (segment != drhd->segment)
541                         continue;
542
543                 for (i = 0; i < drhd->devices_cnt; i++) {
544                         if (drhd->devices[i] &&
545                             drhd->devices[i]->bus->number == bus &&
546                             drhd->devices[i]->devfn == devfn)
547                                 return drhd->iommu;
548                         if (drhd->devices[i] &&
549                             drhd->devices[i]->subordinate &&
550                             drhd->devices[i]->subordinate->number <= bus &&
551                             drhd->devices[i]->subordinate->subordinate >= bus)
552                                 return drhd->iommu;
553                 }
554
555                 if (drhd->include_all)
556                         return drhd->iommu;
557         }
558
559         return NULL;
560 }
561
562 static void domain_flush_cache(struct dmar_domain *domain,
563                                void *addr, int size)
564 {
565         if (!domain->iommu_coherency)
566                 clflush_cache_range(addr, size);
567 }
568
569 /* Gets context entry for a given bus and devfn */
570 static struct context_entry * device_to_context_entry(struct intel_iommu *iommu,
571                 u8 bus, u8 devfn)
572 {
573         struct root_entry *root;
574         struct context_entry *context;
575         unsigned long phy_addr;
576         unsigned long flags;
577
578         spin_lock_irqsave(&iommu->lock, flags);
579         root = &iommu->root_entry[bus];
580         context = get_context_addr_from_root(root);
581         if (!context) {
582                 context = (struct context_entry *)alloc_pgtable_page();
583                 if (!context) {
584                         spin_unlock_irqrestore(&iommu->lock, flags);
585                         return NULL;
586                 }
587                 __iommu_flush_cache(iommu, (void *)context, CONTEXT_SIZE);
588                 phy_addr = virt_to_phys((void *)context);
589                 set_root_value(root, phy_addr);
590                 set_root_present(root);
591                 __iommu_flush_cache(iommu, root, sizeof(*root));
592         }
593         spin_unlock_irqrestore(&iommu->lock, flags);
594         return &context[devfn];
595 }
596
597 static int device_context_mapped(struct intel_iommu *iommu, u8 bus, u8 devfn)
598 {
599         struct root_entry *root;
600         struct context_entry *context;
601         int ret;
602         unsigned long flags;
603
604         spin_lock_irqsave(&iommu->lock, flags);
605         root = &iommu->root_entry[bus];
606         context = get_context_addr_from_root(root);
607         if (!context) {
608                 ret = 0;
609                 goto out;
610         }
611         ret = context_present(&context[devfn]);
612 out:
613         spin_unlock_irqrestore(&iommu->lock, flags);
614         return ret;
615 }
616
617 static void clear_context_table(struct intel_iommu *iommu, u8 bus, u8 devfn)
618 {
619         struct root_entry *root;
620         struct context_entry *context;
621         unsigned long flags;
622
623         spin_lock_irqsave(&iommu->lock, flags);
624         root = &iommu->root_entry[bus];
625         context = get_context_addr_from_root(root);
626         if (context) {
627                 context_clear_entry(&context[devfn]);
628                 __iommu_flush_cache(iommu, &context[devfn], \
629                         sizeof(*context));
630         }
631         spin_unlock_irqrestore(&iommu->lock, flags);
632 }
633
634 static void free_context_table(struct intel_iommu *iommu)
635 {
636         struct root_entry *root;
637         int i;
638         unsigned long flags;
639         struct context_entry *context;
640
641         spin_lock_irqsave(&iommu->lock, flags);
642         if (!iommu->root_entry) {
643                 goto out;
644         }
645         for (i = 0; i < ROOT_ENTRY_NR; i++) {
646                 root = &iommu->root_entry[i];
647                 context = get_context_addr_from_root(root);
648                 if (context)
649                         free_pgtable_page(context);
650         }
651         free_pgtable_page(iommu->root_entry);
652         iommu->root_entry = NULL;
653 out:
654         spin_unlock_irqrestore(&iommu->lock, flags);
655 }
656
657 /* page table handling */
658 #define LEVEL_STRIDE            (9)
659 #define LEVEL_MASK              (((u64)1 << LEVEL_STRIDE) - 1)
660
661 static inline int agaw_to_level(int agaw)
662 {
663         return agaw + 2;
664 }
665
666 static inline int agaw_to_width(int agaw)
667 {
668         return 30 + agaw * LEVEL_STRIDE;
669
670 }
671
672 static inline int width_to_agaw(int width)
673 {
674         return (width - 30) / LEVEL_STRIDE;
675 }
676
677 static inline unsigned int level_to_offset_bits(int level)
678 {
679         return (level - 1) * LEVEL_STRIDE;
680 }
681
682 static inline int pfn_level_offset(unsigned long pfn, int level)
683 {
684         return (pfn >> level_to_offset_bits(level)) & LEVEL_MASK;
685 }
686
687 static inline unsigned long level_mask(int level)
688 {
689         return -1UL << level_to_offset_bits(level);
690 }
691
692 static inline unsigned long level_size(int level)
693 {
694         return 1UL << level_to_offset_bits(level);
695 }
696
697 static inline unsigned long align_to_level(unsigned long pfn, int level)
698 {
699         return (pfn + level_size(level) - 1) & level_mask(level);
700 }
701
702 static struct dma_pte *pfn_to_dma_pte(struct dmar_domain *domain,
703                                       unsigned long pfn)
704 {
705         int addr_width = agaw_to_width(domain->agaw) - VTD_PAGE_SHIFT;
706         struct dma_pte *parent, *pte = NULL;
707         int level = agaw_to_level(domain->agaw);
708         int offset;
709
710         BUG_ON(!domain->pgd);
711         BUG_ON(addr_width < BITS_PER_LONG && pfn >> addr_width);
712         parent = domain->pgd;
713
714         while (level > 0) {
715                 void *tmp_page;
716
717                 offset = pfn_level_offset(pfn, level);
718                 pte = &parent[offset];
719                 if (level == 1)
720                         break;
721
722                 if (!dma_pte_present(pte)) {
723                         uint64_t pteval;
724
725                         tmp_page = alloc_pgtable_page();
726
727                         if (!tmp_page)
728                                 return NULL;
729
730                         domain_flush_cache(domain, tmp_page, VTD_PAGE_SIZE);
731                         pteval = (virt_to_dma_pfn(tmp_page) << VTD_PAGE_SHIFT) | DMA_PTE_READ | DMA_PTE_WRITE;
732                         if (cmpxchg64(&pte->val, 0ULL, pteval)) {
733                                 /* Someone else set it while we were thinking; use theirs. */
734                                 free_pgtable_page(tmp_page);
735                         } else {
736                                 dma_pte_addr(pte);
737                                 domain_flush_cache(domain, pte, sizeof(*pte));
738                         }
739                 }
740                 parent = phys_to_virt(dma_pte_addr(pte));
741                 level--;
742         }
743
744         return pte;
745 }
746
747 /* return address's pte at specific level */
748 static struct dma_pte *dma_pfn_level_pte(struct dmar_domain *domain,
749                                          unsigned long pfn,
750                                          int level)
751 {
752         struct dma_pte *parent, *pte = NULL;
753         int total = agaw_to_level(domain->agaw);
754         int offset;
755
756         parent = domain->pgd;
757         while (level <= total) {
758                 offset = pfn_level_offset(pfn, total);
759                 pte = &parent[offset];
760                 if (level == total)
761                         return pte;
762
763                 if (!dma_pte_present(pte))
764                         break;
765                 parent = phys_to_virt(dma_pte_addr(pte));
766                 total--;
767         }
768         return NULL;
769 }
770
771 /* clear last level pte, a tlb flush should be followed */
772 static void dma_pte_clear_range(struct dmar_domain *domain,
773                                 unsigned long start_pfn,
774                                 unsigned long last_pfn)
775 {
776         int addr_width = agaw_to_width(domain->agaw) - VTD_PAGE_SHIFT;
777         struct dma_pte *first_pte, *pte;
778
779         BUG_ON(addr_width < BITS_PER_LONG && start_pfn >> addr_width);
780         BUG_ON(addr_width < BITS_PER_LONG && last_pfn >> addr_width);
781
782         /* we don't need lock here; nobody else touches the iova range */
783         while (start_pfn <= last_pfn) {
784                 first_pte = pte = dma_pfn_level_pte(domain, start_pfn, 1);
785                 if (!pte) {
786                         start_pfn = align_to_level(start_pfn + 1, 2);
787                         continue;
788                 }
789                 do { 
790                         dma_clear_pte(pte);
791                         start_pfn++;
792                         pte++;
793                 } while (start_pfn <= last_pfn && !first_pte_in_page(pte));
794
795                 domain_flush_cache(domain, first_pte,
796                                    (void *)pte - (void *)first_pte);
797         }
798 }
799
800 /* free page table pages. last level pte should already be cleared */
801 static void dma_pte_free_pagetable(struct dmar_domain *domain,
802                                    unsigned long start_pfn,
803                                    unsigned long last_pfn)
804 {
805         int addr_width = agaw_to_width(domain->agaw) - VTD_PAGE_SHIFT;
806         struct dma_pte *first_pte, *pte;
807         int total = agaw_to_level(domain->agaw);
808         int level;
809         unsigned long tmp;
810
811         BUG_ON(addr_width < BITS_PER_LONG && start_pfn >> addr_width);
812         BUG_ON(addr_width < BITS_PER_LONG && last_pfn >> addr_width);
813
814         /* We don't need lock here; nobody else touches the iova range */
815         level = 2;
816         while (level <= total) {
817                 tmp = align_to_level(start_pfn, level);
818
819                 /* If we can't even clear one PTE at this level, we're done */
820                 if (tmp + level_size(level) - 1 > last_pfn)
821                         return;
822
823                 while (tmp + level_size(level) - 1 <= last_pfn) {
824                         first_pte = pte = dma_pfn_level_pte(domain, tmp, level);
825                         if (!pte) {
826                                 tmp = align_to_level(tmp + 1, level + 1);
827                                 continue;
828                         }
829                         do {
830                                 if (dma_pte_present(pte)) {
831                                         free_pgtable_page(phys_to_virt(dma_pte_addr(pte)));
832                                         dma_clear_pte(pte);
833                                 }
834                                 pte++;
835                                 tmp += level_size(level);
836                         } while (!first_pte_in_page(pte) &&
837                                  tmp + level_size(level) - 1 <= last_pfn);
838
839                         domain_flush_cache(domain, first_pte,
840                                            (void *)pte - (void *)first_pte);
841                         
842                 }
843                 level++;
844         }
845         /* free pgd */
846         if (start_pfn == 0 && last_pfn == DOMAIN_MAX_PFN(domain->gaw)) {
847                 free_pgtable_page(domain->pgd);
848                 domain->pgd = NULL;
849         }
850 }
851
852 /* iommu handling */
853 static int iommu_alloc_root_entry(struct intel_iommu *iommu)
854 {
855         struct root_entry *root;
856         unsigned long flags;
857
858         root = (struct root_entry *)alloc_pgtable_page();
859         if (!root)
860                 return -ENOMEM;
861
862         __iommu_flush_cache(iommu, root, ROOT_SIZE);
863
864         spin_lock_irqsave(&iommu->lock, flags);
865         iommu->root_entry = root;
866         spin_unlock_irqrestore(&iommu->lock, flags);
867
868         return 0;
869 }
870
871 static void iommu_set_root_entry(struct intel_iommu *iommu)
872 {
873         void *addr;
874         u32 sts;
875         unsigned long flag;
876
877         addr = iommu->root_entry;
878
879         spin_lock_irqsave(&iommu->register_lock, flag);
880         dmar_writeq(iommu->reg + DMAR_RTADDR_REG, virt_to_phys(addr));
881
882         writel(iommu->gcmd | DMA_GCMD_SRTP, iommu->reg + DMAR_GCMD_REG);
883
884         /* Make sure hardware complete it */
885         IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
886                       readl, (sts & DMA_GSTS_RTPS), sts);
887
888         spin_unlock_irqrestore(&iommu->register_lock, flag);
889 }
890
891 static void iommu_flush_write_buffer(struct intel_iommu *iommu)
892 {
893         u32 val;
894         unsigned long flag;
895
896         if (!rwbf_quirk && !cap_rwbf(iommu->cap))
897                 return;
898
899         spin_lock_irqsave(&iommu->register_lock, flag);
900         writel(iommu->gcmd | DMA_GCMD_WBF, iommu->reg + DMAR_GCMD_REG);
901
902         /* Make sure hardware complete it */
903         IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
904                       readl, (!(val & DMA_GSTS_WBFS)), val);
905
906         spin_unlock_irqrestore(&iommu->register_lock, flag);
907 }
908
909 /* return value determine if we need a write buffer flush */
910 static void __iommu_flush_context(struct intel_iommu *iommu,
911                                   u16 did, u16 source_id, u8 function_mask,
912                                   u64 type)
913 {
914         u64 val = 0;
915         unsigned long flag;
916
917         switch (type) {
918         case DMA_CCMD_GLOBAL_INVL:
919                 val = DMA_CCMD_GLOBAL_INVL;
920                 break;
921         case DMA_CCMD_DOMAIN_INVL:
922                 val = DMA_CCMD_DOMAIN_INVL|DMA_CCMD_DID(did);
923                 break;
924         case DMA_CCMD_DEVICE_INVL:
925                 val = DMA_CCMD_DEVICE_INVL|DMA_CCMD_DID(did)
926                         | DMA_CCMD_SID(source_id) | DMA_CCMD_FM(function_mask);
927                 break;
928         default:
929                 BUG();
930         }
931         val |= DMA_CCMD_ICC;
932
933         spin_lock_irqsave(&iommu->register_lock, flag);
934         dmar_writeq(iommu->reg + DMAR_CCMD_REG, val);
935
936         /* Make sure hardware complete it */
937         IOMMU_WAIT_OP(iommu, DMAR_CCMD_REG,
938                 dmar_readq, (!(val & DMA_CCMD_ICC)), val);
939
940         spin_unlock_irqrestore(&iommu->register_lock, flag);
941 }
942
943 /* return value determine if we need a write buffer flush */
944 static void __iommu_flush_iotlb(struct intel_iommu *iommu, u16 did,
945                                 u64 addr, unsigned int size_order, u64 type)
946 {
947         int tlb_offset = ecap_iotlb_offset(iommu->ecap);
948         u64 val = 0, val_iva = 0;
949         unsigned long flag;
950
951         switch (type) {
952         case DMA_TLB_GLOBAL_FLUSH:
953                 /* global flush doesn't need set IVA_REG */
954                 val = DMA_TLB_GLOBAL_FLUSH|DMA_TLB_IVT;
955                 break;
956         case DMA_TLB_DSI_FLUSH:
957                 val = DMA_TLB_DSI_FLUSH|DMA_TLB_IVT|DMA_TLB_DID(did);
958                 break;
959         case DMA_TLB_PSI_FLUSH:
960                 val = DMA_TLB_PSI_FLUSH|DMA_TLB_IVT|DMA_TLB_DID(did);
961                 /* Note: always flush non-leaf currently */
962                 val_iva = size_order | addr;
963                 break;
964         default:
965                 BUG();
966         }
967         /* Note: set drain read/write */
968 #if 0
969         /*
970          * This is probably to be super secure.. Looks like we can
971          * ignore it without any impact.
972          */
973         if (cap_read_drain(iommu->cap))
974                 val |= DMA_TLB_READ_DRAIN;
975 #endif
976         if (cap_write_drain(iommu->cap))
977                 val |= DMA_TLB_WRITE_DRAIN;
978
979         spin_lock_irqsave(&iommu->register_lock, flag);
980         /* Note: Only uses first TLB reg currently */
981         if (val_iva)
982                 dmar_writeq(iommu->reg + tlb_offset, val_iva);
983         dmar_writeq(iommu->reg + tlb_offset + 8, val);
984
985         /* Make sure hardware complete it */
986         IOMMU_WAIT_OP(iommu, tlb_offset + 8,
987                 dmar_readq, (!(val & DMA_TLB_IVT)), val);
988
989         spin_unlock_irqrestore(&iommu->register_lock, flag);
990
991         /* check IOTLB invalidation granularity */
992         if (DMA_TLB_IAIG(val) == 0)
993                 printk(KERN_ERR"IOMMU: flush IOTLB failed\n");
994         if (DMA_TLB_IAIG(val) != DMA_TLB_IIRG(type))
995                 pr_debug("IOMMU: tlb flush request %Lx, actual %Lx\n",
996                         (unsigned long long)DMA_TLB_IIRG(type),
997                         (unsigned long long)DMA_TLB_IAIG(val));
998 }
999
1000 static struct device_domain_info *iommu_support_dev_iotlb(
1001         struct dmar_domain *domain, int segment, u8 bus, u8 devfn)
1002 {
1003         int found = 0;
1004         unsigned long flags;
1005         struct device_domain_info *info;
1006         struct intel_iommu *iommu = device_to_iommu(segment, bus, devfn);
1007
1008         if (!ecap_dev_iotlb_support(iommu->ecap))
1009                 return NULL;
1010
1011         if (!iommu->qi)
1012                 return NULL;
1013
1014         spin_lock_irqsave(&device_domain_lock, flags);
1015         list_for_each_entry(info, &domain->devices, link)
1016                 if (info->bus == bus && info->devfn == devfn) {
1017                         found = 1;
1018                         break;
1019                 }
1020         spin_unlock_irqrestore(&device_domain_lock, flags);
1021
1022         if (!found || !info->dev)
1023                 return NULL;
1024
1025         if (!pci_find_ext_capability(info->dev, PCI_EXT_CAP_ID_ATS))
1026                 return NULL;
1027
1028         if (!dmar_find_matched_atsr_unit(info->dev))
1029                 return NULL;
1030
1031         info->iommu = iommu;
1032
1033         return info;
1034 }
1035
1036 static void iommu_enable_dev_iotlb(struct device_domain_info *info)
1037 {
1038         if (!info)
1039                 return;
1040
1041         pci_enable_ats(info->dev, VTD_PAGE_SHIFT);
1042 }
1043
1044 static void iommu_disable_dev_iotlb(struct device_domain_info *info)
1045 {
1046         if (!info->dev || !pci_ats_enabled(info->dev))
1047                 return;
1048
1049         pci_disable_ats(info->dev);
1050 }
1051
1052 static void iommu_flush_dev_iotlb(struct dmar_domain *domain,
1053                                   u64 addr, unsigned mask)
1054 {
1055         u16 sid, qdep;
1056         unsigned long flags;
1057         struct device_domain_info *info;
1058
1059         spin_lock_irqsave(&device_domain_lock, flags);
1060         list_for_each_entry(info, &domain->devices, link) {
1061                 if (!info->dev || !pci_ats_enabled(info->dev))
1062                         continue;
1063
1064                 sid = info->bus << 8 | info->devfn;
1065                 qdep = pci_ats_queue_depth(info->dev);
1066                 qi_flush_dev_iotlb(info->iommu, sid, qdep, addr, mask);
1067         }
1068         spin_unlock_irqrestore(&device_domain_lock, flags);
1069 }
1070
1071 static void iommu_flush_iotlb_psi(struct intel_iommu *iommu, u16 did,
1072                                   unsigned long pfn, unsigned int pages)
1073 {
1074         unsigned int mask = ilog2(__roundup_pow_of_two(pages));
1075         uint64_t addr = (uint64_t)pfn << VTD_PAGE_SHIFT;
1076
1077         BUG_ON(pages == 0);
1078
1079         /*
1080          * Fallback to domain selective flush if no PSI support or the size is
1081          * too big.
1082          * PSI requires page size to be 2 ^ x, and the base address is naturally
1083          * aligned to the size
1084          */
1085         if (!cap_pgsel_inv(iommu->cap) || mask > cap_max_amask_val(iommu->cap))
1086                 iommu->flush.flush_iotlb(iommu, did, 0, 0,
1087                                                 DMA_TLB_DSI_FLUSH);
1088         else
1089                 iommu->flush.flush_iotlb(iommu, did, addr, mask,
1090                                                 DMA_TLB_PSI_FLUSH);
1091
1092         /*
1093          * In caching mode, domain ID 0 is reserved for non-present to present
1094          * mapping flush. Device IOTLB doesn't need to be flushed in this case.
1095          */
1096         if (!cap_caching_mode(iommu->cap) || did)
1097                 iommu_flush_dev_iotlb(iommu->domains[did], addr, mask);
1098 }
1099
1100 static void iommu_disable_protect_mem_regions(struct intel_iommu *iommu)
1101 {
1102         u32 pmen;
1103         unsigned long flags;
1104
1105         spin_lock_irqsave(&iommu->register_lock, flags);
1106         pmen = readl(iommu->reg + DMAR_PMEN_REG);
1107         pmen &= ~DMA_PMEN_EPM;
1108         writel(pmen, iommu->reg + DMAR_PMEN_REG);
1109
1110         /* wait for the protected region status bit to clear */
1111         IOMMU_WAIT_OP(iommu, DMAR_PMEN_REG,
1112                 readl, !(pmen & DMA_PMEN_PRS), pmen);
1113
1114         spin_unlock_irqrestore(&iommu->register_lock, flags);
1115 }
1116
1117 static int iommu_enable_translation(struct intel_iommu *iommu)
1118 {
1119         u32 sts;
1120         unsigned long flags;
1121
1122         spin_lock_irqsave(&iommu->register_lock, flags);
1123         iommu->gcmd |= DMA_GCMD_TE;
1124         writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
1125
1126         /* Make sure hardware complete it */
1127         IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
1128                       readl, (sts & DMA_GSTS_TES), sts);
1129
1130         spin_unlock_irqrestore(&iommu->register_lock, flags);
1131         return 0;
1132 }
1133
1134 static int iommu_disable_translation(struct intel_iommu *iommu)
1135 {
1136         u32 sts;
1137         unsigned long flag;
1138
1139         spin_lock_irqsave(&iommu->register_lock, flag);
1140         iommu->gcmd &= ~DMA_GCMD_TE;
1141         writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
1142
1143         /* Make sure hardware complete it */
1144         IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
1145                       readl, (!(sts & DMA_GSTS_TES)), sts);
1146
1147         spin_unlock_irqrestore(&iommu->register_lock, flag);
1148         return 0;
1149 }
1150
1151
1152 static int iommu_init_domains(struct intel_iommu *iommu)
1153 {
1154         unsigned long ndomains;
1155         unsigned long nlongs;
1156
1157         ndomains = cap_ndoms(iommu->cap);
1158         pr_debug("Number of Domains supportd <%ld>\n", ndomains);
1159         nlongs = BITS_TO_LONGS(ndomains);
1160
1161         /* TBD: there might be 64K domains,
1162          * consider other allocation for future chip
1163          */
1164         iommu->domain_ids = kcalloc(nlongs, sizeof(unsigned long), GFP_KERNEL);
1165         if (!iommu->domain_ids) {
1166                 printk(KERN_ERR "Allocating domain id array failed\n");
1167                 return -ENOMEM;
1168         }
1169         iommu->domains = kcalloc(ndomains, sizeof(struct dmar_domain *),
1170                         GFP_KERNEL);
1171         if (!iommu->domains) {
1172                 printk(KERN_ERR "Allocating domain array failed\n");
1173                 kfree(iommu->domain_ids);
1174                 return -ENOMEM;
1175         }
1176
1177         spin_lock_init(&iommu->lock);
1178
1179         /*
1180          * if Caching mode is set, then invalid translations are tagged
1181          * with domainid 0. Hence we need to pre-allocate it.
1182          */
1183         if (cap_caching_mode(iommu->cap))
1184                 set_bit(0, iommu->domain_ids);
1185         return 0;
1186 }
1187
1188
1189 static void domain_exit(struct dmar_domain *domain);
1190 static void vm_domain_exit(struct dmar_domain *domain);
1191
1192 void free_dmar_iommu(struct intel_iommu *iommu)
1193 {
1194         struct dmar_domain *domain;
1195         int i;
1196         unsigned long flags;
1197
1198         i = find_first_bit(iommu->domain_ids, cap_ndoms(iommu->cap));
1199         for (; i < cap_ndoms(iommu->cap); ) {
1200                 domain = iommu->domains[i];
1201                 clear_bit(i, iommu->domain_ids);
1202
1203                 spin_lock_irqsave(&domain->iommu_lock, flags);
1204                 if (--domain->iommu_count == 0) {
1205                         if (domain->flags & DOMAIN_FLAG_VIRTUAL_MACHINE)
1206                                 vm_domain_exit(domain);
1207                         else
1208                                 domain_exit(domain);
1209                 }
1210                 spin_unlock_irqrestore(&domain->iommu_lock, flags);
1211
1212                 i = find_next_bit(iommu->domain_ids,
1213                         cap_ndoms(iommu->cap), i+1);
1214         }
1215
1216         if (iommu->gcmd & DMA_GCMD_TE)
1217                 iommu_disable_translation(iommu);
1218
1219         if (iommu->irq) {
1220                 set_irq_data(iommu->irq, NULL);
1221                 /* This will mask the irq */
1222                 free_irq(iommu->irq, iommu);
1223                 destroy_irq(iommu->irq);
1224         }
1225
1226         kfree(iommu->domains);
1227         kfree(iommu->domain_ids);
1228
1229         g_iommus[iommu->seq_id] = NULL;
1230
1231         /* if all iommus are freed, free g_iommus */
1232         for (i = 0; i < g_num_of_iommus; i++) {
1233                 if (g_iommus[i])
1234                         break;
1235         }
1236
1237         if (i == g_num_of_iommus)
1238                 kfree(g_iommus);
1239
1240         /* free context mapping */
1241         free_context_table(iommu);
1242 }
1243
1244 static struct dmar_domain *alloc_domain(void)
1245 {
1246         struct dmar_domain *domain;
1247
1248         domain = alloc_domain_mem();
1249         if (!domain)
1250                 return NULL;
1251
1252         memset(&domain->iommu_bmp, 0, sizeof(unsigned long));
1253         domain->flags = 0;
1254
1255         return domain;
1256 }
1257
1258 static int iommu_attach_domain(struct dmar_domain *domain,
1259                                struct intel_iommu *iommu)
1260 {
1261         int num;
1262         unsigned long ndomains;
1263         unsigned long flags;
1264
1265         ndomains = cap_ndoms(iommu->cap);
1266
1267         spin_lock_irqsave(&iommu->lock, flags);
1268
1269         num = find_first_zero_bit(iommu->domain_ids, ndomains);
1270         if (num >= ndomains) {
1271                 spin_unlock_irqrestore(&iommu->lock, flags);
1272                 printk(KERN_ERR "IOMMU: no free domain ids\n");
1273                 return -ENOMEM;
1274         }
1275
1276         domain->id = num;
1277         set_bit(num, iommu->domain_ids);
1278         set_bit(iommu->seq_id, &domain->iommu_bmp);
1279         iommu->domains[num] = domain;
1280         spin_unlock_irqrestore(&iommu->lock, flags);
1281
1282         return 0;
1283 }
1284
1285 static void iommu_detach_domain(struct dmar_domain *domain,
1286                                 struct intel_iommu *iommu)
1287 {
1288         unsigned long flags;
1289         int num, ndomains;
1290         int found = 0;
1291
1292         spin_lock_irqsave(&iommu->lock, flags);
1293         ndomains = cap_ndoms(iommu->cap);
1294         num = find_first_bit(iommu->domain_ids, ndomains);
1295         for (; num < ndomains; ) {
1296                 if (iommu->domains[num] == domain) {
1297                         found = 1;
1298                         break;
1299                 }
1300                 num = find_next_bit(iommu->domain_ids,
1301                                     cap_ndoms(iommu->cap), num+1);
1302         }
1303
1304         if (found) {
1305                 clear_bit(num, iommu->domain_ids);
1306                 clear_bit(iommu->seq_id, &domain->iommu_bmp);
1307                 iommu->domains[num] = NULL;
1308         }
1309         spin_unlock_irqrestore(&iommu->lock, flags);
1310 }
1311
1312 static struct iova_domain reserved_iova_list;
1313 static struct lock_class_key reserved_alloc_key;
1314 static struct lock_class_key reserved_rbtree_key;
1315
1316 static void dmar_init_reserved_ranges(void)
1317 {
1318         struct pci_dev *pdev = NULL;
1319         struct iova *iova;
1320         int i;
1321
1322         init_iova_domain(&reserved_iova_list, DMA_32BIT_PFN);
1323
1324         lockdep_set_class(&reserved_iova_list.iova_alloc_lock,
1325                 &reserved_alloc_key);
1326         lockdep_set_class(&reserved_iova_list.iova_rbtree_lock,
1327                 &reserved_rbtree_key);
1328
1329         /* IOAPIC ranges shouldn't be accessed by DMA */
1330         iova = reserve_iova(&reserved_iova_list, IOVA_PFN(IOAPIC_RANGE_START),
1331                 IOVA_PFN(IOAPIC_RANGE_END));
1332         if (!iova)
1333                 printk(KERN_ERR "Reserve IOAPIC range failed\n");
1334
1335         /* Reserve all PCI MMIO to avoid peer-to-peer access */
1336         for_each_pci_dev(pdev) {
1337                 struct resource *r;
1338
1339                 for (i = 0; i < PCI_NUM_RESOURCES; i++) {
1340                         r = &pdev->resource[i];
1341                         if (!r->flags || !(r->flags & IORESOURCE_MEM))
1342                                 continue;
1343                         iova = reserve_iova(&reserved_iova_list,
1344                                             IOVA_PFN(r->start),
1345                                             IOVA_PFN(r->end));
1346                         if (!iova)
1347                                 printk(KERN_ERR "Reserve iova failed\n");
1348                 }
1349         }
1350
1351 }
1352
1353 static void domain_reserve_special_ranges(struct dmar_domain *domain)
1354 {
1355         copy_reserved_iova(&reserved_iova_list, &domain->iovad);
1356 }
1357
1358 static inline int guestwidth_to_adjustwidth(int gaw)
1359 {
1360         int agaw;
1361         int r = (gaw - 12) % 9;
1362
1363         if (r == 0)
1364                 agaw = gaw;
1365         else
1366                 agaw = gaw + 9 - r;
1367         if (agaw > 64)
1368                 agaw = 64;
1369         return agaw;
1370 }
1371
1372 static int domain_init(struct dmar_domain *domain, int guest_width)
1373 {
1374         struct intel_iommu *iommu;
1375         int adjust_width, agaw;
1376         unsigned long sagaw;
1377
1378         init_iova_domain(&domain->iovad, DMA_32BIT_PFN);
1379         spin_lock_init(&domain->iommu_lock);
1380
1381         domain_reserve_special_ranges(domain);
1382
1383         /* calculate AGAW */
1384         iommu = domain_get_iommu(domain);
1385         if (guest_width > cap_mgaw(iommu->cap))
1386                 guest_width = cap_mgaw(iommu->cap);
1387         domain->gaw = guest_width;
1388         adjust_width = guestwidth_to_adjustwidth(guest_width);
1389         agaw = width_to_agaw(adjust_width);
1390         sagaw = cap_sagaw(iommu->cap);
1391         if (!test_bit(agaw, &sagaw)) {
1392                 /* hardware doesn't support it, choose a bigger one */
1393                 pr_debug("IOMMU: hardware doesn't support agaw %d\n", agaw);
1394                 agaw = find_next_bit(&sagaw, 5, agaw);
1395                 if (agaw >= 5)
1396                         return -ENODEV;
1397         }
1398         domain->agaw = agaw;
1399         INIT_LIST_HEAD(&domain->devices);
1400
1401         if (ecap_coherent(iommu->ecap))
1402                 domain->iommu_coherency = 1;
1403         else
1404                 domain->iommu_coherency = 0;
1405
1406         if (ecap_sc_support(iommu->ecap))
1407                 domain->iommu_snooping = 1;
1408         else
1409                 domain->iommu_snooping = 0;
1410
1411         domain->iommu_count = 1;
1412
1413         /* always allocate the top pgd */
1414         domain->pgd = (struct dma_pte *)alloc_pgtable_page();
1415         if (!domain->pgd)
1416                 return -ENOMEM;
1417         __iommu_flush_cache(iommu, domain->pgd, PAGE_SIZE);
1418         return 0;
1419 }
1420
1421 static void domain_exit(struct dmar_domain *domain)
1422 {
1423         struct dmar_drhd_unit *drhd;
1424         struct intel_iommu *iommu;
1425
1426         /* Domain 0 is reserved, so dont process it */
1427         if (!domain)
1428                 return;
1429
1430         domain_remove_dev_info(domain);
1431         /* destroy iovas */
1432         put_iova_domain(&domain->iovad);
1433
1434         /* clear ptes */
1435         dma_pte_clear_range(domain, 0, DOMAIN_MAX_PFN(domain->gaw));
1436
1437         /* free page tables */
1438         dma_pte_free_pagetable(domain, 0, DOMAIN_MAX_PFN(domain->gaw));
1439
1440         for_each_active_iommu(iommu, drhd)
1441                 if (test_bit(iommu->seq_id, &domain->iommu_bmp))
1442                         iommu_detach_domain(domain, iommu);
1443
1444         free_domain_mem(domain);
1445 }
1446
1447 static int domain_context_mapping_one(struct dmar_domain *domain, int segment,
1448                                  u8 bus, u8 devfn, int translation)
1449 {
1450         struct context_entry *context;
1451         unsigned long flags;
1452         struct intel_iommu *iommu;
1453         struct dma_pte *pgd;
1454         unsigned long num;
1455         unsigned long ndomains;
1456         int id;
1457         int agaw;
1458         struct device_domain_info *info = NULL;
1459
1460         pr_debug("Set context mapping for %02x:%02x.%d\n",
1461                 bus, PCI_SLOT(devfn), PCI_FUNC(devfn));
1462
1463         BUG_ON(!domain->pgd);
1464         BUG_ON(translation != CONTEXT_TT_PASS_THROUGH &&
1465                translation != CONTEXT_TT_MULTI_LEVEL);
1466
1467         iommu = device_to_iommu(segment, bus, devfn);
1468         if (!iommu)
1469                 return -ENODEV;
1470
1471         context = device_to_context_entry(iommu, bus, devfn);
1472         if (!context)
1473                 return -ENOMEM;
1474         spin_lock_irqsave(&iommu->lock, flags);
1475         if (context_present(context)) {
1476                 spin_unlock_irqrestore(&iommu->lock, flags);
1477                 return 0;
1478         }
1479
1480         id = domain->id;
1481         pgd = domain->pgd;
1482
1483         if (domain->flags & DOMAIN_FLAG_VIRTUAL_MACHINE ||
1484             domain->flags & DOMAIN_FLAG_STATIC_IDENTITY) {
1485                 int found = 0;
1486
1487                 /* find an available domain id for this device in iommu */
1488                 ndomains = cap_ndoms(iommu->cap);
1489                 num = find_first_bit(iommu->domain_ids, ndomains);
1490                 for (; num < ndomains; ) {
1491                         if (iommu->domains[num] == domain) {
1492                                 id = num;
1493                                 found = 1;
1494                                 break;
1495                         }
1496                         num = find_next_bit(iommu->domain_ids,
1497                                             cap_ndoms(iommu->cap), num+1);
1498                 }
1499
1500                 if (found == 0) {
1501                         num = find_first_zero_bit(iommu->domain_ids, ndomains);
1502                         if (num >= ndomains) {
1503                                 spin_unlock_irqrestore(&iommu->lock, flags);
1504                                 printk(KERN_ERR "IOMMU: no free domain ids\n");
1505                                 return -EFAULT;
1506                         }
1507
1508                         set_bit(num, iommu->domain_ids);
1509                         set_bit(iommu->seq_id, &domain->iommu_bmp);
1510                         iommu->domains[num] = domain;
1511                         id = num;
1512                 }
1513
1514                 /* Skip top levels of page tables for
1515                  * iommu which has less agaw than default.
1516                  */
1517                 for (agaw = domain->agaw; agaw != iommu->agaw; agaw--) {
1518                         pgd = phys_to_virt(dma_pte_addr(pgd));
1519                         if (!dma_pte_present(pgd)) {
1520                                 spin_unlock_irqrestore(&iommu->lock, flags);
1521                                 return -ENOMEM;
1522                         }
1523                 }
1524         }
1525
1526         context_set_domain_id(context, id);
1527
1528         if (translation != CONTEXT_TT_PASS_THROUGH) {
1529                 info = iommu_support_dev_iotlb(domain, segment, bus, devfn);
1530                 translation = info ? CONTEXT_TT_DEV_IOTLB :
1531                                      CONTEXT_TT_MULTI_LEVEL;
1532         }
1533         /*
1534          * In pass through mode, AW must be programmed to indicate the largest
1535          * AGAW value supported by hardware. And ASR is ignored by hardware.
1536          */
1537         if (unlikely(translation == CONTEXT_TT_PASS_THROUGH))
1538                 context_set_address_width(context, iommu->msagaw);
1539         else {
1540                 context_set_address_root(context, virt_to_phys(pgd));
1541                 context_set_address_width(context, iommu->agaw);
1542         }
1543
1544         context_set_translation_type(context, translation);
1545         context_set_fault_enable(context);
1546         context_set_present(context);
1547         domain_flush_cache(domain, context, sizeof(*context));
1548
1549         /*
1550          * It's a non-present to present mapping. If hardware doesn't cache
1551          * non-present entry we only need to flush the write-buffer. If the
1552          * _does_ cache non-present entries, then it does so in the special
1553          * domain #0, which we have to flush:
1554          */
1555         if (cap_caching_mode(iommu->cap)) {
1556                 iommu->flush.flush_context(iommu, 0,
1557                                            (((u16)bus) << 8) | devfn,
1558                                            DMA_CCMD_MASK_NOBIT,
1559                                            DMA_CCMD_DEVICE_INVL);
1560                 iommu->flush.flush_iotlb(iommu, 0, 0, 0, DMA_TLB_DSI_FLUSH);
1561         } else {
1562                 iommu_flush_write_buffer(iommu);
1563         }
1564         iommu_enable_dev_iotlb(info);
1565         spin_unlock_irqrestore(&iommu->lock, flags);
1566
1567         spin_lock_irqsave(&domain->iommu_lock, flags);
1568         if (!test_and_set_bit(iommu->seq_id, &domain->iommu_bmp)) {
1569                 domain->iommu_count++;
1570                 domain_update_iommu_cap(domain);
1571         }
1572         spin_unlock_irqrestore(&domain->iommu_lock, flags);
1573         return 0;
1574 }
1575
1576 static int
1577 domain_context_mapping(struct dmar_domain *domain, struct pci_dev *pdev,
1578                         int translation)
1579 {
1580         int ret;
1581         struct pci_dev *tmp, *parent;
1582
1583         ret = domain_context_mapping_one(domain, pci_domain_nr(pdev->bus),
1584                                          pdev->bus->number, pdev->devfn,
1585                                          translation);
1586         if (ret)
1587                 return ret;
1588
1589         /* dependent device mapping */
1590         tmp = pci_find_upstream_pcie_bridge(pdev);
1591         if (!tmp)
1592                 return 0;
1593         /* Secondary interface's bus number and devfn 0 */
1594         parent = pdev->bus->self;
1595         while (parent != tmp) {
1596                 ret = domain_context_mapping_one(domain,
1597                                                  pci_domain_nr(parent->bus),
1598                                                  parent->bus->number,
1599                                                  parent->devfn, translation);
1600                 if (ret)
1601                         return ret;
1602                 parent = parent->bus->self;
1603         }
1604         if (tmp->is_pcie) /* this is a PCIE-to-PCI bridge */
1605                 return domain_context_mapping_one(domain,
1606                                         pci_domain_nr(tmp->subordinate),
1607                                         tmp->subordinate->number, 0,
1608                                         translation);
1609         else /* this is a legacy PCI bridge */
1610                 return domain_context_mapping_one(domain,
1611                                                   pci_domain_nr(tmp->bus),
1612                                                   tmp->bus->number,
1613                                                   tmp->devfn,
1614                                                   translation);
1615 }
1616
1617 static int domain_context_mapped(struct pci_dev *pdev)
1618 {
1619         int ret;
1620         struct pci_dev *tmp, *parent;
1621         struct intel_iommu *iommu;
1622
1623         iommu = device_to_iommu(pci_domain_nr(pdev->bus), pdev->bus->number,
1624                                 pdev->devfn);
1625         if (!iommu)
1626                 return -ENODEV;
1627
1628         ret = device_context_mapped(iommu, pdev->bus->number, pdev->devfn);
1629         if (!ret)
1630                 return ret;
1631         /* dependent device mapping */
1632         tmp = pci_find_upstream_pcie_bridge(pdev);
1633         if (!tmp)
1634                 return ret;
1635         /* Secondary interface's bus number and devfn 0 */
1636         parent = pdev->bus->self;
1637         while (parent != tmp) {
1638                 ret = device_context_mapped(iommu, parent->bus->number,
1639                                             parent->devfn);
1640                 if (!ret)
1641                         return ret;
1642                 parent = parent->bus->self;
1643         }
1644         if (tmp->is_pcie)
1645                 return device_context_mapped(iommu, tmp->subordinate->number,
1646                                              0);
1647         else
1648                 return device_context_mapped(iommu, tmp->bus->number,
1649                                              tmp->devfn);
1650 }
1651
1652 static int __domain_mapping(struct dmar_domain *domain, unsigned long iov_pfn,
1653                             struct scatterlist *sg, unsigned long phys_pfn,
1654                             unsigned long nr_pages, int prot)
1655 {
1656         struct dma_pte *first_pte = NULL, *pte = NULL;
1657         phys_addr_t uninitialized_var(pteval);
1658         int addr_width = agaw_to_width(domain->agaw) - VTD_PAGE_SHIFT;
1659         unsigned long sg_res;
1660
1661         BUG_ON(addr_width < BITS_PER_LONG && (iov_pfn + nr_pages - 1) >> addr_width);
1662
1663         if ((prot & (DMA_PTE_READ|DMA_PTE_WRITE)) == 0)
1664                 return -EINVAL;
1665
1666         prot &= DMA_PTE_READ | DMA_PTE_WRITE | DMA_PTE_SNP;
1667
1668         if (sg)
1669                 sg_res = 0;
1670         else {
1671                 sg_res = nr_pages + 1;
1672                 pteval = ((phys_addr_t)phys_pfn << VTD_PAGE_SHIFT) | prot;
1673         }
1674
1675         while (nr_pages--) {
1676                 uint64_t tmp;
1677
1678                 if (!sg_res) {
1679                         sg_res = (sg->offset + sg->length + VTD_PAGE_SIZE - 1) >> VTD_PAGE_SHIFT;
1680                         sg->dma_address = ((dma_addr_t)iov_pfn << VTD_PAGE_SHIFT) + sg->offset;
1681                         sg->dma_length = sg->length;
1682                         pteval = page_to_phys(sg_page(sg)) | prot;
1683                 }
1684                 if (!pte) {
1685                         first_pte = pte = pfn_to_dma_pte(domain, iov_pfn);
1686                         if (!pte)
1687                                 return -ENOMEM;
1688                 }
1689                 /* We don't need lock here, nobody else
1690                  * touches the iova range
1691                  */
1692                 tmp = cmpxchg64_local(&pte->val, 0ULL, pteval);
1693                 if (tmp) {
1694                         static int dumps = 5;
1695                         printk(KERN_CRIT "ERROR: DMA PTE for vPFN 0x%lx already set (to %llx not %llx)\n",
1696                                iov_pfn, tmp, (unsigned long long)pteval);
1697                         if (dumps) {
1698                                 dumps--;
1699                                 debug_dma_dump_mappings(NULL);
1700                         }
1701                         WARN_ON(1);
1702                 }
1703                 pte++;
1704                 if (!nr_pages || first_pte_in_page(pte)) {
1705                         domain_flush_cache(domain, first_pte,
1706                                            (void *)pte - (void *)first_pte);
1707                         pte = NULL;
1708                 }
1709                 iov_pfn++;
1710                 pteval += VTD_PAGE_SIZE;
1711                 sg_res--;
1712                 if (!sg_res)
1713                         sg = sg_next(sg);
1714         }
1715         return 0;
1716 }
1717
1718 static inline int domain_sg_mapping(struct dmar_domain *domain, unsigned long iov_pfn,
1719                                     struct scatterlist *sg, unsigned long nr_pages,
1720                                     int prot)
1721 {
1722         return __domain_mapping(domain, iov_pfn, sg, 0, nr_pages, prot);
1723 }
1724
1725 static inline int domain_pfn_mapping(struct dmar_domain *domain, unsigned long iov_pfn,
1726                                      unsigned long phys_pfn, unsigned long nr_pages,
1727                                      int prot)
1728 {
1729         return __domain_mapping(domain, iov_pfn, NULL, phys_pfn, nr_pages, prot);
1730 }
1731
1732 static void iommu_detach_dev(struct intel_iommu *iommu, u8 bus, u8 devfn)
1733 {
1734         if (!iommu)
1735                 return;
1736
1737         clear_context_table(iommu, bus, devfn);
1738         iommu->flush.flush_context(iommu, 0, 0, 0,
1739                                            DMA_CCMD_GLOBAL_INVL);
1740         iommu->flush.flush_iotlb(iommu, 0, 0, 0, DMA_TLB_GLOBAL_FLUSH);
1741 }
1742
1743 static void domain_remove_dev_info(struct dmar_domain *domain)
1744 {
1745         struct device_domain_info *info;
1746         unsigned long flags;
1747         struct intel_iommu *iommu;
1748
1749         spin_lock_irqsave(&device_domain_lock, flags);
1750         while (!list_empty(&domain->devices)) {
1751                 info = list_entry(domain->devices.next,
1752                         struct device_domain_info, link);
1753                 list_del(&info->link);
1754                 list_del(&info->global);
1755                 if (info->dev)
1756                         info->dev->dev.archdata.iommu = NULL;
1757                 spin_unlock_irqrestore(&device_domain_lock, flags);
1758
1759                 iommu_disable_dev_iotlb(info);
1760                 iommu = device_to_iommu(info->segment, info->bus, info->devfn);
1761                 iommu_detach_dev(iommu, info->bus, info->devfn);
1762                 free_devinfo_mem(info);
1763
1764                 spin_lock_irqsave(&device_domain_lock, flags);
1765         }
1766         spin_unlock_irqrestore(&device_domain_lock, flags);
1767 }
1768
1769 /*
1770  * find_domain
1771  * Note: we use struct pci_dev->dev.archdata.iommu stores the info
1772  */
1773 static struct dmar_domain *
1774 find_domain(struct pci_dev *pdev)
1775 {
1776         struct device_domain_info *info;
1777
1778         /* No lock here, assumes no domain exit in normal case */
1779         info = pdev->dev.archdata.iommu;
1780         if (info)
1781                 return info->domain;
1782         return NULL;
1783 }
1784
1785 /* domain is initialized */
1786 static struct dmar_domain *get_domain_for_dev(struct pci_dev *pdev, int gaw)
1787 {
1788         struct dmar_domain *domain, *found = NULL;
1789         struct intel_iommu *iommu;
1790         struct dmar_drhd_unit *drhd;
1791         struct device_domain_info *info, *tmp;
1792         struct pci_dev *dev_tmp;
1793         unsigned long flags;
1794         int bus = 0, devfn = 0;
1795         int segment;
1796         int ret;
1797
1798         domain = find_domain(pdev);
1799         if (domain)
1800                 return domain;
1801
1802         segment = pci_domain_nr(pdev->bus);
1803
1804         dev_tmp = pci_find_upstream_pcie_bridge(pdev);
1805         if (dev_tmp) {
1806                 if (dev_tmp->is_pcie) {
1807                         bus = dev_tmp->subordinate->number;
1808                         devfn = 0;
1809                 } else {
1810                         bus = dev_tmp->bus->number;
1811                         devfn = dev_tmp->devfn;
1812                 }
1813                 spin_lock_irqsave(&device_domain_lock, flags);
1814                 list_for_each_entry(info, &device_domain_list, global) {
1815                         if (info->segment == segment &&
1816                             info->bus == bus && info->devfn == devfn) {
1817                                 found = info->domain;
1818                                 break;
1819                         }
1820                 }
1821                 spin_unlock_irqrestore(&device_domain_lock, flags);
1822                 /* pcie-pci bridge already has a domain, uses it */
1823                 if (found) {
1824                         domain = found;
1825                         goto found_domain;
1826                 }
1827         }
1828
1829         domain = alloc_domain();
1830         if (!domain)
1831                 goto error;
1832
1833         /* Allocate new domain for the device */
1834         drhd = dmar_find_matched_drhd_unit(pdev);
1835         if (!drhd) {
1836                 printk(KERN_ERR "IOMMU: can't find DMAR for device %s\n",
1837                         pci_name(pdev));
1838                 return NULL;
1839         }
1840         iommu = drhd->iommu;
1841
1842         ret = iommu_attach_domain(domain, iommu);
1843         if (ret) {
1844                 domain_exit(domain);
1845                 goto error;
1846         }
1847
1848         if (domain_init(domain, gaw)) {
1849                 domain_exit(domain);
1850                 goto error;
1851         }
1852
1853         /* register pcie-to-pci device */
1854         if (dev_tmp) {
1855                 info = alloc_devinfo_mem();
1856                 if (!info) {
1857                         domain_exit(domain);
1858                         goto error;
1859                 }
1860                 info->segment = segment;
1861                 info->bus = bus;
1862                 info->devfn = devfn;
1863                 info->dev = NULL;
1864                 info->domain = domain;
1865                 /* This domain is shared by devices under p2p bridge */
1866                 domain->flags |= DOMAIN_FLAG_P2P_MULTIPLE_DEVICES;
1867
1868                 /* pcie-to-pci bridge already has a domain, uses it */
1869                 found = NULL;
1870                 spin_lock_irqsave(&device_domain_lock, flags);
1871                 list_for_each_entry(tmp, &device_domain_list, global) {
1872                         if (tmp->segment == segment &&
1873                             tmp->bus == bus && tmp->devfn == devfn) {
1874                                 found = tmp->domain;
1875                                 break;
1876                         }
1877                 }
1878                 if (found) {
1879                         free_devinfo_mem(info);
1880                         domain_exit(domain);
1881                         domain = found;
1882                 } else {
1883                         list_add(&info->link, &domain->devices);
1884                         list_add(&info->global, &device_domain_list);
1885                 }
1886                 spin_unlock_irqrestore(&device_domain_lock, flags);
1887         }
1888
1889 found_domain:
1890         info = alloc_devinfo_mem();
1891         if (!info)
1892                 goto error;
1893         info->segment = segment;
1894         info->bus = pdev->bus->number;
1895         info->devfn = pdev->devfn;
1896         info->dev = pdev;
1897         info->domain = domain;
1898         spin_lock_irqsave(&device_domain_lock, flags);
1899         /* somebody is fast */
1900         found = find_domain(pdev);
1901         if (found != NULL) {
1902                 spin_unlock_irqrestore(&device_domain_lock, flags);
1903                 if (found != domain) {
1904                         domain_exit(domain);
1905                         domain = found;
1906                 }
1907                 free_devinfo_mem(info);
1908                 return domain;
1909         }
1910         list_add(&info->link, &domain->devices);
1911         list_add(&info->global, &device_domain_list);
1912         pdev->dev.archdata.iommu = info;
1913         spin_unlock_irqrestore(&device_domain_lock, flags);
1914         return domain;
1915 error:
1916         /* recheck it here, maybe others set it */
1917         return find_domain(pdev);
1918 }
1919
1920 static int iommu_identity_mapping;
1921
1922 static int iommu_domain_identity_map(struct dmar_domain *domain,
1923                                      unsigned long long start,
1924                                      unsigned long long end)
1925 {
1926         unsigned long first_vpfn = start >> VTD_PAGE_SHIFT;
1927         unsigned long last_vpfn = end >> VTD_PAGE_SHIFT;
1928
1929         if (!reserve_iova(&domain->iovad, dma_to_mm_pfn(first_vpfn),
1930                           dma_to_mm_pfn(last_vpfn))) {
1931                 printk(KERN_ERR "IOMMU: reserve iova failed\n");
1932                 return -ENOMEM;
1933         }
1934
1935         pr_debug("Mapping reserved region %llx-%llx for domain %d\n",
1936                  start, end, domain->id);
1937         /*
1938          * RMRR range might have overlap with physical memory range,
1939          * clear it first
1940          */
1941         dma_pte_clear_range(domain, first_vpfn, last_vpfn);
1942
1943         return domain_pfn_mapping(domain, first_vpfn, first_vpfn,
1944                                   last_vpfn - first_vpfn + 1,
1945                                   DMA_PTE_READ|DMA_PTE_WRITE);
1946 }
1947
1948 static int iommu_prepare_identity_map(struct pci_dev *pdev,
1949                                       unsigned long long start,
1950                                       unsigned long long end)
1951 {
1952         struct dmar_domain *domain;
1953         int ret;
1954
1955         printk(KERN_INFO
1956                "IOMMU: Setting identity map for device %s [0x%Lx - 0x%Lx]\n",
1957                pci_name(pdev), start, end);
1958
1959         domain = get_domain_for_dev(pdev, DEFAULT_DOMAIN_ADDRESS_WIDTH);
1960         if (!domain)
1961                 return -ENOMEM;
1962
1963         ret = iommu_domain_identity_map(domain, start, end);
1964         if (ret)
1965                 goto error;
1966
1967         /* context entry init */
1968         ret = domain_context_mapping(domain, pdev, CONTEXT_TT_MULTI_LEVEL);
1969         if (ret)
1970                 goto error;
1971
1972         return 0;
1973
1974  error:
1975         domain_exit(domain);
1976         return ret;
1977 }
1978
1979 static inline int iommu_prepare_rmrr_dev(struct dmar_rmrr_unit *rmrr,
1980         struct pci_dev *pdev)
1981 {
1982         if (pdev->dev.archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO)
1983                 return 0;
1984         return iommu_prepare_identity_map(pdev, rmrr->base_address,
1985                 rmrr->end_address + 1);
1986 }
1987
1988 #ifdef CONFIG_DMAR_FLOPPY_WA
1989 static inline void iommu_prepare_isa(void)
1990 {
1991         struct pci_dev *pdev;
1992         int ret;
1993
1994         pdev = pci_get_class(PCI_CLASS_BRIDGE_ISA << 8, NULL);
1995         if (!pdev)
1996                 return;
1997
1998         printk(KERN_INFO "IOMMU: Prepare 0-16MiB unity mapping for LPC\n");
1999         ret = iommu_prepare_identity_map(pdev, 0, 16*1024*1024);
2000
2001         if (ret)
2002                 printk(KERN_ERR "IOMMU: Failed to create 0-16MiB identity map; "
2003                        "floppy might not work\n");
2004
2005 }
2006 #else
2007 static inline void iommu_prepare_isa(void)
2008 {
2009         return;
2010 }
2011 #endif /* !CONFIG_DMAR_FLPY_WA */
2012
2013 /* Initialize each context entry as pass through.*/
2014 static int __init init_context_pass_through(void)
2015 {
2016         struct pci_dev *pdev = NULL;
2017         struct dmar_domain *domain;
2018         int ret;
2019
2020         for_each_pci_dev(pdev) {
2021                 domain = get_domain_for_dev(pdev, DEFAULT_DOMAIN_ADDRESS_WIDTH);
2022                 ret = domain_context_mapping(domain, pdev,
2023                                              CONTEXT_TT_PASS_THROUGH);
2024                 if (ret)
2025                         return ret;
2026         }
2027         return 0;
2028 }
2029
2030 static int md_domain_init(struct dmar_domain *domain, int guest_width);
2031
2032 static int __init si_domain_work_fn(unsigned long start_pfn,
2033                                     unsigned long end_pfn, void *datax)
2034 {
2035         int *ret = datax;
2036
2037         *ret = iommu_domain_identity_map(si_domain,
2038                                          (uint64_t)start_pfn << PAGE_SHIFT,
2039                                          (uint64_t)end_pfn << PAGE_SHIFT);
2040         return *ret;
2041
2042 }
2043
2044 static int si_domain_init(void)
2045 {
2046         struct dmar_drhd_unit *drhd;
2047         struct intel_iommu *iommu;
2048         int nid, ret = 0;
2049
2050         si_domain = alloc_domain();
2051         if (!si_domain)
2052                 return -EFAULT;
2053
2054         pr_debug("Identity mapping domain is domain %d\n", si_domain->id);
2055
2056         for_each_active_iommu(iommu, drhd) {
2057                 ret = iommu_attach_domain(si_domain, iommu);
2058                 if (ret) {
2059                         domain_exit(si_domain);
2060                         return -EFAULT;
2061                 }
2062         }
2063
2064         if (md_domain_init(si_domain, DEFAULT_DOMAIN_ADDRESS_WIDTH)) {
2065                 domain_exit(si_domain);
2066                 return -EFAULT;
2067         }
2068
2069         si_domain->flags = DOMAIN_FLAG_STATIC_IDENTITY;
2070
2071         for_each_online_node(nid) {
2072                 work_with_active_regions(nid, si_domain_work_fn, &ret);
2073                 if (ret)
2074                         return ret;
2075         }
2076
2077         return 0;
2078 }
2079
2080 static void domain_remove_one_dev_info(struct dmar_domain *domain,
2081                                           struct pci_dev *pdev);
2082 static int identity_mapping(struct pci_dev *pdev)
2083 {
2084         struct device_domain_info *info;
2085
2086         if (likely(!iommu_identity_mapping))
2087                 return 0;
2088
2089
2090         list_for_each_entry(info, &si_domain->devices, link)
2091                 if (info->dev == pdev)
2092                         return 1;
2093         return 0;
2094 }
2095
2096 static int domain_add_dev_info(struct dmar_domain *domain,
2097                                   struct pci_dev *pdev)
2098 {
2099         struct device_domain_info *info;
2100         unsigned long flags;
2101
2102         info = alloc_devinfo_mem();
2103         if (!info)
2104                 return -ENOMEM;
2105
2106         info->segment = pci_domain_nr(pdev->bus);
2107         info->bus = pdev->bus->number;
2108         info->devfn = pdev->devfn;
2109         info->dev = pdev;
2110         info->domain = domain;
2111
2112         spin_lock_irqsave(&device_domain_lock, flags);
2113         list_add(&info->link, &domain->devices);
2114         list_add(&info->global, &device_domain_list);
2115         pdev->dev.archdata.iommu = info;
2116         spin_unlock_irqrestore(&device_domain_lock, flags);
2117
2118         return 0;
2119 }
2120
2121 static int iommu_should_identity_map(struct pci_dev *pdev, int startup)
2122 {
2123         if (iommu_identity_mapping == 2)
2124                 return IS_GFX_DEVICE(pdev);
2125
2126         /*
2127          * We want to start off with all devices in the 1:1 domain, and
2128          * take them out later if we find they can't access all of memory.
2129          *
2130          * However, we can't do this for PCI devices behind bridges,
2131          * because all PCI devices behind the same bridge will end up
2132          * with the same source-id on their transactions.
2133          *
2134          * Practically speaking, we can't change things around for these
2135          * devices at run-time, because we can't be sure there'll be no
2136          * DMA transactions in flight for any of their siblings.
2137          * 
2138          * So PCI devices (unless they're on the root bus) as well as
2139          * their parent PCI-PCI or PCIe-PCI bridges must be left _out_ of
2140          * the 1:1 domain, just in _case_ one of their siblings turns out
2141          * not to be able to map all of memory.
2142          */
2143         if (!pdev->is_pcie) {
2144                 if (!pci_is_root_bus(pdev->bus))
2145                         return 0;
2146                 if (pdev->class >> 8 == PCI_CLASS_BRIDGE_PCI)
2147                         return 0;
2148         } else if (pdev->pcie_type == PCI_EXP_TYPE_PCI_BRIDGE)
2149                 return 0;
2150
2151         /* 
2152          * At boot time, we don't yet know if devices will be 64-bit capable.
2153          * Assume that they will -- if they turn out not to be, then we can 
2154          * take them out of the 1:1 domain later.
2155          */
2156         if (!startup)
2157                 return pdev->dma_mask > DMA_BIT_MASK(32);
2158
2159         return 1;
2160 }
2161
2162 static int iommu_prepare_static_identity_mapping(void)
2163 {
2164         struct pci_dev *pdev = NULL;
2165         int ret;
2166
2167         ret = si_domain_init();
2168         if (ret)
2169                 return -EFAULT;
2170
2171         for_each_pci_dev(pdev) {
2172                 if (iommu_should_identity_map(pdev, 1)) {
2173                         printk(KERN_INFO "IOMMU: identity mapping for device %s\n",
2174                                pci_name(pdev));
2175
2176                         ret = domain_context_mapping(si_domain, pdev,
2177                                                      CONTEXT_TT_MULTI_LEVEL);
2178                         if (ret)
2179                                 return ret;
2180                         ret = domain_add_dev_info(si_domain, pdev);
2181                         if (ret)
2182                                 return ret;
2183                 }
2184         }
2185
2186         return 0;
2187 }
2188
2189 int __init init_dmars(void)
2190 {
2191         struct dmar_drhd_unit *drhd;
2192         struct dmar_rmrr_unit *rmrr;
2193         struct pci_dev *pdev;
2194         struct intel_iommu *iommu;
2195         int i, ret;
2196         int pass_through = 1;
2197
2198         /*
2199          * In case pass through can not be enabled, iommu tries to use identity
2200          * mapping.
2201          */
2202         if (iommu_pass_through)
2203                 iommu_identity_mapping = 1;
2204
2205         /*
2206          * for each drhd
2207          *    allocate root
2208          *    initialize and program root entry to not present
2209          * endfor
2210          */
2211         for_each_drhd_unit(drhd) {
2212                 g_num_of_iommus++;
2213                 /*
2214                  * lock not needed as this is only incremented in the single
2215                  * threaded kernel __init code path all other access are read
2216                  * only
2217                  */
2218         }
2219
2220         g_iommus = kcalloc(g_num_of_iommus, sizeof(struct intel_iommu *),
2221                         GFP_KERNEL);
2222         if (!g_iommus) {
2223                 printk(KERN_ERR "Allocating global iommu array failed\n");
2224                 ret = -ENOMEM;
2225                 goto error;
2226         }
2227
2228         deferred_flush = kzalloc(g_num_of_iommus *
2229                 sizeof(struct deferred_flush_tables), GFP_KERNEL);
2230         if (!deferred_flush) {
2231                 kfree(g_iommus);
2232                 ret = -ENOMEM;
2233                 goto error;
2234         }
2235
2236         for_each_drhd_unit(drhd) {
2237                 if (drhd->ignored)
2238                         continue;
2239
2240                 iommu = drhd->iommu;
2241                 g_iommus[iommu->seq_id] = iommu;
2242
2243                 ret = iommu_init_domains(iommu);
2244                 if (ret)
2245                         goto error;
2246
2247                 /*
2248                  * TBD:
2249                  * we could share the same root & context tables
2250                  * amoung all IOMMU's. Need to Split it later.
2251                  */
2252                 ret = iommu_alloc_root_entry(iommu);
2253                 if (ret) {
2254                         printk(KERN_ERR "IOMMU: allocate root entry failed\n");
2255                         goto error;
2256                 }
2257                 if (!ecap_pass_through(iommu->ecap))
2258                         pass_through = 0;
2259         }
2260         if (iommu_pass_through)
2261                 if (!pass_through) {
2262                         printk(KERN_INFO
2263                                "Pass Through is not supported by hardware.\n");
2264                         iommu_pass_through = 0;
2265                 }
2266
2267         /*
2268          * Start from the sane iommu hardware state.
2269          */
2270         for_each_drhd_unit(drhd) {
2271                 if (drhd->ignored)
2272                         continue;
2273
2274                 iommu = drhd->iommu;
2275
2276                 /*
2277                  * If the queued invalidation is already initialized by us
2278                  * (for example, while enabling interrupt-remapping) then
2279                  * we got the things already rolling from a sane state.
2280                  */
2281                 if (iommu->qi)
2282                         continue;
2283
2284                 /*
2285                  * Clear any previous faults.
2286                  */
2287                 dmar_fault(-1, iommu);
2288                 /*
2289                  * Disable queued invalidation if supported and already enabled
2290                  * before OS handover.
2291                  */
2292                 dmar_disable_qi(iommu);
2293         }
2294
2295         for_each_drhd_unit(drhd) {
2296                 if (drhd->ignored)
2297                         continue;
2298
2299                 iommu = drhd->iommu;
2300
2301                 if (dmar_enable_qi(iommu)) {
2302                         /*
2303                          * Queued Invalidate not enabled, use Register Based
2304                          * Invalidate
2305                          */
2306                         iommu->flush.flush_context = __iommu_flush_context;
2307                         iommu->flush.flush_iotlb = __iommu_flush_iotlb;
2308                         printk(KERN_INFO "IOMMU 0x%Lx: using Register based "
2309                                "invalidation\n",
2310                                (unsigned long long)drhd->reg_base_addr);
2311                 } else {
2312                         iommu->flush.flush_context = qi_flush_context;
2313                         iommu->flush.flush_iotlb = qi_flush_iotlb;
2314                         printk(KERN_INFO "IOMMU 0x%Lx: using Queued "
2315                                "invalidation\n",
2316                                (unsigned long long)drhd->reg_base_addr);
2317                 }
2318         }
2319
2320         /*
2321          * If pass through is set and enabled, context entries of all pci
2322          * devices are intialized by pass through translation type.
2323          */
2324         if (iommu_pass_through) {
2325                 ret = init_context_pass_through();
2326                 if (ret) {
2327                         printk(KERN_ERR "IOMMU: Pass through init failed.\n");
2328                         iommu_pass_through = 0;
2329                 }
2330         }
2331
2332         /*
2333          * If pass through is not set or not enabled, setup context entries for
2334          * identity mappings for rmrr, gfx, and isa and may fall back to static
2335          * identity mapping if iommu_identity_mapping is set.
2336          */
2337         if (!iommu_pass_through) {
2338 #ifdef CONFIG_DMAR_BROKEN_GFX_WA
2339                 if (!iommu_identity_mapping)
2340                         iommu_identity_mapping = 2;
2341 #endif
2342                 if (iommu_identity_mapping)
2343                         iommu_prepare_static_identity_mapping();
2344                 /*
2345                  * For each rmrr
2346                  *   for each dev attached to rmrr
2347                  *   do
2348                  *     locate drhd for dev, alloc domain for dev
2349                  *     allocate free domain
2350                  *     allocate page table entries for rmrr
2351                  *     if context not allocated for bus
2352                  *           allocate and init context
2353                  *           set present in root table for this bus
2354                  *     init context with domain, translation etc
2355                  *    endfor
2356                  * endfor
2357                  */
2358                 printk(KERN_INFO "IOMMU: Setting RMRR:\n");
2359                 for_each_rmrr_units(rmrr) {
2360                         for (i = 0; i < rmrr->devices_cnt; i++) {
2361                                 pdev = rmrr->devices[i];
2362                                 /*
2363                                  * some BIOS lists non-exist devices in DMAR
2364                                  * table.
2365                                  */
2366                                 if (!pdev)
2367                                         continue;
2368                                 ret = iommu_prepare_rmrr_dev(rmrr, pdev);
2369                                 if (ret)
2370                                         printk(KERN_ERR
2371                                  "IOMMU: mapping reserved region failed\n");
2372                         }
2373                 }
2374
2375                 iommu_prepare_isa();
2376         }
2377
2378         /*
2379          * for each drhd
2380          *   enable fault log
2381          *   global invalidate context cache
2382          *   global invalidate iotlb
2383          *   enable translation
2384          */
2385         for_each_drhd_unit(drhd) {
2386                 if (drhd->ignored)
2387                         continue;
2388                 iommu = drhd->iommu;
2389
2390                 iommu_flush_write_buffer(iommu);
2391
2392                 ret = dmar_set_interrupt(iommu);
2393                 if (ret)
2394                         goto error;
2395
2396                 iommu_set_root_entry(iommu);
2397
2398                 iommu->flush.flush_context(iommu, 0, 0, 0, DMA_CCMD_GLOBAL_INVL);
2399                 iommu->flush.flush_iotlb(iommu, 0, 0, 0, DMA_TLB_GLOBAL_FLUSH);
2400                 iommu_disable_protect_mem_regions(iommu);
2401
2402                 ret = iommu_enable_translation(iommu);
2403                 if (ret)
2404                         goto error;
2405         }
2406
2407         return 0;
2408 error:
2409         for_each_drhd_unit(drhd) {
2410                 if (drhd->ignored)
2411                         continue;
2412                 iommu = drhd->iommu;
2413                 free_iommu(iommu);
2414         }
2415         kfree(g_iommus);
2416         return ret;
2417 }
2418
2419 /* Returns a number of VTD pages, but aligned to MM page size */
2420 static inline unsigned long aligned_nrpages(unsigned long host_addr,
2421                                             size_t size)
2422 {
2423         host_addr &= ~PAGE_MASK;
2424         return PAGE_ALIGN(host_addr + size) >> VTD_PAGE_SHIFT;
2425 }
2426
2427 /* This takes a number of _MM_ pages, not VTD pages */
2428 static struct iova *intel_alloc_iova(struct device *dev,
2429                                      struct dmar_domain *domain,
2430                                      unsigned long nrpages, uint64_t dma_mask)
2431 {
2432         struct pci_dev *pdev = to_pci_dev(dev);
2433         struct iova *iova = NULL;
2434
2435         /* Restrict dma_mask to the width that the iommu can handle */
2436         dma_mask = min_t(uint64_t, DOMAIN_MAX_ADDR(domain->gaw), dma_mask);
2437
2438         if (!dmar_forcedac && dma_mask > DMA_BIT_MASK(32)) {
2439                 /*
2440                  * First try to allocate an io virtual address in
2441                  * DMA_BIT_MASK(32) and if that fails then try allocating
2442                  * from higher range
2443                  */
2444                 iova = alloc_iova(&domain->iovad, nrpages,
2445                                   IOVA_PFN(DMA_BIT_MASK(32)), 1);
2446                 if (iova)
2447                         return iova;
2448         }
2449         iova = alloc_iova(&domain->iovad, nrpages, IOVA_PFN(dma_mask), 1);
2450         if (unlikely(!iova)) {
2451                 printk(KERN_ERR "Allocating %ld-page iova for %s failed",
2452                        nrpages, pci_name(pdev));
2453                 return NULL;
2454         }
2455
2456         return iova;
2457 }
2458
2459 static struct dmar_domain *
2460 get_valid_domain_for_dev(struct pci_dev *pdev)
2461 {
2462         struct dmar_domain *domain;
2463         int ret;
2464
2465         domain = get_domain_for_dev(pdev,
2466                         DEFAULT_DOMAIN_ADDRESS_WIDTH);
2467         if (!domain) {
2468                 printk(KERN_ERR
2469                         "Allocating domain for %s failed", pci_name(pdev));
2470                 return NULL;
2471         }
2472
2473         /* make sure context mapping is ok */
2474         if (unlikely(!domain_context_mapped(pdev))) {
2475                 ret = domain_context_mapping(domain, pdev,
2476                                              CONTEXT_TT_MULTI_LEVEL);
2477                 if (ret) {
2478                         printk(KERN_ERR
2479                                 "Domain context map for %s failed",
2480                                 pci_name(pdev));
2481                         return NULL;
2482                 }
2483         }
2484
2485         return domain;
2486 }
2487
2488 static int iommu_dummy(struct pci_dev *pdev)
2489 {
2490         return pdev->dev.archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO;
2491 }
2492
2493 /* Check if the pdev needs to go through non-identity map and unmap process.*/
2494 static int iommu_no_mapping(struct device *dev)
2495 {
2496         struct pci_dev *pdev;
2497         int found;
2498
2499         if (unlikely(dev->bus != &pci_bus_type))
2500                 return 1;
2501
2502         pdev = to_pci_dev(dev);
2503         if (iommu_dummy(pdev))
2504                 return 1;
2505
2506         if (!iommu_identity_mapping)
2507                 return 0;
2508
2509         found = identity_mapping(pdev);
2510         if (found) {
2511                 if (iommu_should_identity_map(pdev, 0))
2512                         return 1;
2513                 else {
2514                         /*
2515                          * 32 bit DMA is removed from si_domain and fall back
2516                          * to non-identity mapping.
2517                          */
2518                         domain_remove_one_dev_info(si_domain, pdev);
2519                         printk(KERN_INFO "32bit %s uses non-identity mapping\n",
2520                                pci_name(pdev));
2521                         return 0;
2522                 }
2523         } else {
2524                 /*
2525                  * In case of a detached 64 bit DMA device from vm, the device
2526                  * is put into si_domain for identity mapping.
2527                  */
2528                 if (iommu_should_identity_map(pdev, 0)) {
2529                         int ret;
2530                         ret = domain_add_dev_info(si_domain, pdev);
2531                         if (ret)
2532                                 return 0;
2533                         ret = domain_context_mapping(si_domain, pdev, CONTEXT_TT_MULTI_LEVEL);
2534                         if (!ret) {
2535                                 printk(KERN_INFO "64bit %s uses identity mapping\n",
2536                                        pci_name(pdev));
2537                                 return 1;
2538                         }
2539                 }
2540         }
2541
2542         return 0;
2543 }
2544
2545 static dma_addr_t __intel_map_single(struct device *hwdev, phys_addr_t paddr,
2546                                      size_t size, int dir, u64 dma_mask)
2547 {
2548         struct pci_dev *pdev = to_pci_dev(hwdev);
2549         struct dmar_domain *domain;
2550         phys_addr_t start_paddr;
2551         struct iova *iova;
2552         int prot = 0;
2553         int ret;
2554         struct intel_iommu *iommu;
2555
2556         BUG_ON(dir == DMA_NONE);
2557
2558         if (iommu_no_mapping(hwdev))
2559                 return paddr;
2560
2561         domain = get_valid_domain_for_dev(pdev);
2562         if (!domain)
2563                 return 0;
2564
2565         iommu = domain_get_iommu(domain);
2566         size = aligned_nrpages(paddr, size);
2567
2568         iova = intel_alloc_iova(hwdev, domain, dma_to_mm_pfn(size),
2569                                 pdev->dma_mask);
2570         if (!iova)
2571                 goto error;
2572
2573         /*
2574          * Check if DMAR supports zero-length reads on write only
2575          * mappings..
2576          */
2577         if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL || \
2578                         !cap_zlr(iommu->cap))
2579                 prot |= DMA_PTE_READ;
2580         if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
2581                 prot |= DMA_PTE_WRITE;
2582         /*
2583          * paddr - (paddr + size) might be partial page, we should map the whole
2584          * page.  Note: if two part of one page are separately mapped, we
2585          * might have two guest_addr mapping to the same host paddr, but this
2586          * is not a big problem
2587          */
2588         ret = domain_pfn_mapping(domain, mm_to_dma_pfn(iova->pfn_lo),
2589                                  paddr >> VTD_PAGE_SHIFT, size, prot);
2590         if (ret)
2591                 goto error;
2592
2593         /* it's a non-present to present mapping. Only flush if caching mode */
2594         if (cap_caching_mode(iommu->cap))
2595                 iommu_flush_iotlb_psi(iommu, 0, mm_to_dma_pfn(iova->pfn_lo), size);
2596         else
2597                 iommu_flush_write_buffer(iommu);
2598
2599         start_paddr = (phys_addr_t)iova->pfn_lo << PAGE_SHIFT;
2600         start_paddr += paddr & ~PAGE_MASK;
2601         return start_paddr;
2602
2603 error:
2604         if (iova)
2605                 __free_iova(&domain->iovad, iova);
2606         printk(KERN_ERR"Device %s request: %zx@%llx dir %d --- failed\n",
2607                 pci_name(pdev), size, (unsigned long long)paddr, dir);
2608         return 0;
2609 }
2610
2611 static dma_addr_t intel_map_page(struct device *dev, struct page *page,
2612                                  unsigned long offset, size_t size,
2613                                  enum dma_data_direction dir,
2614                                  struct dma_attrs *attrs)
2615 {
2616         return __intel_map_single(dev, page_to_phys(page) + offset, size,
2617                                   dir, to_pci_dev(dev)->dma_mask);
2618 }
2619
2620 static void flush_unmaps(void)
2621 {
2622         int i, j;
2623
2624         timer_on = 0;
2625
2626         /* just flush them all */
2627         for (i = 0; i < g_num_of_iommus; i++) {
2628                 struct intel_iommu *iommu = g_iommus[i];
2629                 if (!iommu)
2630                         continue;
2631
2632                 if (!deferred_flush[i].next)
2633                         continue;
2634
2635                 iommu->flush.flush_iotlb(iommu, 0, 0, 0,
2636                                          DMA_TLB_GLOBAL_FLUSH);
2637                 for (j = 0; j < deferred_flush[i].next; j++) {
2638                         unsigned long mask;
2639                         struct iova *iova = deferred_flush[i].iova[j];
2640
2641                         mask = (iova->pfn_hi - iova->pfn_lo + 1) << PAGE_SHIFT;
2642                         mask = ilog2(mask >> VTD_PAGE_SHIFT);
2643                         iommu_flush_dev_iotlb(deferred_flush[i].domain[j],
2644                                         iova->pfn_lo << PAGE_SHIFT, mask);
2645                         __free_iova(&deferred_flush[i].domain[j]->iovad, iova);
2646                 }
2647                 deferred_flush[i].next = 0;
2648         }
2649
2650         list_size = 0;
2651 }
2652
2653 static void flush_unmaps_timeout(unsigned long data)
2654 {
2655         unsigned long flags;
2656
2657         spin_lock_irqsave(&async_umap_flush_lock, flags);
2658         flush_unmaps();
2659         spin_unlock_irqrestore(&async_umap_flush_lock, flags);
2660 }
2661
2662 static void add_unmap(struct dmar_domain *dom, struct iova *iova)
2663 {
2664         unsigned long flags;
2665         int next, iommu_id;
2666         struct intel_iommu *iommu;
2667
2668         spin_lock_irqsave(&async_umap_flush_lock, flags);
2669         if (list_size == HIGH_WATER_MARK)
2670                 flush_unmaps();
2671
2672         iommu = domain_get_iommu(dom);
2673         iommu_id = iommu->seq_id;
2674
2675         next = deferred_flush[iommu_id].next;
2676         deferred_flush[iommu_id].domain[next] = dom;
2677         deferred_flush[iommu_id].iova[next] = iova;
2678         deferred_flush[iommu_id].next++;
2679
2680         if (!timer_on) {
2681                 mod_timer(&unmap_timer, jiffies + msecs_to_jiffies(10));
2682                 timer_on = 1;
2683         }
2684         list_size++;
2685         spin_unlock_irqrestore(&async_umap_flush_lock, flags);
2686 }
2687
2688 static void intel_unmap_page(struct device *dev, dma_addr_t dev_addr,
2689                              size_t size, enum dma_data_direction dir,
2690                              struct dma_attrs *attrs)
2691 {
2692         struct pci_dev *pdev = to_pci_dev(dev);
2693         struct dmar_domain *domain;
2694         unsigned long start_pfn, last_pfn;
2695         struct iova *iova;
2696         struct intel_iommu *iommu;
2697
2698         if (iommu_no_mapping(dev))
2699                 return;
2700
2701         domain = find_domain(pdev);
2702         BUG_ON(!domain);
2703
2704         iommu = domain_get_iommu(domain);
2705
2706         iova = find_iova(&domain->iovad, IOVA_PFN(dev_addr));
2707         if (WARN_ONCE(!iova, "Driver unmaps unmatched page at PFN %llx\n",
2708                       (unsigned long long)dev_addr))
2709                 return;
2710
2711         start_pfn = mm_to_dma_pfn(iova->pfn_lo);
2712         last_pfn = mm_to_dma_pfn(iova->pfn_hi + 1) - 1;
2713
2714         pr_debug("Device %s unmapping: pfn %lx-%lx\n",
2715                  pci_name(pdev), start_pfn, last_pfn);
2716
2717         /*  clear the whole page */
2718         dma_pte_clear_range(domain, start_pfn, last_pfn);
2719
2720         /* free page tables */
2721         dma_pte_free_pagetable(domain, start_pfn, last_pfn);
2722
2723         if (intel_iommu_strict) {
2724                 iommu_flush_iotlb_psi(iommu, domain->id, start_pfn,
2725                                       last_pfn - start_pfn + 1);
2726                 /* free iova */
2727                 __free_iova(&domain->iovad, iova);
2728         } else {
2729                 add_unmap(domain, iova);
2730                 /*
2731                  * queue up the release of the unmap to save the 1/6th of the
2732                  * cpu used up by the iotlb flush operation...
2733                  */
2734         }
2735 }
2736
2737 static void intel_unmap_single(struct device *dev, dma_addr_t dev_addr, size_t size,
2738                                int dir)
2739 {
2740         intel_unmap_page(dev, dev_addr, size, dir, NULL);
2741 }
2742
2743 static void *intel_alloc_coherent(struct device *hwdev, size_t size,
2744                                   dma_addr_t *dma_handle, gfp_t flags)
2745 {
2746         void *vaddr;
2747         int order;
2748
2749         size = PAGE_ALIGN(size);
2750         order = get_order(size);
2751         flags &= ~(GFP_DMA | GFP_DMA32);
2752
2753         vaddr = (void *)__get_free_pages(flags, order);
2754         if (!vaddr)
2755                 return NULL;
2756         memset(vaddr, 0, size);
2757
2758         *dma_handle = __intel_map_single(hwdev, virt_to_bus(vaddr), size,
2759                                          DMA_BIDIRECTIONAL,
2760                                          hwdev->coherent_dma_mask);
2761         if (*dma_handle)
2762                 return vaddr;
2763         free_pages((unsigned long)vaddr, order);
2764         return NULL;
2765 }
2766
2767 static void intel_free_coherent(struct device *hwdev, size_t size, void *vaddr,
2768                                 dma_addr_t dma_handle)
2769 {
2770         int order;
2771
2772         size = PAGE_ALIGN(size);
2773         order = get_order(size);
2774
2775         intel_unmap_single(hwdev, dma_handle, size, DMA_BIDIRECTIONAL);
2776         free_pages((unsigned long)vaddr, order);
2777 }
2778
2779 static void intel_unmap_sg(struct device *hwdev, struct scatterlist *sglist,
2780                            int nelems, enum dma_data_direction dir,
2781                            struct dma_attrs *attrs)
2782 {
2783         struct pci_dev *pdev = to_pci_dev(hwdev);
2784         struct dmar_domain *domain;
2785         unsigned long start_pfn, last_pfn;
2786         struct iova *iova;
2787         struct intel_iommu *iommu;
2788
2789         if (iommu_no_mapping(hwdev))
2790                 return;
2791
2792         domain = find_domain(pdev);
2793         BUG_ON(!domain);
2794
2795         iommu = domain_get_iommu(domain);
2796
2797         iova = find_iova(&domain->iovad, IOVA_PFN(sglist[0].dma_address));
2798         if (WARN_ONCE(!iova, "Driver unmaps unmatched sglist at PFN %llx\n",
2799                       (unsigned long long)sglist[0].dma_address))
2800                 return;
2801
2802         start_pfn = mm_to_dma_pfn(iova->pfn_lo);
2803         last_pfn = mm_to_dma_pfn(iova->pfn_hi + 1) - 1;
2804
2805         /*  clear the whole page */
2806         dma_pte_clear_range(domain, start_pfn, last_pfn);
2807
2808         /* free page tables */
2809         dma_pte_free_pagetable(domain, start_pfn, last_pfn);
2810
2811         iommu_flush_iotlb_psi(iommu, domain->id, start_pfn,
2812                               (last_pfn - start_pfn + 1));
2813
2814         /* free iova */
2815         __free_iova(&domain->iovad, iova);
2816 }
2817
2818 static int intel_nontranslate_map_sg(struct device *hddev,
2819         struct scatterlist *sglist, int nelems, int dir)
2820 {
2821         int i;
2822         struct scatterlist *sg;
2823
2824         for_each_sg(sglist, sg, nelems, i) {
2825                 BUG_ON(!sg_page(sg));
2826                 sg->dma_address = page_to_phys(sg_page(sg)) + sg->offset;
2827                 sg->dma_length = sg->length;
2828         }
2829         return nelems;
2830 }
2831
2832 static int intel_map_sg(struct device *hwdev, struct scatterlist *sglist, int nelems,
2833                         enum dma_data_direction dir, struct dma_attrs *attrs)
2834 {
2835         int i;
2836         struct pci_dev *pdev = to_pci_dev(hwdev);
2837         struct dmar_domain *domain;
2838         size_t size = 0;
2839         int prot = 0;
2840         size_t offset_pfn = 0;
2841         struct iova *iova = NULL;
2842         int ret;
2843         struct scatterlist *sg;
2844         unsigned long start_vpfn;
2845         struct intel_iommu *iommu;
2846
2847         BUG_ON(dir == DMA_NONE);
2848         if (iommu_no_mapping(hwdev))
2849                 return intel_nontranslate_map_sg(hwdev, sglist, nelems, dir);
2850
2851         domain = get_valid_domain_for_dev(pdev);
2852         if (!domain)
2853                 return 0;
2854
2855         iommu = domain_get_iommu(domain);
2856
2857         for_each_sg(sglist, sg, nelems, i)
2858                 size += aligned_nrpages(sg->offset, sg->length);
2859
2860         iova = intel_alloc_iova(hwdev, domain, dma_to_mm_pfn(size),
2861                                 pdev->dma_mask);
2862         if (!iova) {
2863                 sglist->dma_length = 0;
2864                 return 0;
2865         }
2866
2867         /*
2868          * Check if DMAR supports zero-length reads on write only
2869          * mappings..
2870          */
2871         if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL || \
2872                         !cap_zlr(iommu->cap))
2873                 prot |= DMA_PTE_READ;
2874         if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
2875                 prot |= DMA_PTE_WRITE;
2876
2877         start_vpfn = mm_to_dma_pfn(iova->pfn_lo);
2878
2879         ret = domain_sg_mapping(domain, start_vpfn, sglist, mm_to_dma_pfn(size), prot);
2880         if (unlikely(ret)) {
2881                 /*  clear the page */
2882                 dma_pte_clear_range(domain, start_vpfn,
2883                                     start_vpfn + size - 1);
2884                 /* free page tables */
2885                 dma_pte_free_pagetable(domain, start_vpfn,
2886                                        start_vpfn + size - 1);
2887                 /* free iova */
2888                 __free_iova(&domain->iovad, iova);
2889                 return 0;
2890         }
2891
2892         /* it's a non-present to present mapping. Only flush if caching mode */
2893         if (cap_caching_mode(iommu->cap))
2894                 iommu_flush_iotlb_psi(iommu, 0, start_vpfn, offset_pfn);
2895         else
2896                 iommu_flush_write_buffer(iommu);
2897
2898         return nelems;
2899 }
2900
2901 static int intel_mapping_error(struct device *dev, dma_addr_t dma_addr)
2902 {
2903         return !dma_addr;
2904 }
2905
2906 struct dma_map_ops intel_dma_ops = {
2907         .alloc_coherent = intel_alloc_coherent,
2908         .free_coherent = intel_free_coherent,
2909         .map_sg = intel_map_sg,
2910         .unmap_sg = intel_unmap_sg,
2911         .map_page = intel_map_page,
2912         .unmap_page = intel_unmap_page,
2913         .mapping_error = intel_mapping_error,
2914 };
2915
2916 static inline int iommu_domain_cache_init(void)
2917 {
2918         int ret = 0;
2919
2920         iommu_domain_cache = kmem_cache_create("iommu_domain",
2921                                          sizeof(struct dmar_domain),
2922                                          0,
2923                                          SLAB_HWCACHE_ALIGN,
2924
2925                                          NULL);
2926         if (!iommu_domain_cache) {
2927                 printk(KERN_ERR "Couldn't create iommu_domain cache\n");
2928                 ret = -ENOMEM;
2929         }
2930
2931         return ret;
2932 }
2933
2934 static inline int iommu_devinfo_cache_init(void)
2935 {
2936         int ret = 0;
2937
2938         iommu_devinfo_cache = kmem_cache_create("iommu_devinfo",
2939                                          sizeof(struct device_domain_info),
2940                                          0,
2941                                          SLAB_HWCACHE_ALIGN,
2942                                          NULL);
2943         if (!iommu_devinfo_cache) {
2944                 printk(KERN_ERR "Couldn't create devinfo cache\n");
2945                 ret = -ENOMEM;
2946         }
2947
2948         return ret;
2949 }
2950
2951 static inline int iommu_iova_cache_init(void)
2952 {
2953         int ret = 0;
2954
2955         iommu_iova_cache = kmem_cache_create("iommu_iova",
2956                                          sizeof(struct iova),
2957                                          0,
2958                                          SLAB_HWCACHE_ALIGN,
2959                                          NULL);
2960         if (!iommu_iova_cache) {
2961                 printk(KERN_ERR "Couldn't create iova cache\n");
2962                 ret = -ENOMEM;
2963         }
2964
2965         return ret;
2966 }
2967
2968 static int __init iommu_init_mempool(void)
2969 {
2970         int ret;
2971         ret = iommu_iova_cache_init();
2972         if (ret)
2973                 return ret;
2974
2975         ret = iommu_domain_cache_init();
2976         if (ret)
2977                 goto domain_error;
2978
2979         ret = iommu_devinfo_cache_init();
2980         if (!ret)
2981                 return ret;
2982
2983         kmem_cache_destroy(iommu_domain_cache);
2984 domain_error:
2985         kmem_cache_destroy(iommu_iova_cache);
2986
2987         return -ENOMEM;
2988 }
2989
2990 static void __init iommu_exit_mempool(void)
2991 {
2992         kmem_cache_destroy(iommu_devinfo_cache);
2993         kmem_cache_destroy(iommu_domain_cache);
2994         kmem_cache_destroy(iommu_iova_cache);
2995
2996 }
2997
2998 static void __init init_no_remapping_devices(void)
2999 {
3000         struct dmar_drhd_unit *drhd;
3001
3002         for_each_drhd_unit(drhd) {
3003                 if (!drhd->include_all) {
3004                         int i;
3005                         for (i = 0; i < drhd->devices_cnt; i++)
3006                                 if (drhd->devices[i] != NULL)
3007                                         break;
3008                         /* ignore DMAR unit if no pci devices exist */
3009                         if (i == drhd->devices_cnt)
3010                                 drhd->ignored = 1;
3011                 }
3012         }
3013
3014         if (dmar_map_gfx)
3015                 return;
3016
3017         for_each_drhd_unit(drhd) {
3018                 int i;
3019                 if (drhd->ignored || drhd->include_all)
3020                         continue;
3021
3022                 for (i = 0; i < drhd->devices_cnt; i++)
3023                         if (drhd->devices[i] &&
3024                                 !IS_GFX_DEVICE(drhd->devices[i]))
3025                                 break;
3026
3027                 if (i < drhd->devices_cnt)
3028                         continue;
3029
3030                 /* bypass IOMMU if it is just for gfx devices */
3031                 drhd->ignored = 1;
3032                 for (i = 0; i < drhd->devices_cnt; i++) {
3033                         if (!drhd->devices[i])
3034                                 continue;
3035                         drhd->devices[i]->dev.archdata.iommu = DUMMY_DEVICE_DOMAIN_INFO;
3036                 }
3037         }
3038 }
3039
3040 #ifdef CONFIG_SUSPEND
3041 static int init_iommu_hw(void)
3042 {
3043         struct dmar_drhd_unit *drhd;
3044         struct intel_iommu *iommu = NULL;
3045
3046         for_each_active_iommu(iommu, drhd)
3047                 if (iommu->qi)
3048                         dmar_reenable_qi(iommu);
3049
3050         for_each_active_iommu(iommu, drhd) {
3051                 iommu_flush_write_buffer(iommu);
3052
3053                 iommu_set_root_entry(iommu);
3054
3055                 iommu->flush.flush_context(iommu, 0, 0, 0,
3056                                            DMA_CCMD_GLOBAL_INVL);
3057                 iommu->flush.flush_iotlb(iommu, 0, 0, 0,
3058                                          DMA_TLB_GLOBAL_FLUSH);
3059                 iommu_disable_protect_mem_regions(iommu);
3060                 iommu_enable_translation(iommu);
3061         }
3062
3063         return 0;
3064 }
3065
3066 static void iommu_flush_all(void)
3067 {
3068         struct dmar_drhd_unit *drhd;
3069         struct intel_iommu *iommu;
3070
3071         for_each_active_iommu(iommu, drhd) {
3072                 iommu->flush.flush_context(iommu, 0, 0, 0,
3073                                            DMA_CCMD_GLOBAL_INVL);
3074                 iommu->flush.flush_iotlb(iommu, 0, 0, 0,
3075                                          DMA_TLB_GLOBAL_FLUSH);
3076         }
3077 }
3078
3079 static int iommu_suspend(struct sys_device *dev, pm_message_t state)
3080 {
3081         struct dmar_drhd_unit *drhd;
3082         struct intel_iommu *iommu = NULL;
3083         unsigned long flag;
3084
3085         for_each_active_iommu(iommu, drhd) {
3086                 iommu->iommu_state = kzalloc(sizeof(u32) * MAX_SR_DMAR_REGS,
3087                                                  GFP_ATOMIC);
3088                 if (!iommu->iommu_state)
3089                         goto nomem;
3090         }
3091
3092         iommu_flush_all();
3093
3094         for_each_active_iommu(iommu, drhd) {
3095                 iommu_disable_translation(iommu);
3096
3097                 spin_lock_irqsave(&iommu->register_lock, flag);
3098
3099                 iommu->iommu_state[SR_DMAR_FECTL_REG] =
3100                         readl(iommu->reg + DMAR_FECTL_REG);
3101                 iommu->iommu_state[SR_DMAR_FEDATA_REG] =
3102                         readl(iommu->reg + DMAR_FEDATA_REG);
3103                 iommu->iommu_state[SR_DMAR_FEADDR_REG] =
3104                         readl(iommu->reg + DMAR_FEADDR_REG);
3105                 iommu->iommu_state[SR_DMAR_FEUADDR_REG] =
3106                         readl(iommu->reg + DMAR_FEUADDR_REG);
3107
3108                 spin_unlock_irqrestore(&iommu->register_lock, flag);
3109         }
3110         return 0;
3111
3112 nomem:
3113         for_each_active_iommu(iommu, drhd)
3114                 kfree(iommu->iommu_state);
3115
3116         return -ENOMEM;
3117 }
3118
3119 static int iommu_resume(struct sys_device *dev)
3120 {
3121         struct dmar_drhd_unit *drhd;
3122         struct intel_iommu *iommu = NULL;
3123         unsigned long flag;
3124
3125         if (init_iommu_hw()) {
3126                 WARN(1, "IOMMU setup failed, DMAR can not resume!\n");
3127                 return -EIO;
3128         }
3129
3130         for_each_active_iommu(iommu, drhd) {
3131
3132                 spin_lock_irqsave(&iommu->register_lock, flag);
3133
3134                 writel(iommu->iommu_state[SR_DMAR_FECTL_REG],
3135                         iommu->reg + DMAR_FECTL_REG);
3136                 writel(iommu->iommu_state[SR_DMAR_FEDATA_REG],
3137                         iommu->reg + DMAR_FEDATA_REG);
3138                 writel(iommu->iommu_state[SR_DMAR_FEADDR_REG],
3139                         iommu->reg + DMAR_FEADDR_REG);
3140                 writel(iommu->iommu_state[SR_DMAR_FEUADDR_REG],
3141                         iommu->reg + DMAR_FEUADDR_REG);
3142
3143                 spin_unlock_irqrestore(&iommu->register_lock, flag);
3144         }
3145
3146         for_each_active_iommu(iommu, drhd)
3147                 kfree(iommu->iommu_state);
3148
3149         return 0;
3150 }
3151
3152 static struct sysdev_class iommu_sysclass = {
3153         .name           = "iommu",
3154         .resume         = iommu_resume,
3155         .suspend        = iommu_suspend,
3156 };
3157
3158 static struct sys_device device_iommu = {
3159         .cls    = &iommu_sysclass,
3160 };
3161
3162 static int __init init_iommu_sysfs(void)
3163 {
3164         int error;
3165
3166         error = sysdev_class_register(&iommu_sysclass);
3167         if (error)
3168                 return error;
3169
3170         error = sysdev_register(&device_iommu);
3171         if (error)
3172                 sysdev_class_unregister(&iommu_sysclass);
3173
3174         return error;
3175 }
3176
3177 #else
3178 static int __init init_iommu_sysfs(void)
3179 {
3180         return 0;
3181 }
3182 #endif  /* CONFIG_PM */
3183
3184 int __init intel_iommu_init(void)
3185 {
3186         int ret = 0;
3187         int force_on = 0;
3188
3189         /* VT-d is required for a TXT/tboot launch, so enforce that */
3190         force_on = tboot_force_iommu();
3191
3192         if (dmar_table_init()) {
3193                 if (force_on)
3194                         panic("tboot: Failed to initialize DMAR table\n");
3195                 return  -ENODEV;
3196         }
3197
3198         if (dmar_dev_scope_init()) {
3199                 if (force_on)
3200                         panic("tboot: Failed to initialize DMAR device scope\n");
3201                 return  -ENODEV;
3202         }
3203
3204         /*
3205          * Check the need for DMA-remapping initialization now.
3206          * Above initialization will also be used by Interrupt-remapping.
3207          */
3208         if (no_iommu || (swiotlb && !iommu_pass_through) || dmar_disabled)
3209                 return -ENODEV;
3210
3211         iommu_init_mempool();
3212         dmar_init_reserved_ranges();
3213
3214         init_no_remapping_devices();
3215
3216         ret = init_dmars();
3217         if (ret) {
3218                 if (force_on)
3219                         panic("tboot: Failed to initialize DMARs\n");
3220                 printk(KERN_ERR "IOMMU: dmar init failed\n");
3221                 put_iova_domain(&reserved_iova_list);
3222                 iommu_exit_mempool();
3223                 return ret;
3224         }
3225         printk(KERN_INFO
3226         "PCI-DMA: Intel(R) Virtualization Technology for Directed I/O\n");
3227
3228         init_timer(&unmap_timer);
3229         force_iommu = 1;
3230
3231         if (!iommu_pass_through) {
3232                 printk(KERN_INFO
3233                        "Multi-level page-table translation for DMAR.\n");
3234                 dma_ops = &intel_dma_ops;
3235         } else
3236                 printk(KERN_INFO
3237                        "DMAR: Pass through translation for DMAR.\n");
3238
3239         init_iommu_sysfs();
3240
3241         register_iommu(&intel_iommu_ops);
3242
3243         return 0;
3244 }
3245
3246 static void iommu_detach_dependent_devices(struct intel_iommu *iommu,
3247                                            struct pci_dev *pdev)
3248 {
3249         struct pci_dev *tmp, *parent;
3250
3251         if (!iommu || !pdev)
3252                 return;
3253
3254         /* dependent device detach */
3255         tmp = pci_find_upstream_pcie_bridge(pdev);
3256         /* Secondary interface's bus number and devfn 0 */
3257         if (tmp) {
3258                 parent = pdev->bus->self;
3259                 while (parent != tmp) {
3260                         iommu_detach_dev(iommu, parent->bus->number,
3261                                          parent->devfn);
3262                         parent = parent->bus->self;
3263                 }
3264                 if (tmp->is_pcie) /* this is a PCIE-to-PCI bridge */
3265                         iommu_detach_dev(iommu,
3266                                 tmp->subordinate->number, 0);
3267                 else /* this is a legacy PCI bridge */
3268                         iommu_detach_dev(iommu, tmp->bus->number,
3269                                          tmp->devfn);
3270         }
3271 }
3272
3273 static void domain_remove_one_dev_info(struct dmar_domain *domain,
3274                                           struct pci_dev *pdev)
3275 {
3276         struct device_domain_info *info;
3277         struct intel_iommu *iommu;
3278         unsigned long flags;
3279         int found = 0;
3280         struct list_head *entry, *tmp;
3281
3282         iommu = device_to_iommu(pci_domain_nr(pdev->bus), pdev->bus->number,
3283                                 pdev->devfn);
3284         if (!iommu)
3285                 return;
3286
3287         spin_lock_irqsave(&device_domain_lock, flags);
3288         list_for_each_safe(entry, tmp, &domain->devices) {
3289                 info = list_entry(entry, struct device_domain_info, link);
3290                 /* No need to compare PCI domain; it has to be the same */
3291                 if (info->bus == pdev->bus->number &&
3292                     info->devfn == pdev->devfn) {
3293                         list_del(&info->link);
3294                         list_del(&info->global);
3295                         if (info->dev)
3296                                 info->dev->dev.archdata.iommu = NULL;
3297                         spin_unlock_irqrestore(&device_domain_lock, flags);
3298
3299                         iommu_disable_dev_iotlb(info);
3300                         iommu_detach_dev(iommu, info->bus, info->devfn);
3301                         iommu_detach_dependent_devices(iommu, pdev);
3302                         free_devinfo_mem(info);
3303
3304                         spin_lock_irqsave(&device_domain_lock, flags);
3305
3306                         if (found)
3307                                 break;
3308                         else
3309                                 continue;
3310                 }
3311
3312                 /* if there is no other devices under the same iommu
3313                  * owned by this domain, clear this iommu in iommu_bmp
3314                  * update iommu count and coherency
3315                  */
3316                 if (iommu == device_to_iommu(info->segment, info->bus,
3317                                             info->devfn))
3318                         found = 1;
3319         }
3320
3321         if (found == 0) {
3322                 unsigned long tmp_flags;
3323                 spin_lock_irqsave(&domain->iommu_lock, tmp_flags);
3324                 clear_bit(iommu->seq_id, &domain->iommu_bmp);
3325                 domain->iommu_count--;
3326                 domain_update_iommu_cap(domain);
3327                 spin_unlock_irqrestore(&domain->iommu_lock, tmp_flags);
3328         }
3329
3330         spin_unlock_irqrestore(&device_domain_lock, flags);
3331 }
3332
3333 static void vm_domain_remove_all_dev_info(struct dmar_domain *domain)
3334 {
3335         struct device_domain_info *info;
3336         struct intel_iommu *iommu;
3337         unsigned long flags1, flags2;
3338
3339         spin_lock_irqsave(&device_domain_lock, flags1);
3340         while (!list_empty(&domain->devices)) {
3341                 info = list_entry(domain->devices.next,
3342                         struct device_domain_info, link);
3343                 list_del(&info->link);
3344                 list_del(&info->global);
3345                 if (info->dev)
3346                         info->dev->dev.archdata.iommu = NULL;
3347
3348                 spin_unlock_irqrestore(&device_domain_lock, flags1);
3349
3350                 iommu_disable_dev_iotlb(info);
3351                 iommu = device_to_iommu(info->segment, info->bus, info->devfn);
3352                 iommu_detach_dev(iommu, info->bus, info->devfn);
3353                 iommu_detach_dependent_devices(iommu, info->dev);
3354
3355                 /* clear this iommu in iommu_bmp, update iommu count
3356                  * and capabilities
3357                  */
3358                 spin_lock_irqsave(&domain->iommu_lock, flags2);
3359                 if (test_and_clear_bit(iommu->seq_id,
3360                                        &domain->iommu_bmp)) {
3361                         domain->iommu_count--;
3362                         domain_update_iommu_cap(domain);
3363                 }
3364                 spin_unlock_irqrestore(&domain->iommu_lock, flags2);
3365
3366                 free_devinfo_mem(info);
3367                 spin_lock_irqsave(&device_domain_lock, flags1);
3368         }
3369         spin_unlock_irqrestore(&device_domain_lock, flags1);
3370 }
3371
3372 /* domain id for virtual machine, it won't be set in context */
3373 static unsigned long vm_domid;
3374
3375 static int vm_domain_min_agaw(struct dmar_domain *domain)
3376 {
3377         int i;
3378         int min_agaw = domain->agaw;
3379
3380         i = find_first_bit(&domain->iommu_bmp, g_num_of_iommus);
3381         for (; i < g_num_of_iommus; ) {
3382                 if (min_agaw > g_iommus[i]->agaw)
3383                         min_agaw = g_iommus[i]->agaw;
3384
3385                 i = find_next_bit(&domain->iommu_bmp, g_num_of_iommus, i+1);
3386         }
3387
3388         return min_agaw;
3389 }
3390
3391 static struct dmar_domain *iommu_alloc_vm_domain(void)
3392 {
3393         struct dmar_domain *domain;
3394
3395         domain = alloc_domain_mem();
3396         if (!domain)
3397                 return NULL;
3398
3399         domain->id = vm_domid++;
3400         memset(&domain->iommu_bmp, 0, sizeof(unsigned long));
3401         domain->flags = DOMAIN_FLAG_VIRTUAL_MACHINE;
3402
3403         return domain;
3404 }
3405
3406 static int md_domain_init(struct dmar_domain *domain, int guest_width)
3407 {
3408         int adjust_width;
3409
3410         init_iova_domain(&domain->iovad, DMA_32BIT_PFN);
3411         spin_lock_init(&domain->iommu_lock);
3412
3413         domain_reserve_special_ranges(domain);
3414
3415         /* calculate AGAW */
3416         domain->gaw = guest_width;
3417         adjust_width = guestwidth_to_adjustwidth(guest_width);
3418         domain->agaw = width_to_agaw(adjust_width);
3419
3420         INIT_LIST_HEAD(&domain->devices);
3421
3422         domain->iommu_count = 0;
3423         domain->iommu_coherency = 0;
3424         domain->max_addr = 0;
3425
3426         /* always allocate the top pgd */
3427         domain->pgd = (struct dma_pte *)alloc_pgtable_page();
3428         if (!domain->pgd)
3429                 return -ENOMEM;
3430         domain_flush_cache(domain, domain->pgd, PAGE_SIZE);
3431         return 0;
3432 }
3433
3434 static void iommu_free_vm_domain(struct dmar_domain *domain)
3435 {
3436         unsigned long flags;
3437         struct dmar_drhd_unit *drhd;
3438         struct intel_iommu *iommu;
3439         unsigned long i;
3440         unsigned long ndomains;
3441
3442         for_each_drhd_unit(drhd) {
3443                 if (drhd->ignored)
3444                         continue;
3445                 iommu = drhd->iommu;
3446
3447                 ndomains = cap_ndoms(iommu->cap);
3448                 i = find_first_bit(iommu->domain_ids, ndomains);
3449                 for (; i < ndomains; ) {
3450                         if (iommu->domains[i] == domain) {
3451                                 spin_lock_irqsave(&iommu->lock, flags);
3452                                 clear_bit(i, iommu->domain_ids);
3453                                 iommu->domains[i] = NULL;
3454                                 spin_unlock_irqrestore(&iommu->lock, flags);
3455                                 break;
3456                         }
3457                         i = find_next_bit(iommu->domain_ids, ndomains, i+1);
3458                 }
3459         }
3460 }
3461
3462 static void vm_domain_exit(struct dmar_domain *domain)
3463 {
3464         /* Domain 0 is reserved, so dont process it */
3465         if (!domain)
3466                 return;
3467
3468         vm_domain_remove_all_dev_info(domain);
3469         /* destroy iovas */
3470         put_iova_domain(&domain->iovad);
3471
3472         /* clear ptes */
3473         dma_pte_clear_range(domain, 0, DOMAIN_MAX_PFN(domain->gaw));
3474
3475         /* free page tables */
3476         dma_pte_free_pagetable(domain, 0, DOMAIN_MAX_PFN(domain->gaw));
3477
3478         iommu_free_vm_domain(domain);
3479         free_domain_mem(domain);
3480 }
3481
3482 static int intel_iommu_domain_init(struct iommu_domain *domain)
3483 {
3484         struct dmar_domain *dmar_domain;
3485
3486         dmar_domain = iommu_alloc_vm_domain();
3487         if (!dmar_domain) {
3488                 printk(KERN_ERR
3489                         "intel_iommu_domain_init: dmar_domain == NULL\n");
3490                 return -ENOMEM;
3491         }
3492         if (md_domain_init(dmar_domain, DEFAULT_DOMAIN_ADDRESS_WIDTH)) {
3493                 printk(KERN_ERR
3494                         "intel_iommu_domain_init() failed\n");
3495                 vm_domain_exit(dmar_domain);
3496                 return -ENOMEM;
3497         }
3498         domain->priv = dmar_domain;
3499
3500         return 0;
3501 }
3502
3503 static void intel_iommu_domain_destroy(struct iommu_domain *domain)
3504 {
3505         struct dmar_domain *dmar_domain = domain->priv;
3506
3507         domain->priv = NULL;
3508         vm_domain_exit(dmar_domain);
3509 }
3510
3511 static int intel_iommu_attach_device(struct iommu_domain *domain,
3512                                      struct device *dev)
3513 {
3514         struct dmar_domain *dmar_domain = domain->priv;
3515         struct pci_dev *pdev = to_pci_dev(dev);
3516         struct intel_iommu *iommu;
3517         int addr_width;
3518         u64 end;
3519         int ret;
3520
3521         /* normally pdev is not mapped */
3522         if (unlikely(domain_context_mapped(pdev))) {
3523                 struct dmar_domain *old_domain;
3524
3525                 old_domain = find_domain(pdev);
3526                 if (old_domain) {
3527                         if (dmar_domain->flags & DOMAIN_FLAG_VIRTUAL_MACHINE ||
3528                             dmar_domain->flags & DOMAIN_FLAG_STATIC_IDENTITY)
3529                                 domain_remove_one_dev_info(old_domain, pdev);
3530                         else
3531                                 domain_remove_dev_info(old_domain);
3532                 }
3533         }
3534
3535         iommu = device_to_iommu(pci_domain_nr(pdev->bus), pdev->bus->number,
3536                                 pdev->devfn);
3537         if (!iommu)
3538                 return -ENODEV;
3539
3540         /* check if this iommu agaw is sufficient for max mapped address */
3541         addr_width = agaw_to_width(iommu->agaw);
3542         end = DOMAIN_MAX_ADDR(addr_width);
3543         end = end & VTD_PAGE_MASK;
3544         if (end < dmar_domain->max_addr) {
3545                 printk(KERN_ERR "%s: iommu agaw (%d) is not "
3546                        "sufficient for the mapped address (%llx)\n",
3547                        __func__, iommu->agaw, dmar_domain->max_addr);
3548                 return -EFAULT;
3549         }
3550
3551         ret = domain_add_dev_info(dmar_domain, pdev);
3552         if (ret)
3553                 return ret;
3554
3555         ret = domain_context_mapping(dmar_domain, pdev, CONTEXT_TT_MULTI_LEVEL);
3556         return ret;
3557 }
3558
3559 static void intel_iommu_detach_device(struct iommu_domain *domain,
3560                                       struct device *dev)
3561 {
3562         struct dmar_domain *dmar_domain = domain->priv;
3563         struct pci_dev *pdev = to_pci_dev(dev);
3564
3565         domain_remove_one_dev_info(dmar_domain, pdev);
3566 }
3567
3568 static int intel_iommu_map_range(struct iommu_domain *domain,
3569                                  unsigned long iova, phys_addr_t hpa,
3570                                  size_t size, int iommu_prot)
3571 {
3572         struct dmar_domain *dmar_domain = domain->priv;
3573         u64 max_addr;
3574         int addr_width;
3575         int prot = 0;
3576         int ret;
3577
3578         if (iommu_prot & IOMMU_READ)
3579                 prot |= DMA_PTE_READ;
3580         if (iommu_prot & IOMMU_WRITE)
3581                 prot |= DMA_PTE_WRITE;
3582         if ((iommu_prot & IOMMU_CACHE) && dmar_domain->iommu_snooping)
3583                 prot |= DMA_PTE_SNP;
3584
3585         max_addr = iova + size;
3586         if (dmar_domain->max_addr < max_addr) {
3587                 int min_agaw;
3588                 u64 end;
3589
3590                 /* check if minimum agaw is sufficient for mapped address */
3591                 min_agaw = vm_domain_min_agaw(dmar_domain);
3592                 addr_width = agaw_to_width(min_agaw);
3593                 end = DOMAIN_MAX_ADDR(addr_width);
3594                 end = end & VTD_PAGE_MASK;
3595                 if (end < max_addr) {
3596                         printk(KERN_ERR "%s: iommu agaw (%d) is not "
3597                                "sufficient for the mapped address (%llx)\n",
3598                                __func__, min_agaw, max_addr);
3599                         return -EFAULT;
3600                 }
3601                 dmar_domain->max_addr = max_addr;
3602         }
3603         /* Round up size to next multiple of PAGE_SIZE, if it and
3604            the low bits of hpa would take us onto the next page */
3605         size = aligned_nrpages(hpa, size);
3606         ret = domain_pfn_mapping(dmar_domain, iova >> VTD_PAGE_SHIFT,
3607                                  hpa >> VTD_PAGE_SHIFT, size, prot);
3608         return ret;
3609 }
3610
3611 static void intel_iommu_unmap_range(struct iommu_domain *domain,
3612                                     unsigned long iova, size_t size)
3613 {
3614         struct dmar_domain *dmar_domain = domain->priv;
3615
3616         if (!size)
3617                 return;
3618
3619         dma_pte_clear_range(dmar_domain, iova >> VTD_PAGE_SHIFT,
3620                             (iova + size - 1) >> VTD_PAGE_SHIFT);
3621
3622         if (dmar_domain->max_addr == iova + size)
3623                 dmar_domain->max_addr = iova;
3624 }
3625
3626 static phys_addr_t intel_iommu_iova_to_phys(struct iommu_domain *domain,
3627                                             unsigned long iova)
3628 {
3629         struct dmar_domain *dmar_domain = domain->priv;
3630         struct dma_pte *pte;
3631         u64 phys = 0;
3632
3633         pte = pfn_to_dma_pte(dmar_domain, iova >> VTD_PAGE_SHIFT);
3634         if (pte)
3635                 phys = dma_pte_addr(pte);
3636
3637         return phys;
3638 }
3639
3640 static int intel_iommu_domain_has_cap(struct iommu_domain *domain,
3641                                       unsigned long cap)
3642 {
3643         struct dmar_domain *dmar_domain = domain->priv;
3644
3645         if (cap == IOMMU_CAP_CACHE_COHERENCY)
3646                 return dmar_domain->iommu_snooping;
3647
3648         return 0;
3649 }
3650
3651 static struct iommu_ops intel_iommu_ops = {
3652         .domain_init    = intel_iommu_domain_init,
3653         .domain_destroy = intel_iommu_domain_destroy,
3654         .attach_dev     = intel_iommu_attach_device,
3655         .detach_dev     = intel_iommu_detach_device,
3656         .map            = intel_iommu_map_range,
3657         .unmap          = intel_iommu_unmap_range,
3658         .iova_to_phys   = intel_iommu_iova_to_phys,
3659         .domain_has_cap = intel_iommu_domain_has_cap,
3660 };
3661
3662 static void __devinit quirk_iommu_rwbf(struct pci_dev *dev)
3663 {
3664         /*
3665          * Mobile 4 Series Chipset neglects to set RWBF capability,
3666          * but needs it:
3667          */
3668         printk(KERN_INFO "DMAR: Forcing write-buffer flush capability\n");
3669         rwbf_quirk = 1;
3670 }
3671
3672 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2a40, quirk_iommu_rwbf);